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>
240 lines
7.1 KiB
Go
240 lines
7.1 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// ---- Personal API tokens ---------------------------------------------------
|
|
//
|
|
// A token acts as its owner, with their rights, for scripts and integrations.
|
|
// "read" tokens can only make GET requests. Only the SHA-256 of a token is
|
|
// stored; the token itself is shown once, when it is created.
|
|
|
|
// TokenPrefix starts every API token, which tells them apart from session tokens.
|
|
const TokenPrefix = "dw_"
|
|
|
|
const (
|
|
ScopeRead = "read"
|
|
ScopeWrite = "write"
|
|
maxTokens = 50
|
|
)
|
|
|
|
// APIToken is a token as its owner (or an admin) sees it, without the secret.
|
|
type APIToken struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Prefix string `json:"prefix"`
|
|
Scope string `json:"scope"`
|
|
LastUsed string `json:"lastUsed"`
|
|
Expires string `json:"expires"`
|
|
Created string `json:"created"`
|
|
// User is set in admin listings.
|
|
User *TokenOwner `json:"user,omitempty"`
|
|
}
|
|
|
|
type TokenOwner struct {
|
|
ID string `json:"id"`
|
|
Email string `json:"email"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// NewAPIToken is a token just created: Token is shown this once.
|
|
type NewAPIToken struct {
|
|
APIToken
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
type tokenRecord struct {
|
|
ID string `json:"id"`
|
|
User string `json:"user"`
|
|
Name string `json:"name"`
|
|
TokenHash string `json:"token_hash"`
|
|
Prefix string `json:"prefix"`
|
|
Scope string `json:"scope"`
|
|
LastUsed string `json:"last_used"`
|
|
Expires string `json:"expires"`
|
|
Created string `json:"created"`
|
|
Expand struct {
|
|
User *UserRecord `json:"user"`
|
|
} `json:"expand"`
|
|
}
|
|
|
|
func (r tokenRecord) view() APIToken {
|
|
t := APIToken{ID: r.ID, Name: r.Name, Prefix: r.Prefix, Scope: r.Scope, LastUsed: r.LastUsed, Expires: r.Expires, Created: r.Created}
|
|
if u := r.Expand.User; u != nil {
|
|
t.User = &TokenOwner{ID: u.ID, Email: u.Email, Name: u.Name}
|
|
}
|
|
return t
|
|
}
|
|
|
|
func tokenHash(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
const pbTimeLayout = "2006-01-02 15:04:05.000Z"
|
|
|
|
// CreateAPIToken makes a token for u. expiresDays 0 means it never expires.
|
|
func (s *Service) CreateAPIToken(ctx context.Context, u User, name, scope string, expiresDays int) (NewAPIToken, error) {
|
|
name = strings.TrimSpace(name)
|
|
fields := map[string]string{}
|
|
if name == "" || len(name) > 100 {
|
|
fields["name"] = "Give the token a name (up to 100 characters)."
|
|
}
|
|
if scope != ScopeRead && scope != ScopeWrite {
|
|
fields["scope"] = "Scope must be read or write."
|
|
}
|
|
if expiresDays < 0 || expiresDays > 3650 {
|
|
fields["expiresDays"] = "Expiry must be between 0 (never) and 3650 days."
|
|
}
|
|
if len(fields) > 0 {
|
|
return NewAPIToken{}, &ValidationError{Fields: fields}
|
|
}
|
|
n, err := pocketbase.List[tokenRecord](ctx, s.pb, "api_tokens", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("user = '%s'", u.ID), Fields: "id",
|
|
})
|
|
if err != nil {
|
|
return NewAPIToken{}, err
|
|
}
|
|
if n.TotalItems >= maxTokens {
|
|
return NewAPIToken{}, &ValidationError{Fields: map[string]string{"name": "You have as many tokens as allowed; revoke one first."}}
|
|
}
|
|
token := TokenPrefix + randomToken(32)
|
|
body := map[string]any{
|
|
"user": u.ID, "name": name, "token_hash": tokenHash(token), "prefix": token[:10], "scope": scope,
|
|
}
|
|
if expiresDays > 0 {
|
|
body["expires"] = s.now().Add(time.Duration(expiresDays) * 24 * time.Hour).UTC().Format(pbTimeLayout)
|
|
}
|
|
rec, err := pocketbase.Create[tokenRecord](ctx, s.pb, "api_tokens", body)
|
|
if err != nil {
|
|
return NewAPIToken{}, mapError(err)
|
|
}
|
|
return NewAPIToken{APIToken: rec.view(), Token: token}, nil
|
|
}
|
|
|
|
// ListAPITokens lists a user's tokens, newest first.
|
|
func (s *Service) ListAPITokens(ctx context.Context, userID string) ([]APIToken, error) {
|
|
res, err := pocketbase.List[tokenRecord](ctx, s.pb, "api_tokens", pocketbase.ListOptions{
|
|
PerPage: maxTokens, Filter: fmt.Sprintf("user = '%s'", userID), Sort: "-created",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]APIToken, 0, len(res.Items))
|
|
for _, r := range res.Items {
|
|
out = append(out, r.view())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// AdminListAPITokens lists the tokens of the users c manages (superadmins:
|
|
// everyone; admins: their organization), newest first.
|
|
func (s *Service) AdminListAPITokens(ctx context.Context, c access.Caller) ([]APIToken, error) {
|
|
all, org, err := access.UserScope(c)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
filter := ""
|
|
if !all {
|
|
if org == "" {
|
|
return []APIToken{}, nil
|
|
}
|
|
filter = fmt.Sprintf("user.organization = '%s'", org)
|
|
}
|
|
res, err := pocketbase.List[tokenRecord](ctx, s.pb, "api_tokens", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: filter, Sort: "-created", Expand: "user",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]APIToken, 0, len(res.Items))
|
|
for _, r := range res.Items {
|
|
out = append(out, r.view())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RevokeAPIToken deletes token id: its owner may, or (admin true) a manager
|
|
// of the owner, which the caller has checked with access.ManageUser.
|
|
func (s *Service) RevokeAPIToken(ctx context.Context, c access.Caller, id string, manage func(ownerID string) error) error {
|
|
if id == "" || strings.ContainsAny(id, "/?#'") {
|
|
return ErrUnauthorized
|
|
}
|
|
rec, err := pocketbase.Get[tokenRecord](ctx, s.pb, "api_tokens", id)
|
|
if err != nil {
|
|
return tokenError(err)
|
|
}
|
|
if rec.User != c.ID {
|
|
if manage == nil {
|
|
return ErrUnauthorized
|
|
}
|
|
if err := manage(rec.User); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
s.forgetToken(rec.TokenHash)
|
|
return s.pb.Delete(ctx, "api_tokens", rec.ID)
|
|
}
|
|
|
|
// VerifyAPIToken returns the owner and scope of an API token.
|
|
func (s *Service) VerifyAPIToken(ctx context.Context, token string) (User, string, error) {
|
|
h := tokenHash(token)
|
|
key := sha256.Sum256([]byte("pat:" + h))
|
|
now := s.now()
|
|
s.mu.Lock()
|
|
if c, ok := s.cache[key]; ok && now.Before(c.expires) {
|
|
s.mu.Unlock()
|
|
return c.user, c.scope, nil
|
|
}
|
|
s.mu.Unlock()
|
|
|
|
res, err := pocketbase.List[tokenRecord](ctx, s.pb, "api_tokens", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("token_hash = '%s'", h),
|
|
})
|
|
if err != nil {
|
|
return User{}, "", err
|
|
}
|
|
if len(res.Items) == 0 {
|
|
return User{}, "", ErrUnauthorized
|
|
}
|
|
rec := res.Items[0]
|
|
if rec.Expires != "" {
|
|
if exp, err := time.Parse(pbTimeLayout, rec.Expires); err == nil && now.After(exp) {
|
|
return User{}, "", ErrUnauthorized
|
|
}
|
|
}
|
|
u, err := s.UserByID(ctx, rec.User)
|
|
if err != nil {
|
|
return User{}, "", err
|
|
}
|
|
// last_used is for people, so a minute's precision is plenty.
|
|
if last, err := time.Parse(pbTimeLayout, rec.LastUsed); err != nil || now.Sub(last) > time.Minute {
|
|
_, _ = pocketbase.Update[tokenRecord](ctx, s.pb, "api_tokens", rec.ID, map[string]any{"last_used": now.UTC().Format(pbTimeLayout)})
|
|
}
|
|
s.mu.Lock()
|
|
s.cache[key] = cachedUser{user: u, scope: rec.Scope, tokenHash: h, expires: now.Add(s.opts.CacheTTL)}
|
|
s.mu.Unlock()
|
|
return u, rec.Scope, nil
|
|
}
|
|
|
|
func (s *Service) forgetToken(hash string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for k, c := range s.cache {
|
|
if c.tokenHash == hash {
|
|
delete(s.cache, k)
|
|
}
|
|
}
|
|
}
|