Files
Docwell/Server/internal/auth/oauth.go
T
tajniak81andClaude Opus 5.5 631b929433 Add OAuth and OIDC sign-in, two-step codes, audit log, API tokens and webhooks
Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
  admin panel (secrets are write-only). PocketBase talks to the provider,
  and docwell-server keeps the state and PKCE verifier. Accounts a
  provider creates follow the sign-up switch and the domain list; refused
  ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
  account", with ten single-use recovery codes. After any first factor
  (password, email code, provider) the session is held behind a
  five-minute challenge: five tries, each code works once. Turning it off
  needs a code. Managers can reset it for someone who lost their phone.
  Both the web app and the admin panel ask for the code.

Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
  read-write, with optional expiry. Only a hash is stored, and the token is
  shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
  and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
  HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
  and a test button. Loopback and link-local addresses are refused
  (DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).

Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:31:45 +01:00

183 lines
5.6 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package auth
import (
"context"
"errors"
"net/http"
"net/url"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/store/pocketbase"
)
// ---- Sign-in with Google, GitHub, Microsoft or any OpenID Connect provider -
//
// PocketBase talks to the provider; docwell-server keeps the flow's state and
// PKCE verifier (so the client never handles them), and applies Docwell's
// rules to accounts the provider creates: the sign-up switch and domain list
// (or the account is removed again), plain user role, and the second step.
const oauthTTL = 10 * time.Minute
type oauthFlow struct {
provider string
codeVerifier string
redirect string
expires time.Time
}
type oauthState struct {
mu sync.Mutex
flows map[string]oauthFlow
}
func newOAuthState() *oauthState { return &oauthState{flows: map[string]oauthFlow{}} }
// OAuthStart is where to send the browser to sign in with a provider.
type OAuthStart struct {
URL string `json:"url"`
State string `json:"state"`
}
type pbAuthMethods struct {
OAuth2 struct {
Enabled bool `json:"enabled"`
Providers []struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
State string `json:"state"`
AuthURL string `json:"authURL"`
CodeVerifier string `json:"codeVerifier"`
} `json:"providers"`
} `json:"oauth2"`
}
// redirectAllowed reports whether redirect is one of the configured callback
// addresses (the web app's /oauth/callback, the desktop app's link).
func (s *Service) redirectAllowed(redirect string) bool {
for _, r := range s.opts.OAuthRedirects {
if redirect == r {
return true
}
}
return false
}
// StartOAuth begins signing in with provider; the provider sends the browser
// back to redirect with a code and the state.
func (s *Service) StartOAuth(ctx context.Context, provider, redirect string) (OAuthStart, error) {
if !s.redirectAllowed(redirect) {
return OAuthStart{}, &ValidationError{Fields: map[string]string{"redirect": "This return address is not allowed."}}
}
var m pbAuthMethods
if err := s.pb.DoAs(ctx, http.MethodGet, usersPath+"/auth-methods", "", nil, &m); err != nil {
return OAuthStart{}, mapError(err)
}
for _, p := range m.OAuth2.Providers {
if !m.OAuth2.Enabled || p.Name != provider {
continue
}
now := s.now()
s.oauth.mu.Lock()
for k, f := range s.oauth.flows {
if now.After(f.expires) {
delete(s.oauth.flows, k)
}
}
s.oauth.flows[p.State] = oauthFlow{provider: p.Name, codeVerifier: p.CodeVerifier, redirect: redirect, expires: now.Add(oauthTTL)}
s.oauth.mu.Unlock()
// PocketBase's authURL ends with "redirect_uri=" for the caller to fill.
return OAuthStart{URL: p.AuthURL + url.QueryEscape(redirect), State: p.State}, nil
}
return OAuthStart{}, &ValidationError{Fields: map[string]string{"provider": "That sign-in method is not turned on."}}
}
// FinishOAuth completes a provider sign-in with the code from the callback.
func (s *Service) FinishOAuth(ctx context.Context, state, code string) (Session, error) {
s.oauth.mu.Lock()
flow, ok := s.oauth.flows[state]
delete(s.oauth.flows, state)
s.oauth.mu.Unlock()
if !ok || s.now().After(flow.expires) || strings.TrimSpace(code) == "" {
return Session{}, ErrInvalidToken
}
var res struct {
authResponse
Meta struct {
IsNew bool `json:"isNew"`
} `json:"meta"`
}
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/auth-with-oauth2", "", map[string]any{
"provider": flow.provider, "code": code, "codeVerifier": flow.codeVerifier, "redirectURL": flow.redirect,
// Fields for an account the provider creates; role and status are ours to set.
"createData": map[string]any{"status": "active", "role": access.RoleUser, "emailVisibility": false},
}, &res)
if err != nil {
return Session{}, s.authError(err)
}
if res.Meta.IsNew {
if err := s.admitNewAccount(ctx, res.Record); err != nil {
return Session{}, err
}
if res.Record, err = pocketbase.Get[UserRecord](ctx, s.pb, "users", res.Record.ID); err != nil {
return Session{}, err
}
}
u := res.Record.User()
if u.Status == "disabled" {
return Session{}, ErrAccountDisabled
}
return s.secondStep(ctx, Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, u)})
}
// admitNewAccount applies the sign-up rules to an account a provider just
// created: the first account on the instance becomes the superadmin; later
// ones need sign-up on and an allowed domain, or they are removed again.
func (s *Service) admitNewAccount(ctx context.Context, rec UserRecord) error {
all, err := pocketbase.List[UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 1})
if err != nil {
return err
}
if all.TotalItems <= 1 {
_, err := pocketbase.Update[UserRecord](ctx, s.pb, "users", rec.ID, map[string]any{"role": access.RoleSuperadmin})
return err
}
enabled, domains, err := s.signupRules(ctx)
if err != nil {
return err
}
var refuse error
switch {
case !enabled:
refuse = ErrSignupDisabled
case !DomainAllowed(domains, rec.Email):
refuse = ErrDomainNotAllowed
}
if refuse != nil {
_ = s.pb.Delete(ctx, "users", rec.ID)
return refuse
}
// The provider vouched for the address.
_, err = pocketbase.Update[UserRecord](ctx, s.pb, "users", rec.ID, map[string]any{"verified": true})
return err
}
// authError maps PocketBase's sign-in failures like authenticate does.
func (s *Service) authError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) {
if pbErr.Status == http.StatusBadRequest && len(pbErr.Data) == 0 {
return ErrInvalidCredentials
}
if pbErr.Status == http.StatusForbidden {
return ErrAccountDisabled
}
}
return mapError(err)
}