git.iko.soy/typeable/oauth2-proxy
on v1.1 help sign in
typeable/oauth2-proxy/oauthproxy.go
513 lines 13 kB history raw
1package main
3import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "html/template"
9 "io/ioutil"
10 "log"
11 "net"
12 "net/http"
13 "net/http/httputil"
14 "net/url"
15 "regexp"
16 "strings"
17 "time"
19 "github.com/bitly/go-simplejson"
22const pingPath = "/ping"
23const signInPath = "/oauth2/sign_in"
24const oauthStartPath = "/oauth2/start"
25const oauthCallbackPath = "/oauth2/callback"
27type OauthProxy struct {
28 CookieSeed string
29 CookieKey string
30 CookieDomain string
31 CookieSecure bool
32 CookieHttpOnly bool
33 CookieExpire time.Duration
34 Validator func(string) bool
36 redirectUrl *url.URL // the url to receive requests at
37 oauthRedemptionUrl *url.URL // endpoint to redeem the code
38 oauthLoginUrl *url.URL // to redirect the user to
39 oauthScope string
40 clientID string
41 clientSecret string
42 SignInMessage string
43 HtpasswdFile *HtpasswdFile
44 DisplayHtpasswdForm bool
45 serveMux http.Handler
46 PassBasicAuth bool
47 skipAuthRegex []string
48 compiledRegex []*regexp.Regexp
49 templates *template.Template
52type UpstreamProxy struct {
53 upstream string
54 handler http.Handler
57func (u *UpstreamProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
58 w.Header().Set("GAP-Upstream-Address", u.upstream)
59 u.handler.ServeHTTP(w, r)
62func NewReverseProxy(target *url.URL) (proxy *httputil.ReverseProxy) {
63 return httputil.NewSingleHostReverseProxy(target)
65func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
66 director := proxy.Director
67 proxy.Director = func(req *http.Request) {
68 director(req)
69 // use RequestURI so that we aren't unescaping encoded slashes in the request path
70 req.URL.Opaque = fmt.Sprintf("//%s%s", target.Host, req.RequestURI)
71 req.URL.RawQuery = ""
72 }
74func setProxyDirector(proxy *httputil.ReverseProxy) {
75 director := proxy.Director
76 proxy.Director = func(req *http.Request) {
77 director(req)
78 // use RequestURI so that we aren't unescaping encoded slashes in the request path
79 req.URL.Opaque = fmt.Sprintf("//%s%s", req.URL.Host, req.RequestURI)
80 req.URL.RawQuery = ""
81 }
84func NewOauthProxy(opts *Options, validator func(string) bool) *OauthProxy {
85 login, _ := url.Parse("https://accounts.google.com/o/oauth2/auth")
86 redeem, _ := url.Parse("https://accounts.google.com/o/oauth2/token")
87 serveMux := http.NewServeMux()
88 for _, u := range opts.proxyUrls {
89 path := u.Path
90 u.Path = ""
91 log.Printf("mapping path %q => upstream %q", path, u)
92 proxy := NewReverseProxy(u)
93 if !opts.PassHostHeader {
94 setProxyUpstreamHostHeader(proxy, u)
95 } else {
96 setProxyDirector(proxy)
97 }
98 serveMux.Handle(path, &UpstreamProxy{u.Host, proxy})
99 }
100 for _, u := range opts.CompiledRegex {
101 log.Printf("compiled skip-auth-regex => %q", u)
102 }
104 redirectUrl := opts.redirectUrl
105 redirectUrl.Path = oauthCallbackPath
107 log.Printf("OauthProxy configured for %s", opts.ClientID)
108 domain := opts.CookieDomain
109 if domain == "" {
110 domain = "<default>"
111 }
112 if !opts.CookieHttpsOnly {
113 log.Printf("Warning: cookie-https-only setting is deprecated and will be removed in a future version. use cookie-secure")
114 opts.CookieSecure = opts.CookieHttpsOnly
115 }
117 log.Printf("Cookie settings: secure (https):%v httponly:%v expiry:%s domain:%s", opts.CookieSecure, opts.CookieHttpOnly, opts.CookieExpire, domain)
119 return &OauthProxy{
120 CookieKey: "_oauthproxy",
121 CookieSeed: opts.CookieSecret,
122 CookieDomain: opts.CookieDomain,
123 CookieSecure: opts.CookieSecure,
124 CookieHttpOnly: opts.CookieHttpOnly,
125 CookieExpire: opts.CookieExpire,
126 Validator: validator,
128 clientID: opts.ClientID,
129 clientSecret: opts.ClientSecret,
130 oauthScope: "profile email",
131 oauthRedemptionUrl: redeem,
132 oauthLoginUrl: login,
133 serveMux: serveMux,
134 redirectUrl: redirectUrl,
135 skipAuthRegex: opts.SkipAuthRegex,
136 compiledRegex: opts.CompiledRegex,
137 PassBasicAuth: opts.PassBasicAuth,
138 templates: loadTemplates(opts.CustomTemplatesDir),
139 }
142func (p *OauthProxy) GetRedirectUrl(host string) string {
143 // default to the request Host if not set
144 if p.redirectUrl.Host != "" {
145 return p.redirectUrl.String()
146 }
147 var u url.URL
148 u = *p.redirectUrl
149 if u.Scheme == "" {
150 if p.CookieSecure {
151 u.Scheme = "https"
152 } else {
153 u.Scheme = "http"
154 }
155 }
156 u.Host = host
157 return u.String()
160func (p *OauthProxy) GetLoginURL(host, redirect string) string {
161 params := url.Values{}
162 params.Add("redirect_uri", p.GetRedirectUrl(host))
163 params.Add("approval_prompt", "force")
164 params.Add("scope", p.oauthScope)
165 params.Add("client_id", p.clientID)
166 params.Add("response_type", "code")
167 if strings.HasPrefix(redirect, "/") {
168 params.Add("state", redirect)
169 }
170 return fmt.Sprintf("%s?%s", p.oauthLoginUrl, params.Encode())
173func apiRequest(req *http.Request) (*simplejson.Json, error) {
174 httpclient := &http.Client{}
175 resp, err := httpclient.Do(req)
176 if err != nil {
177 return nil, err
178 }
179 body, err := ioutil.ReadAll(resp.Body)
180 resp.Body.Close()
181 if err != nil {
182 return nil, err
183 }
184 if resp.StatusCode != 200 {
185 log.Printf("got response code %d - %s", resp.StatusCode, body)
186 return nil, errors.New("api request returned non 200 status code")
187 }
188 data, err := simplejson.NewJson(body)
189 if err != nil {
190 return nil, err
191 }
192 return data, nil
195func (p *OauthProxy) displayCustomLoginForm() bool {
196 return p.HtpasswdFile != nil && p.DisplayHtpasswdForm
199func (p *OauthProxy) redeemCode(host, code string) (string, string, error) {
200 if code == "" {
201 return "", "", errors.New("missing code")
202 }
203 params := url.Values{}
204 params.Add("redirect_uri", p.GetRedirectUrl(host))
205 params.Add("client_id", p.clientID)
206 params.Add("client_secret", p.clientSecret)
207 params.Add("code", code)
208 params.Add("grant_type", "authorization_code")
209 req, err := http.NewRequest("POST", p.oauthRedemptionUrl.String(), bytes.NewBufferString(params.Encode()))
210 if err != nil {
211 log.Printf("failed building request %s", err.Error())
212 return "", "", err
213 }
214 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
215 json, err := apiRequest(req)
216 if err != nil {
217 log.Printf("failed making request %s", err)
218 return "", "", err
219 }
220 access_token, err := json.Get("access_token").String()
221 if err != nil {
222 return "", "", err
223 }
225 idToken, err := json.Get("id_token").String()
226 if err != nil {
227 return "", "", err
228 }
230 // id_token is a base64 encode ID token payload
231 // https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
232 jwt := strings.Split(idToken, ".")
233 b, err := jwtDecodeSegment(jwt[1])
234 if err != nil {
235 return "", "", err
236 }
237 data, err := simplejson.NewJson(b)
238 if err != nil {
239 return "", "", err
240 }
241 email, err := data.Get("email").String()
242 if err != nil {
243 return "", "", err
244 }
246 return access_token, email, nil
249func jwtDecodeSegment(seg string) ([]byte, error) {
250 if l := len(seg) % 4; l > 0 {
251 seg += strings.Repeat("=", 4-l)
252 }
254 return base64.URLEncoding.DecodeString(seg)
257func (p *OauthProxy) ClearCookie(rw http.ResponseWriter, req *http.Request) {
258 domain := req.Host
259 if h, _, err := net.SplitHostPort(domain); err == nil {
260 domain = h
261 }
262 if p.CookieDomain != "" {
263 if !strings.HasSuffix(domain, p.CookieDomain) {
264 log.Printf("Warning: request host is %q but using configured cookie domain of %q", domain, p.CookieDomain)
265 }
266 domain = p.CookieDomain
267 }
268 cookie := &http.Cookie{
269 Name: p.CookieKey,
270 Value: "",
271 Path: "/",
272 Domain: domain,
273 HttpOnly: p.CookieHttpOnly,
274 Secure: p.CookieSecure,
275 Expires: time.Now().Add(time.Duration(1) * time.Hour * -1),
276 }
277 http.SetCookie(rw, cookie)
280func (p *OauthProxy) SetCookie(rw http.ResponseWriter, req *http.Request, val string) {
282 domain := req.Host
283 if h, _, err := net.SplitHostPort(domain); err == nil {
284 domain = h
285 }
286 if p.CookieDomain != "" {
287 if !strings.HasSuffix(domain, p.CookieDomain) {
288 log.Printf("Warning: request host is %q but using configured cookie domain of %q", domain, p.CookieDomain)
289 }
290 domain = p.CookieDomain
291 }
292 cookie := &http.Cookie{
293 Name: p.CookieKey,
294 Value: signedCookieValue(p.CookieSeed, p.CookieKey, val),
295 Path: "/",
296 Domain: domain,
297 HttpOnly: p.CookieHttpOnly,
298 Secure: p.CookieSecure,
299 Expires: time.Now().Add(p.CookieExpire),
300 }
301 http.SetCookie(rw, cookie)
304func (p *OauthProxy) PingPage(rw http.ResponseWriter) {
305 rw.WriteHeader(http.StatusOK)
306 fmt.Fprintf(rw, "OK")
309func (p *OauthProxy) ErrorPage(rw http.ResponseWriter, code int, title string, message string) {
310 log.Printf("ErrorPage %d %s %s", code, title, message)
311 rw.WriteHeader(code)
312 t := struct {
313 Title string
314 Message string
315 }{
316 Title: fmt.Sprintf("%d %s", code, title),
317 Message: message,
318 }
319 p.templates.ExecuteTemplate(rw, "error.html", t)
322func (p *OauthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) {
323 p.ClearCookie(rw, req)
324 rw.WriteHeader(code)
326 t := struct {
327 SignInMessage string
328 CustomLogin bool
329 Redirect string
330 Version string
331 }{
332 SignInMessage: p.SignInMessage,
333 CustomLogin: p.displayCustomLoginForm(),
334 Redirect: req.URL.RequestURI(),
335 Version: VERSION,
336 }
337 p.templates.ExecuteTemplate(rw, "sign_in.html", t)
340func (p *OauthProxy) ManualSignIn(rw http.ResponseWriter, req *http.Request) (string, bool) {
341 if req.Method != "POST" || p.HtpasswdFile == nil {
342 return "", false
343 }
344 user := req.FormValue("username")
345 passwd := req.FormValue("password")
346 if user == "" {
347 return "", false
348 }
349 // check auth
350 if p.HtpasswdFile.Validate(user, passwd) {
351 log.Printf("authenticated %q via HtpasswdFile", user)
352 return user, true
353 }
354 return "", false
357func (p *OauthProxy) GetRedirect(req *http.Request) (string, error) {
358 err := req.ParseForm()
360 if err != nil {
361 return "", err
362 }
364 redirect := req.FormValue("rd")
366 if redirect == "" {
367 redirect = "/"
368 }
370 return redirect, err
373func (p *OauthProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
374 // check if this is a redirect back at the end of oauth
375 remoteAddr := req.RemoteAddr
376 if req.Header.Get("X-Real-IP") != "" {
377 remoteAddr += fmt.Sprintf(" (%q)", req.Header.Get("X-Real-IP"))
378 }
380 var ok bool
381 var user string
382 var email string
384 if req.URL.Path == pingPath {
385 p.PingPage(rw)
386 return
387 }
389 for _, u := range p.compiledRegex {
390 match := u.MatchString(req.URL.Path)
391 if match {
392 p.serveMux.ServeHTTP(rw, req)
393 return
394 }
396 }
398 if req.URL.Path == signInPath {
399 redirect, err := p.GetRedirect(req)
400 if err != nil {
401 p.ErrorPage(rw, 500, "Internal Error", err.Error())
402 return
403 }
405 user, ok = p.ManualSignIn(rw, req)
406 if ok {
407 p.SetCookie(rw, req, user)
408 http.Redirect(rw, req, redirect, 302)
409 } else {
410 p.SignInPage(rw, req, 200)
411 }
412 return
413 }
414 if req.URL.Path == oauthStartPath {
415 redirect, err := p.GetRedirect(req)
416 if err != nil {
417 p.ErrorPage(rw, 500, "Internal Error", err.Error())
418 return
419 }
420 http.Redirect(rw, req, p.GetLoginURL(req.Host, redirect), 302)
421 return
422 }
423 if req.URL.Path == oauthCallbackPath {
424 // finish the oauth cycle
425 err := req.ParseForm()
426 if err != nil {
427 p.ErrorPage(rw, 500, "Internal Error", err.Error())
428 return
429 }
430 errorString := req.Form.Get("error")
431 if errorString != "" {
432 p.ErrorPage(rw, 403, "Permission Denied", errorString)
433 return
434 }
436 _, email, err := p.redeemCode(req.Host, req.Form.Get("code"))
437 if err != nil {
438 log.Printf("%s error redeeming code %s", remoteAddr, err)
439 p.ErrorPage(rw, 500, "Internal Error", err.Error())
440 return
441 }
443 redirect := req.Form.Get("state")
444 if redirect == "" {
445 redirect = "/"
446 }
448 // set cookie, or deny
449 if p.Validator(email) {
450 log.Printf("%s authenticating %s completed", remoteAddr, email)
451 p.SetCookie(rw, req, email)
452 http.Redirect(rw, req, redirect, 302)
453 return
454 } else {
455 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
456 return
457 }
458 }
460 if !ok {
461 cookie, err := req.Cookie(p.CookieKey)
462 if err == nil {
463 email, ok = validateCookie(cookie, p.CookieSeed)
464 user = strings.Split(email, "@")[0]
465 }
466 }
468 if !ok {
469 user, ok = p.CheckBasicAuth(req)
470 }
472 if !ok {
473 p.SignInPage(rw, req, 403)
474 return
475 }
477 // At this point, the user is authenticated. proxy normally
478 if p.PassBasicAuth {
479 req.SetBasicAuth(user, "")
480 req.Header["X-Forwarded-User"] = []string{user}
481 req.Header["X-Forwarded-Email"] = []string{email}
482 }
483 if email == "" {
484 rw.Header().Set("GAP-Auth", user)
485 } else {
486 rw.Header().Set("GAP-Auth", email)
487 }
489 p.serveMux.ServeHTTP(rw, req)
492func (p *OauthProxy) CheckBasicAuth(req *http.Request) (string, bool) {
493 if p.HtpasswdFile == nil {
494 return "", false
495 }
496 s := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
497 if len(s) != 2 || s[0] != "Basic" {
498 return "", false
499 }
500 b, err := base64.StdEncoding.DecodeString(s[1])
501 if err != nil {
502 return "", false
503 }
504 pair := strings.SplitN(string(b), ":", 2)
505 if len(pair) != 2 {
506 return "", false
507 }
508 if p.HtpasswdFile.Validate(pair[0], pair[1]) {
509 log.Printf("authenticated %q via basic auth", pair[0])
510 return pair[0], true
511 }
512 return "", false