// SPDX-License-Identifier: AGPL-3.0-or-later // Package oauth signs people in to Google and Microsoft for the services // Docwell reads on their behalf (Google Calendar, OneNote): the // authorization-code flow of a confidential client, with a signed state // that carries who asked and why, and token refresh. package oauth import ( "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" ) // Provider is an OAuth app at one identity provider. type Provider struct { // Name is how routes and states name it ("google", "microsoft"). Name string ClientID string ClientSecret string AuthURL string TokenURL string // Extra goes into the authorization URL (access_type=offline, prompt=…). Extra url.Values } // Enabled reports whether the app is configured. func (p Provider) Enabled() bool { return p.ClientID != "" && p.ClientSecret != "" } // The providers' sign-in endpoints. Variables only so a test build can // point them at a stand-in (go build -ldflags "-X …"). var ( GoogleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth" GoogleTokenURL = "https://oauth2.googleapis.com/token" MicrosoftLogin = "https://login.microsoftonline.com" ) // Google is Google's OAuth endpoints for app id and secret. func Google(id, secret string) Provider { return Provider{ //nolint:gosec // endpoints, not credentials Name: "google", ClientID: id, ClientSecret: secret, AuthURL: GoogleAuthURL, TokenURL: GoogleTokenURL, // A refresh token every time, so a reconnect replaces a revoked one. Extra: url.Values{"access_type": {"offline"}, "prompt": {"consent"}, "include_granted_scopes": {"true"}}, } } // Microsoft is the Microsoft identity platform (v2) for tenant ("common" // for any work, school or personal account). func Microsoft(id, secret, tenant string) Provider { if tenant == "" { tenant = "common" } base := MicrosoftLogin + "/" + url.PathEscape(tenant) + "/oauth2/v2.0" return Provider{ Name: "microsoft", ClientID: id, ClientSecret: secret, AuthURL: base + "/authorize", TokenURL: base + "/token", Extra: url.Values{"prompt": {"select_account"}}, } } // AuthCodeURL is where the browser goes to sign in and allow scopes. func (p Provider) AuthCodeURL(state, redirect string, scopes []string) string { q := url.Values{ "client_id": {p.ClientID}, "redirect_uri": {redirect}, "response_type": {"code"}, "scope": {strings.Join(scopes, " ")}, "state": {state}, } for k, v := range p.Extra { q[k] = v } return p.AuthURL + "?" + q.Encode() } // Token is what the token endpoint answers. type Token struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` ExpiresIn int `json:"expires_in"` IDToken string `json:"id_token"` Scope string `json:"scope"` // Expires is when AccessToken stops working (set by Exchange and Refresh). Expires time.Time `json:"-"` } // ErrRevoked is returned when the provider refuses a refresh token: the // person removed Docwell's access, or it expired. var ErrRevoked = errors.New("the sign-in was revoked or expired; connect the account again") func (p Provider) token(ctx context.Context, client *http.Client, form url.Values) (Token, error) { form.Set("client_id", p.ClientID) form.Set("client_secret", p.ClientSecret) req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.TokenURL, strings.NewReader(form.Encode())) if err != nil { return Token{}, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") res, err := client.Do(req) if err != nil { return Token{}, fmt.Errorf("%s did not answer: %w", p.Name, err) } defer func() { _ = res.Body.Close() }() body, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) if res.StatusCode != http.StatusOK { var e struct { Error string `json:"error"` Description string `json:"error_description"` } _ = json.Unmarshal(body, &e) if e.Error == "invalid_grant" { return Token{}, ErrRevoked } msg := e.Description if msg == "" { msg = e.Error } if msg == "" { msg = res.Status } return Token{}, fmt.Errorf("%s refused the sign-in: %s", p.Name, msg) } var t Token if err := json.Unmarshal(body, &t); err != nil || t.AccessToken == "" { return Token{}, fmt.Errorf("%s answered without a token", p.Name) } t.Expires = time.Now().Add(time.Duration(max(t.ExpiresIn-60, 30)) * time.Second) return t, nil } // Exchange trades the code from the callback for tokens. func (p Provider) Exchange(ctx context.Context, client *http.Client, code, redirect string) (Token, error) { return p.token(ctx, client, url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {redirect}}) } // Refresh gets a new access token. Microsoft may send a new refresh token, // which replaces the old one. func (p Provider) Refresh(ctx context.Context, client *http.Client, refresh string, scopes []string) (Token, error) { form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}} if len(scopes) > 0 && p.Name == "microsoft" { form.Set("scope", strings.Join(scopes, " ")) } t, err := p.token(ctx, client, form) if err == nil && t.RefreshToken == "" { t.RefreshToken = refresh } return t, err } // ---- State ------------------------------------------------------------------------ // State travels through the provider and back to the callback: who asked, // for what (Purpose), and what to do after (Data). It is signed, so the // callback trusts it, and short-lived. type State struct { User string `json:"u"` Purpose string `json:"p"` Data map[string]string `json:"d,omitempty"` Expires int64 `json:"e"` Nonce string `json:"n"` } // States signs and checks states with a server secret. type States struct{ key []byte } func NewStates(secret string) *States { k := sha256.Sum256([]byte("docwell-oauth-state:" + secret)) return &States{key: k[:]} } // Sign returns s as a URL-safe string valid for 15 minutes. func (st *States) Sign(s State) string { var nonce [12]byte _, _ = rand.Read(nonce[:]) s.Nonce = base64.RawURLEncoding.EncodeToString(nonce[:]) s.Expires = time.Now().Add(15 * time.Minute).Unix() raw, _ := json.Marshal(s) payload := base64.RawURLEncoding.EncodeToString(raw) return payload + "." + st.mac(payload) } func (st *States) mac(payload string) string { m := hmac.New(sha256.New, st.key) m.Write([]byte(payload)) return base64.RawURLEncoding.EncodeToString(m.Sum(nil)) } // ErrBadState is a state that was changed, is too old, or was made for // something else. var ErrBadState = errors.New("the sign-in link is invalid or too old; start again") // Verify checks a state made for purpose. func (st *States) Verify(raw, purpose string) (State, error) { payload, sig, ok := strings.Cut(raw, ".") if !ok || !hmac.Equal([]byte(sig), []byte(st.mac(payload))) { return State{}, ErrBadState } data, err := base64.RawURLEncoding.DecodeString(payload) if err != nil { return State{}, ErrBadState } var s State if json.Unmarshal(data, &s) != nil || s.Purpose != purpose || s.User == "" || time.Now().Unix() > s.Expires { return State{}, ErrBadState } return s, nil } // Peek reads a verified state's purpose without knowing it first (the // callback routes by it). func (st *States) Peek(raw string) (State, error) { payload, _, _ := strings.Cut(raw, ".") data, err := base64.RawURLEncoding.DecodeString(payload) if err != nil { return State{}, ErrBadState } var s State if json.Unmarshal(data, &s) != nil { return State{}, ErrBadState } return st.Verify(raw, s.Purpose) } // ---- Callback routing ----------------------------------------------------------------- // Handler finishes a sign-in made for one purpose and returns where the // browser goes next. type Handler func(ctx context.Context, st State, code, providerErr string) string // Router sends a provider's callback to the handler its state names. type Router struct { states *States handlers map[string]Handler fallback string } // NewRouter routes callbacks; a state that does not check out goes to // fallback (the web app) with oauthError set. func NewRouter(states *States, fallback string) *Router { return &Router{states: states, handlers: map[string]Handler{}, fallback: strings.TrimRight(fallback, "/")} } // Handle registers the handler for purpose. func (r *Router) Handle(purpose string, h Handler) { r.handlers[purpose] = h } // Callback handles the query a provider redirects back with. func (r *Router) Callback(ctx context.Context, q url.Values) string { st, err := r.states.Peek(q.Get("state")) h := r.handlers[st.Purpose] if err != nil || h == nil { if err == nil { err = ErrBadState } return r.fallback + "/?" + url.Values{"oauthError": {err.Error()}}.Encode() } return h(ctx, st, q.Get("code"), q.Get("error")) }