251 lines
10 KiB
Go
251 lines
10 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"pageswiki/internal/db"
|
|
)
|
|
|
|
var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff", Statements: []string{
|
|
`CREATE TABLE auth_cli_requests (
|
|
id TEXT PRIMARY KEY, domain_uuid TEXT NOT NULL, origin TEXT NOT NULL,
|
|
device_hash TEXT NOT NULL UNIQUE, challenge TEXT NOT NULL, code_hash TEXT NOT NULL,
|
|
state TEXT NOT NULL DEFAULT 'pending', browser_hash TEXT NOT NULL DEFAULT '',
|
|
principal_uuid TEXT NOT NULL DEFAULT '', mfa_level INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, oidc_attempts INTEGER NOT NULL DEFAULT 0,
|
|
created_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, next_poll_ms INTEGER NOT NULL DEFAULT 0)`,
|
|
`CREATE INDEX auth_cli_domain_created ON auth_cli_requests(domain_uuid,created_ms)`,
|
|
`CREATE INDEX auth_cli_expiry ON auth_cli_requests(expires_ms)`,
|
|
}, Assertions: []string{
|
|
schemaColumns("auth_cli_requests", "id,domain_uuid,origin,device_hash,challenge,code_hash,state,browser_hash,principal_uuid,mfa_level,attempts,oidc_attempts,created_ms,expires_ms,next_poll_ms"),
|
|
schemaUnique("auth_cli_requests", "id"), schemaUnique("auth_cli_requests", "device_hash"),
|
|
schemaIndex("auth_cli_requests", "auth_cli_domain_created", "domain_uuid,created_ms"),
|
|
schemaIndex("auth_cli_requests", "auth_cli_expiry", "expires_ms"),
|
|
}}, {Version: 2, Name: "cli_trusted_session_choice", Statements: []string{
|
|
`ALTER TABLE auth_cli_requests ADD COLUMN remember INTEGER NOT NULL DEFAULT 0 CHECK(remember IN (0,1))`,
|
|
}, Assertions: []string{schemaColumns("auth_cli_requests", "remember")}}}
|
|
|
|
var (
|
|
ErrCLIPending = errors.New("authorization_pending")
|
|
ErrCLISlowDown = errors.New("slow_down")
|
|
ErrCLIExpired = errors.New("expired_token")
|
|
ErrCLILimit = errors.New("too_many_requests")
|
|
)
|
|
|
|
type CLIAuthRequest struct {
|
|
ID, Origin, State, BrowserHash, PrincipalUUID string
|
|
ExpiresMS int64
|
|
Remember bool
|
|
}
|
|
|
|
// Admission is one write statement; concurrent unauthenticated requests cannot
|
|
// race the caps. Requests are retained for ten minutes for issuance accounting.
|
|
func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) {
|
|
return s.StartCLIAuthForLogin(ctx, domain, origin, challenge, false)
|
|
}
|
|
|
|
func (s *Store) StartCLIAuthForLogin(ctx context.Context, domain, origin, challenge string, remember bool) (id, device, code string, err error) {
|
|
if s.ReadOnly {
|
|
return "", "", "", ErrReadOnly
|
|
}
|
|
id, _, err = authToken()
|
|
if err != nil {
|
|
return
|
|
}
|
|
device, _, err = authToken()
|
|
if err != nil {
|
|
return
|
|
}
|
|
var raw [4]byte
|
|
if _, err = rand.Read(raw[:]); err != nil {
|
|
return
|
|
}
|
|
code = strings.ToUpper(hex.EncodeToString(raw[:]))
|
|
now := time.Now().UnixMilli()
|
|
_, err = s.DB.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms<?`, now-5*60*1000)
|
|
if err != nil {
|
|
return
|
|
}
|
|
var result sql.Result
|
|
result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms,remember)
|
|
SELECT ?,?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
|
|
AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=? AND created_ms>?)<64`,
|
|
id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, remember, domain, now-300000)
|
|
if err == nil {
|
|
if n, e := result.RowsAffected(); e != nil {
|
|
err = e
|
|
} else if n != 1 {
|
|
err = ErrCLILimit
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func (s *Store) CLIAuthRequest(ctx context.Context, domain, origin, id string) (*CLIAuthRequest, error) {
|
|
var grant CLIAuthRequest
|
|
err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms,remember FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS, &grant.Remember)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrCLIExpired
|
|
}
|
|
return &grant, err
|
|
}
|
|
|
|
func (s *Store) BeginCLIAuth(ctx context.Context, domain, origin, id string) error {
|
|
if s.ReadOnly {
|
|
return ErrReadOnly
|
|
}
|
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET oidc_attempts=oidc_attempts+1 WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>? AND oidc_attempts<3`, id, domain, origin, time.Now().UnixMilli())
|
|
return cliChanged(result, err)
|
|
}
|
|
|
|
// Only the verified OIDC callback calls this method. The first successful
|
|
// browser wins; another browser cannot rebind an in-flight approval.
|
|
func (s *Store) BindCLIAuth(ctx context.Context, domain, origin, id, browser string) error {
|
|
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
|
return ErrAccessDenied
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET browser_hash=?,principal_uuid=(SELECT principal_uuid FROM auth_sessions WHERE token_hash=?)
|
|
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>?
|
|
AND EXISTS(SELECT 1 FROM auth_sessions WHERE token_hash=? AND domain_uuid=? AND revoked_at_ms=0 AND expires_at_ms>?)`, hashAuthToken(browser), hashAuthToken(browser), id, domain, origin, now, hashAuthToken(browser), domain, now)
|
|
return cliChanged(result, err)
|
|
}
|
|
|
|
func cliChanged(result sql.Result, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n, err := result.RowsAffected()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n != 1 {
|
|
return ErrAccessDenied
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// The verified OIDC callback is the only production caller of BindCLIAuth.
|
|
// Authenticate at the provider, then require explicit local consent, not a
|
|
// second local TOTP challenge. This does not claim the provider performed MFA.
|
|
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, _ string, approve bool) error {
|
|
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
|
return ErrAccessDenied
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
var expectedCode string
|
|
err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1
|
|
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>?
|
|
RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode)
|
|
if err != nil {
|
|
return ErrAccessDenied
|
|
}
|
|
level := 0
|
|
if approve {
|
|
if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
|
|
return ErrAccessDenied
|
|
}
|
|
}
|
|
state := "denied"
|
|
if approve {
|
|
state = "approved"
|
|
}
|
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET state=?,mfa_level=? WHERE id=? AND domain_uuid=? AND state='pending' AND browser_hash=? AND expires_ms>?
|
|
AND EXISTS(SELECT 1 FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
|
|
WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active')`, state, level, id, domain, hashAuthToken(browser), now, hashAuthToken(browser), domain, now)
|
|
if err = cliChanged(result, err); err != nil {
|
|
return err
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Poll and exchange start with a write, avoiding a WAL read-to-write upgrade.
|
|
// Grant consumption and API-session creation commit together. No replay on a
|
|
// lost HTTP response: a new login is required (no credential stored in grant).
|
|
func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, verifier string) (token, username string, expires int64, err error) {
|
|
if s.ReadOnly {
|
|
err = ErrReadOnly
|
|
return
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
lifetime := s.AuthSessionLifetime(domain).Milliseconds()
|
|
trustedLifetime := s.LoginSessionLifetime(domain, true).Milliseconds()
|
|
tx, err := s.DB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
var id, state, browser string
|
|
var remember bool
|
|
err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END
|
|
WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied')
|
|
RETURNING id,state,browser_hash,remember`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser, &remember)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
var exists int
|
|
e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists)
|
|
if e != nil {
|
|
err = e
|
|
} else if exists > 0 {
|
|
err = ErrCLISlowDown
|
|
} else {
|
|
err = ErrCLIExpired
|
|
}
|
|
return
|
|
}
|
|
if err != nil {
|
|
return
|
|
}
|
|
if state != "consumed" {
|
|
err = tx.Commit()
|
|
if err == nil {
|
|
if state == "denied" {
|
|
err = ErrAccessDenied
|
|
} else {
|
|
err = ErrCLIPending
|
|
}
|
|
}
|
|
return
|
|
}
|
|
var raw string
|
|
if remember {
|
|
lifetime = trustedLifetime
|
|
}
|
|
raw, _, err = authToken()
|
|
if err != nil {
|
|
return
|
|
}
|
|
token = "pw_api_" + raw
|
|
// A disabled user, removed membership or revoked browser cannot delegate.
|
|
err = tx.QueryRowContext(ctx, `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level)
|
|
SELECT ?,?,p.uuid,a.domain_uuid,a.auth_time_ms,min(?,a.expires_at_ms),?,max(a.mfa_level,g.mfa_level)
|
|
FROM auth_cli_requests g JOIN auth_sessions a ON a.token_hash=g.browser_hash JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
|
|
WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active'
|
|
AND g.id=?
|
|
RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
err = ErrAccessDenied
|
|
}
|
|
if err != nil {
|
|
token = ""
|
|
return
|
|
}
|
|
var name string
|
|
err = tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT subject FROM principal_identities WHERE principal_uuid=? AND provider_type='password' LIMIT 1),?)`, username, username).Scan(&name)
|
|
if err != nil {
|
|
token = ""
|
|
return
|
|
}
|
|
username = name
|
|
err = tx.Commit()
|
|
if err != nil {
|
|
token = ""
|
|
}
|
|
return
|
|
}
|