feat: add browser upload queue and trusted sessions with bounded projections
Build and publish container images / images (push) Successful in 11m37s
Release container images / release (push) Successful in 22s

This commit is contained in:
Anya Tokugawa committed 2026-11-08 20:27:04 +09:00
1 parent 84d52390f9
commit b90aef79d0
79 files changed
+1962 -196

No files matched your search

+5 -1
View File
@@ -164,6 +164,10 @@ func (s *Store) CreateBrowserAuthSession(domainUUID, principalUUID string, mfaLe
}
func (s *Store) createTypedAuthSession(domainUUID, principalUUID string, mfaLevel int, prefix string) (string, error) {
return s.createTypedAuthSessionForLifetime(domainUUID, principalUUID, mfaLevel, prefix, s.AuthSessionLifetime(domainUUID))
}
func (s *Store) createTypedAuthSessionForLifetime(domainUUID, principalUUID string, mfaLevel int, prefix string, lifetime time.Duration) (string, error) {
raw, _, err := authToken()
if err != nil {
return "", err
@@ -177,7 +181,7 @@ func (s *Store) createTypedAuthSession(domainUUID, principalUUID string, mfaLeve
result, err := s.DB.Exec(`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,m.domain_uuid,?,?,?,? FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid
WHERE p.uuid=? AND p.state IN ('active','readonly') AND m.domain_uuid=? AND m.state='active'`,
uuid.NewString(), hash, now, now+s.AuthSessionLifetime(domainUUID).Milliseconds(), now, mfaLevel, principalUUID, domainUUID)
uuid.NewString(), hash, now, now+lifetime.Milliseconds(), now, mfaLevel, principalUUID, domainUUID)
if err != nil {
return "", err
}
+18 -6
View File
@@ -27,7 +27,9 @@ var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff",
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")
@@ -39,11 +41,16 @@ var (
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
}
@@ -66,10 +73,10 @@ func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge stri
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)
SELECT ?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
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, domain, now-300000)
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
@@ -82,7 +89,7 @@ func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge stri
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 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)
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
}
@@ -168,15 +175,17 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
}
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`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser)
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)
@@ -204,6 +213,9 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
return
}
var raw string
if remember {
lifetime = trustedLifetime
}
raw, _, err = authToken()
if err != nil {
return
+58
View File
@@ -8,10 +8,68 @@ import (
"sync/atomic"
"testing"
"time"
"pageswiki/internal/db"
)
const cliTestOrigin = "https://wiki.example"
func TestCLIAuthTrustedMigrationPreservesExistingRequests(t *testing.T) {
s := newSchemaTestStore(t)
ctx := context.Background()
if err := db.ApplySQLiteMigrations(ctx, s.DB, "cli-auth", cliAuthMigrations[:1]); err != nil {
t.Fatal(err)
}
if _, err := s.DB.Exec(`INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms) VALUES('old','domain','https://wiki.example','device','challenge','code',1,2)`); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if err := db.ApplySQLiteMigrations(ctx, s.DB, "cli-auth", cliAuthMigrations); err != nil {
t.Fatal(err)
}
}
var remember int
var challenge string
if err := s.DB.QueryRow(`SELECT remember,challenge FROM auth_cli_requests WHERE id='old'`).Scan(&remember, &challenge); err != nil || remember != 0 || challenge != "challenge" {
t.Fatalf("old grant changed: %d %q %v", remember, challenge, err)
}
if _, err := s.DB.Exec(`UPDATE auth_cli_requests SET remember=2`); err == nil {
t.Fatal("invalid remember flag accepted")
}
}
func TestTOTPLoginBindsTrustedChoice(t *testing.T) {
for _, remember := range []bool{false, true} {
s, p, _ := cliAuthFixture(t)
secret, err := s.BeginTOTPEnrollment(p)
if err != nil {
t.Fatal(err)
}
code, err := totpCode(secret, time.Now().Unix()/30)
if err != nil {
t.Fatal(err)
}
if err = s.ConfirmTOTPEnrollment(p, code); err != nil {
t.Fatal(err)
}
// Synthetic fixture: permit this time step once for login after enrollment.
if _, err = s.DB.Exec(`UPDATE auth_credentials SET parameters_json='{"last_counter":0}' WHERE principal_uuid=? AND kind='totp'`, p); err != nil {
t.Fatal(err)
}
challenge, err := s.CreateTOTPLoginChallengeForLogin("domain", p, remember)
if err != nil {
t.Fatal(err)
}
got, choice, err := s.CompleteTOTPLoginChallengeForLogin("domain", challenge, code)
if err != nil || got != p || choice != remember {
t.Fatalf("bound choice: %q %v %v", got, choice, err)
}
if _, _, err = s.CompleteTOTPLoginChallengeForLogin("domain", challenge, code); err == nil {
t.Fatal("challenge replay accepted")
}
}
}
func cliAuthFixture(t *testing.T) (*Store, string, string) {
t.Helper()
s := newSchemaTestStore(t)
+34
View File
@@ -30,3 +30,37 @@ func (s *Store) SetAuthSessionLifetimeMinutes(domain string, minutes int) error
func (s *Store) AuthSessionLifetime(domain string) time.Duration {
return time.Duration(s.AuthSessionLifetimeMinutes(domain)) * time.Minute
}
// Opt-in persistent sessions have a separate, administrator-controlled ceiling.
// Zero disables the option. Existing sessions retain their original expiry.
func (s *Store) TrustedSessionDays(domain string) int {
raw, err := s.GetConfigInDomain(domain, "auth_trusted_session_days")
if err != nil {
return 0
}
if raw == "" {
return 30
}
days, err := strconv.Atoi(raw)
if err != nil || days < 0 || days > 30 {
return 0
}
return days
}
func (s *Store) LoginSessionLifetime(domain string, remember bool) time.Duration {
if days := s.TrustedSessionDays(domain); remember && days > 0 {
return time.Duration(days) * 24 * time.Hour
}
return s.AuthSessionLifetime(domain)
}
func (s *Store) CreateLoginSession(domain, principal string, mfa int, browser, remember bool) (string, time.Duration, error) {
lifetime := s.LoginSessionLifetime(domain, remember)
prefix := "pw_api_"
if browser {
prefix = "pw_browser_"
}
token, err := s.createTypedAuthSessionForLifetime(domain, principal, mfa, prefix, lifetime)
return token, lifetime, err
}
+23 -8
View File
@@ -176,36 +176,51 @@ func TOTPURI(secret, account, issuer string) string {
}
func (s *Store) CreateTOTPLoginChallenge(domainUUID, principalUUID string) (string, error) {
return s.CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID, false)
}
func (s *Store) CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID string, remember bool) (string, error) {
token, hash, err := authToken()
if err != nil {
return "", err
}
now := time.Now().UnixMilli()
payload, _ := json.Marshal(map[string]string{"principal_uuid": principalUUID})
payload, _ := json.Marshal(map[string]any{"principal_uuid": principalUUID, "remember": remember})
_, err = s.DB.Exec(`INSERT INTO auth_challenges(uuid,domain_uuid,principal_uuid,kind,token_hash,payload_json,expires_at_ms,created_at_ms) VALUES(?,?,?,?,?,?,?,?)`, uuid.NewString(), domainUUID, principalUUID, "totp-login", hash, string(payload), now+5*60*1000, now)
return token, err
}
func (s *Store) CompleteTOTPLoginChallenge(domainUUID, token, code string) (string, error) {
id, _, err := s.CompleteTOTPLoginChallengeForLogin(domainUUID, token, code)
return id, err
}
func (s *Store) CompleteTOTPLoginChallengeForLogin(domainUUID, token, code string) (string, bool, error) {
sum := sha256.Sum256([]byte(token))
hash := base64.RawURLEncoding.EncodeToString(sum[:])
var challengeUUID, principalUUID string
var challengeUUID, principalUUID, payload string
var expires int64
var attempts int
err := s.DB.QueryRow(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count FROM auth_challenges WHERE domain_uuid=? AND kind='totp-login' AND token_hash=? AND consumed_at_ms=0`, domainUUID, hash).Scan(&challengeUUID, &principalUUID, &expires, &attempts)
err := s.DB.QueryRow(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count,payload_json FROM auth_challenges WHERE domain_uuid=? AND kind='totp-login' AND token_hash=? AND consumed_at_ms=0`, domainUUID, hash).Scan(&challengeUUID, &principalUUID, &expires, &attempts, &payload)
if err != nil || expires < time.Now().UnixMilli() || attempts >= 5 {
return "", ErrAccessDenied
return "", false, ErrAccessDenied
}
var options struct {
Remember bool `json:"remember"`
}
if json.Unmarshal([]byte(payload), &options) != nil {
return "", false, ErrAccessDenied
}
if err = s.VerifyTOTP(principalUUID, code); err != nil {
_, _ = s.DB.Exec(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN ? ELSE consumed_at_ms END WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
return "", err
return "", false, err
}
result, err := s.DB.Exec(`UPDATE auth_challenges SET consumed_at_ms=? WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
if err != nil {
return "", err
return "", false, err
}
changed, _ := result.RowsAffected()
if changed != 1 {
return "", ErrAccessDenied
return "", false, ErrAccessDenied
}
return principalUUID, nil
return principalUUID, options.Remember, nil
}
+5 -1
View File
@@ -81,7 +81,11 @@ func minInt64(a, b int64) int64 {
}
func (s *Store) GetRevisionMetadata(revisionUUID string) (*Revision, error) {
row := s.DB.QueryRow(`SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE uuid=?`, revisionUUID)
return s.GetRevisionMetadataContext(context.Background(), revisionUUID)
}
func (s *Store) GetRevisionMetadataContext(ctx context.Context, revisionUUID string) (*Revision, error) {
row := s.DB.QueryRowContext(ctx, `SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE uuid=?`, revisionUUID)
return scanRevision(row)
}
+6 -1
View File
@@ -1,6 +1,7 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"strings"
@@ -69,6 +70,10 @@ func (s *Store) ResolvePathInDomain(
domainUUID string,
path string,
) (string, error) {
return s.ResolvePathInDomainContext(context.Background(), domainUUID, path)
}
func (s *Store) ResolvePathInDomainContext(ctx context.Context, domainUUID, path string) (string, error) {
path = normalizePath(path)
if err := s.ensureLocalDomain(domainUUID); err != nil {
return "", err
@@ -76,7 +81,7 @@ func (s *Store) ResolvePathInDomain(
var objectUUID string
err := s.DB.QueryRow(`
err := s.DB.QueryRowContext(ctx, `
SELECT object_uuid
FROM paths
WHERE domain_uuid = ?
+6 -1
View File
@@ -1,6 +1,7 @@
package store
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
@@ -324,6 +325,10 @@ func (s *Store) GetRevision(
}
func (s *Store) GetLatestRevisionMetadataForLanguages(objectUUID string, rawLanguages []string) (*Revision, error) {
return s.GetLatestRevisionMetadataForLanguagesContext(context.Background(), objectUUID, rawLanguages)
}
func (s *Store) GetLatestRevisionMetadataForLanguagesContext(ctx context.Context, objectUUID string, rawLanguages []string) (*Revision, error) {
candidates := make([]string, 0, len(rawLanguages)+1)
seen := map[string]bool{}
for _, rawLanguage := range rawLanguages {
@@ -336,7 +341,7 @@ func (s *Store) GetLatestRevisionMetadataForLanguages(objectUUID string, rawLang
candidates = append(candidates, "und")
}
for _, lang := range candidates {
row := s.DB.QueryRow(`SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE object_uuid=? AND COALESCE(NULLIF(lang,''),'und')=? ORDER BY COALESCE(created_at_ms,created_at*1000) DESC,rowid DESC LIMIT 1`, objectUUID, lang)
row := s.DB.QueryRowContext(ctx, `SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE object_uuid=? AND COALESCE(NULLIF(lang,''),'und')=? ORDER BY COALESCE(created_at_ms,created_at*1000) DESC,rowid DESC LIMIT 1`, objectUUID, lang)
revision, err := scanRevision(row)
if err == nil {
return revision, nil