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 {
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
43 HtpasswdFile *HtpasswdFile
44 DisplayHtpasswdForm bool
47 skipAuthRegex []string
48 compiledRegex []*regexp.Regexp
49 templates *template.Template
52type UpstreamProxy struct {
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) {
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)
74func setProxyDirector(proxy *httputil.ReverseProxy) {
75 director := proxy.Director
76 proxy.Director = func(req *http.Request) {
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)
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 {
91 log.Printf("mapping path %q => upstream %q", path, u)
92 proxy := NewReverseProxy(u)
93 if !opts.PassHostHeader {
94 setProxyUpstreamHostHeader(proxy, u)
96 setProxyDirector(proxy)
98 serveMux.Handle(path, &UpstreamProxy{u.Host, proxy})
100 for _, u := range opts.CompiledRegex {
101 log.Printf("compiled skip-auth-regex => %q", u)
104 redirectUrl := opts.redirectUrl
105 redirectUrl.Path = oauthCallbackPath
107 log.Printf("OauthProxy configured for %s", opts.ClientID)
108 domain := opts.CookieDomain
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
117 log.Printf("Cookie settings: secure (https):%v httponly:%v expiry:%s domain:%s", opts.CookieSecure, opts.CookieHttpOnly, opts.CookieExpire, domain)
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,
134 redirectUrl: redirectUrl,
135 skipAuthRegex: opts.SkipAuthRegex,
136 compiledRegex: opts.CompiledRegex,
137 PassBasicAuth: opts.PassBasicAuth,
138 templates: loadTemplates(opts.CustomTemplatesDir),
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()
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)
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)
179 body, err := ioutil.ReadAll(resp.Body)
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")
188 data, err := simplejson.NewJson(body)
195func (p *OauthProxy) displayCustomLoginForm() bool {
196 return p.HtpasswdFile != nil && p.DisplayHtpasswdForm
199func (p *OauthProxy) redeemCode(host, code string) (string, string, error) {
201 return "", "", errors.New("missing code")
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()))
211 log.Printf("failed building request %s", err.Error())
214 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
215 json, err := apiRequest(req)
217 log.Printf("failed making request %s", err)
220 access_token, err := json.Get("access_token").String()
225 idToken, err := json.Get("id_token").String()
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])
237 data, err := simplejson.NewJson(b)
241 email, err := data.Get("email").String()
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)
254 return base64.URLEncoding.DecodeString(seg)
257func (p *OauthProxy) ClearCookie(rw http.ResponseWriter, req *http.Request) {
259 if h, _, err := net.SplitHostPort(domain); err == nil {
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)
266 domain = p.CookieDomain
268 cookie := &http.Cookie{
273 HttpOnly: p.CookieHttpOnly,
274 Secure: p.CookieSecure,
275 Expires: time.Now().Add(time.Duration(1) * time.Hour * -1),
277 http.SetCookie(rw, cookie)
280func (p *OauthProxy) SetCookie(rw http.ResponseWriter, req *http.Request, val string) {
283 if h, _, err := net.SplitHostPort(domain); err == nil {
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)
290 domain = p.CookieDomain
292 cookie := &http.Cookie{
294 Value: signedCookieValue(p.CookieSeed, p.CookieKey, val),
297 HttpOnly: p.CookieHttpOnly,
298 Secure: p.CookieSecure,
299 Expires: time.Now().Add(p.CookieExpire),
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)
316 Title: fmt.Sprintf("%d %s", code, title),
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)
332 SignInMessage: p.SignInMessage,
333 CustomLogin: p.displayCustomLoginForm(),
334 Redirect: req.URL.RequestURI(),
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 {
344 user := req.FormValue("username")
345 passwd := req.FormValue("password")
350 if p.HtpasswdFile.Validate(user, passwd) {
351 log.Printf("authenticated %q via HtpasswdFile", user)
357func (p *OauthProxy) GetRedirect(req *http.Request) (string, error) {
358 err := req.ParseForm()
364 redirect := req.FormValue("rd")
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"))
384 if req.URL.Path == pingPath {
389 for _, u := range p.compiledRegex {
390 match := u.MatchString(req.URL.Path)
392 p.serveMux.ServeHTTP(rw, req)
398 if req.URL.Path == signInPath {
399 redirect, err := p.GetRedirect(req)
401 p.ErrorPage(rw, 500, "Internal Error", err.Error())
405 user, ok = p.ManualSignIn(rw, req)
407 p.SetCookie(rw, req, user)
408 http.Redirect(rw, req, redirect, 302)
410 p.SignInPage(rw, req, 200)
414 if req.URL.Path == oauthStartPath {
415 redirect, err := p.GetRedirect(req)
417 p.ErrorPage(rw, 500, "Internal Error", err.Error())
420 http.Redirect(rw, req, p.GetLoginURL(req.Host, redirect), 302)
423 if req.URL.Path == oauthCallbackPath {
424 // finish the oauth cycle
425 err := req.ParseForm()
427 p.ErrorPage(rw, 500, "Internal Error", err.Error())
430 errorString := req.Form.Get("error")
431 if errorString != "" {
432 p.ErrorPage(rw, 403, "Permission Denied", errorString)
436 _, email, err := p.redeemCode(req.Host, req.Form.Get("code"))
438 log.Printf("%s error redeeming code %s", remoteAddr, err)
439 p.ErrorPage(rw, 500, "Internal Error", err.Error())
443 redirect := req.Form.Get("state")
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)
455 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
461 cookie, err := req.Cookie(p.CookieKey)
463 email, ok = validateCookie(cookie, p.CookieSeed)
464 user = strings.Split(email, "@")[0]
469 user, ok = p.CheckBasicAuth(req)
473 p.SignInPage(rw, req, 403)
477 // At this point, the user is authenticated. proxy normally
479 req.SetBasicAuth(user, "")
480 req.Header["X-Forwarded-User"] = []string{user}
481 req.Header["X-Forwarded-Email"] = []string{email}
484 rw.Header().Set("GAP-Auth", user)
486 rw.Header().Set("GAP-Auth", email)
489 p.serveMux.ServeHTTP(rw, req)
492func (p *OauthProxy) CheckBasicAuth(req *http.Request) (string, bool) {
493 if p.HtpasswdFile == nil {
496 s := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
497 if len(s) != 2 || s[0] != "Basic" {
500 b, err := base64.StdEncoding.DecodeString(s[1])
504 pair := strings.SplitN(string(b), ":", 2)
508 if p.HtpasswdFile.Validate(pair[0], pair[1]) {
509 log.Printf("authenticated %q via basic auth", pair[0])
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list