package server import ( "html" "net/http" "sync" "time" ) const oauthRelayTTL = 5 * time.Minute type oauthRelayEntry struct { code string expiresAt time.Time } type oauthRelayStore struct { mu sync.Mutex entries map[string]oauthRelayEntry ttl time.Duration now func() time.Time } func newOAuthRelayStore() *oauthRelayStore { return &oauthRelayStore{ entries: make(map[string]oauthRelayEntry), ttl: oauthRelayTTL, now: time.Now, } } func (o *oauthRelayStore) Set(state, code string) { o.mu.Lock() defer o.mu.Unlock() now := o.now() o.pruneLocked(now) o.entries[state] = oauthRelayEntry{ code: code, expiresAt: now.Add(o.ttl), } } func (o *oauthRelayStore) Take(state string) (string, bool) { o.mu.Lock() defer o.mu.Unlock() now := o.now() o.pruneLocked(now) entry, ok := o.entries[state] if !ok { return "", false } delete(o.entries, state) if now.After(entry.expiresAt) { return "", false } return entry.code, true } func (o *oauthRelayStore) pruneLocked(now time.Time) { for k, v := range o.entries { if now.After(v.expiresAt) { delete(o.entries, k) } } } func (s *Server) handleOAuthCallback(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() if errParam := q.Get("error"); errParam != "" { desc := q.Get("error_description") if desc == "" { desc = errParam } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusBadRequest) _, _ = w.Write([]byte(`Authorization Failed

Authorization Failed

` + html.EscapeString(desc) + `

`)) return } state := q.Get("state") code := q.Get("code") if state == "" || code == "" { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusBadRequest) _, _ = w.Write([]byte(`Invalid OAuth Callback

Invalid OAuth Callback

Missing required code or state query parameter.

`)) return } s.oauth.Set(state, code) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`Authorized

Authorized!

Authorized! You can close this tab.

`)) } func (s *Server) handleOAuthPoll(w http.ResponseWriter, r *http.Request) { state := r.URL.Query().Get("state") if state == "" { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "state is required"}) return } code, ok := s.oauth.Take(state) if !ok { writeJSON(w, http.StatusAccepted, map[string]string{"status": "pending"}) return } writeJSON(w, http.StatusOK, map[string]string{ "status": "ready", "code": code, }) }