forked from discourse/discourse-auth-proxy
/
main.go
199 lines (155 loc) · 4.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package main
import (
"code.google.com/p/go-uuid/uuid"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/golang/groupcache/lru"
"github.com/namsral/flag"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
var nonceCache = lru.New(20)
func main() {
proxyUriPtr := flag.String("proxy-url", "", "uri to listen on eg: http://proxy.com")
originUriPtr := flag.String("origin-url", "", "origin to proxy eg: http://origin.com")
ssoSecretPtr := flag.String("sso-secret", "", "SSO secret for origin")
ssoUriPtr := flag.String("sso-url", "", "SSO endpoint eg: http://discourse.forum.com")
flag.Parse()
originUrl, err := url.Parse(*originUriPtr)
if err != nil {
flag.Usage()
log.Fatal("invalid origin url")
}
_, err = url.Parse(*ssoUriPtr)
if err != nil {
flag.Usage()
log.Fatal("invalid sso url, should point at Discourse site with enable sso")
}
proxyUrl, err2 := url.Parse(*proxyUriPtr)
if err2 != nil {
flag.Usage()
log.Fatal("invalid proxy uri")
}
if *proxyUriPtr == "" || *originUriPtr == "" || *ssoSecretPtr == "" || *ssoUriPtr == "" {
flag.Usage()
os.Exit(1)
return
}
cookieSecret := uuid.New()
proxy := httputil.NewSingleHostReverseProxy(originUrl)
handler := redirectIfCookieMissing(proxy, *ssoSecretPtr, cookieSecret, *ssoUriPtr)
server := &http.Server{
Addr: proxyUrl.Host,
Handler: handler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(server.ListenAndServe())
}
func envOrFlag(name, help string) string {
flag.String(name, "", help)
return ""
}
func redirectIfCookieMissing(handler http.Handler, ssoSecret, cookieSecret, ssoUri string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("__discourse_proxy")
var username string
if err == nil && cookie != nil {
username, err = parseCookie(cookie.Value, cookieSecret)
}
if err == nil {
r.Header.Set("Discourse-User-Name", username)
handler.ServeHTTP(w, r)
return
}
query := r.URL.Query()
sso := query.Get("sso")
sig := query.Get("sig")
if len(sso) == 0 {
url := ssoUri + "/session/sso_provider?" + sso_payload(ssoSecret, "http://"+r.Host, r.URL.String())
http.Redirect(w, r, url, 302)
} else {
decoded, _ := base64.StdEncoding.DecodeString(sso)
decodedString := string(decoded)
parsedQuery, _ := url.ParseQuery(decodedString)
username := parsedQuery["username"]
admin := parsedQuery["admin"]
nonce := parsedQuery["nonce"]
if len(nonce) > 0 && len(admin) > 0 && len(username) > 0 && admin[0] == "true" {
returnUrl, err := getReturnUrl(ssoSecret, sso, sig, nonce[0])
if err != nil {
fmt.Fprintf(w, "Invalid request")
return
}
// we have a valid auth
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "__discourse_proxy", Value: signCookie(username[0], cookieSecret), Expires: expiration, HttpOnly: true}
http.SetCookie(w, &cookie)
// works around weird safari stuff
fmt.Fprintf(w, "<html><head></head><body><script>window.location = '%v'</script></body>", returnUrl)
}
}
})
}
func getReturnUrl(secret string, payload string, sig string, nonce string) (returnUrl string, err error) {
value, gotNonce := nonceCache.Get(nonce)
returnUrl = value.(string)
nonceCache.Remove(nonce)
valid := ComputeHmac256(payload, secret) == sig && gotNonce
if !valid {
err = fmt.Errorf("Signature is invalid")
}
return
}
func sameHost(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = r.URL.Host
handler.ServeHTTP(w, r)
})
}
func signCookie(data, secret string) string {
return data + "," + ComputeHmac256(data, secret)
}
func parseCookie(data, secret string) (parsed string, err error) {
err = nil
parsed = ""
split := strings.Split(data, ",")
if len(split) < 2 {
err = fmt.Errorf("Expecting a semi column in cookie")
return
}
signature := split[len(split)-1]
parsed = strings.Join(split[:len(split)-1], ",")
expected := ComputeHmac256(parsed, secret)
if expected != signature {
parsed = ""
err = fmt.Errorf("Expecting signature to match")
return
}
return
}
func sso_payload(secret string, return_sso_url string, returnUrl string) string {
result := "return_sso_url=" + return_sso_url + "&nonce=" + addNonce(returnUrl)
payload := base64.StdEncoding.EncodeToString([]byte(result))
return "sso=" + payload + "&sig=" + ComputeHmac256(payload, secret)
}
func addNonce(returnUrl string) string {
guid := uuid.New()
nonceCache.Add(guid, returnUrl)
return guid
}
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return hex.EncodeToString(h.Sum(nil))
}