From 26a7bbec377ee0960474f68ca65db6be921c2b7f Mon Sep 17 00:00:00 2001 From: protonmatter Date: Tue, 17 Nov 2026 13:04:30 -0500 Subject: [PATCH 1/4] Reject sessions issued before a password change. A failed password read no longer mints a setup token, and filling the login limiter no longer drops an active lockout. --- server/auth.go | 104 ++++++++++++++++++++++++++++++++----- server/auth_epoch_test.go | 23 ++++++++ server/login_limit.go | 26 ++++++++-- server/login_limit_test.go | 30 +++++++++++ server/server.go | 8 ++- web/src/lib/api.ts | 7 ++- 6 files changed, 178 insertions(+), 20 deletions(-) create mode 100644 server/auth_epoch_test.go diff --git a/server/auth.go b/server/auth.go index b76a1d2d1..28ba185bd 100644 --- a/server/auth.go +++ b/server/auth.go @@ -19,13 +19,15 @@ import ( "golang.org/x/crypto/bcrypt" "github.com/Autumn-27/artex/config" + "github.com/Autumn-27/artex/db" ) const ( - jwtKeyFilename = "jwt.key" - authPassKey = "auth.password_hash" - jwtTTL = 7 * 24 * time.Hour - keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + jwtKeyFilename = "jwt.key" + authPassKey = "auth.password_hash" + authPwdEpochKey = "auth.password_epoch" + jwtTTL = 7 * 24 * time.Hour + keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // The lower bound matches the setup page's frontend validation — validation that // lives only in the frontend is as good as none: hitting the API directly bypasses @@ -167,15 +169,24 @@ func signJWT(key []byte) (string, error) { }).SignedString(key) } -// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token. -func verifyJWT(tokenStr string, key []byte) bool { - t, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) { +// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token +// issued at or after notBefore. notBefore is Unix seconds; 0 means no cutoff, +// so a deployment that has never stored a password epoch keeps existing sessions. +func verifyJWT(tokenStr string, key []byte, notBefore int64) bool { + claims := &jwt.RegisteredClaims{} + t, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method") } return key, nil }) - return err == nil && t.Valid + if err != nil || !t.Valid { + return false + } + if notBefore > 0 && (claims.IssuedAt == nil || claims.IssuedAt.Unix() < notBefore) { + return false + } + return true } // jwtSubject returns the subject of tokenStr when it is a valid, non-expired @@ -197,7 +208,11 @@ func jwtSubject(tokenStr string, key []byte) string { // approver is who a human decision is recorded for: the subject of the // request's session token. func (s *Server) approver(r *http.Request) string { - return jwtSubject(extractToken(r), s.jwtKey) + tok := extractToken(r) + if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) { + return "" + } + return jwtSubject(tok, s.jwtKey) } // extractToken reads the JWT from Authorization: Bearer header, @@ -226,7 +241,7 @@ func (s *Server) requireAuth(h http.Handler) http.Handler { writeErr(w, 401, "Unauthorized") return } - if !verifyJWT(tok, s.jwtKey) { + if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) { writeErr(w, 401, "token is invalid or expired") return } @@ -258,15 +273,72 @@ func (s *Server) initSetupToken() { if s.m == nil || s.m.pg == nil { return } - if hash, _, err := s.m.pg.GetSetting(authPassKey); err == nil && hash != "" { + var hash string + var err error + for attempt := 1; attempt <= 3; attempt++ { + var ok bool + hash, ok, err = s.m.pg.GetSetting(authPassKey) + if err == nil { + if ok && hash != "" { + return + } + break + } + log.Printf("[auth] password lookup attempt %d/3: %v", attempt, err) + if attempt < 3 { + time.Sleep(time.Duration(attempt) * 100 * time.Millisecond) + } + } + if err != nil { + log.Printf("[auth] password lookup failed; not issuing a setup token: %v", err) return } buf := make([]byte, 16) if _, err := rand.Read(buf); err != nil { log.Fatalf("[auth] generate setup token: %v", err) } - s.setupToken = hex.EncodeToString(buf) - log.Printf("[auth] no admin password is set. Setup token for the /setup page: %s", s.setupToken) + token := hex.EncodeToString(buf) + s.setupMu.Lock() + s.setupToken = token + s.setupMu.Unlock() + log.Printf("[auth] no admin password is set. Setup token for the /setup page: %s", token) +} + +// loadPwdEpoch reads auth.password_epoch. A missing key leaves the cutoff at +// zero, which accepts every valid token. +func (s *Server) loadPwdEpoch() { + if s.m == nil || s.m.pg == nil { + return + } + raw, ok, err := s.m.pg.GetSetting(authPwdEpochKey) + if err != nil { + log.Printf("[auth] password epoch: %v", err) + return + } + if !ok || raw == "" { + return + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + log.Printf("[auth] password epoch %q: %v", raw, err) + return + } + s.pwdEpoch.Store(n) +} + +// bumpPwdEpoch records the current second as the oldest token that is still +// valid. A token signed in that same second still passes. A failed write leaves +// the previous cutoff in place and is logged; the password change itself stands. +func (s *Server) bumpPwdEpoch(pg *db.DB) { + if pg == nil { + return + } + epoch := time.Now().Unix() + if err := pg.SetSetting(authPwdEpochKey, strconv.FormatInt(epoch, 10)); err != nil { + log.Printf("[auth] save password epoch: %v", err) + return + } + s.pwdEpoch.Store(epoch) } // checkSetupToken compares got with the active setup token in constant time. @@ -330,6 +402,7 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) { s.setupMu.Lock() s.setupToken = "" s.setupMu.Unlock() + s.bumpPwdEpoch(pg) tok, err := signJWT(s.jwtKey) if err != nil { writeErr(w, 500, "token generation failed") @@ -346,7 +419,7 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) { if pg == nil { return } - if !verifyJWT(extractToken(r), s.jwtKey) { + if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) { writeErr(w, 401, "Unauthorized") return } @@ -388,6 +461,9 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, "Save failed: "+err.Error()) return } + // Sessions issued before this second stop working. This response does not + // include a replacement token; the next request asks for a new login. + s.bumpPwdEpoch(pg) writeJSON(w, 200, map[string]any{"ok": true}) } diff --git a/server/auth_epoch_test.go b/server/auth_epoch_test.go new file mode 100644 index 000000000..14e538661 --- /dev/null +++ b/server/auth_epoch_test.go @@ -0,0 +1,23 @@ +package server + +import ( + "testing" + "time" +) + +func TestTokenBeforePasswordEpochIsRejected(t *testing.T) { + key := []byte("0123456789abcdef0123456789abcdef") + tok, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + if !verifyJWT(tok, key, 0) { + t.Fatal("a token with no password epoch must be accepted") + } + if verifyJWT(tok, key, time.Now().Add(time.Minute).Unix()) { + t.Fatal("a token issued before the password epoch must be rejected") + } + if !verifyJWT(tok, key, time.Now().Add(-time.Minute).Unix()) { + t.Fatal("a token issued after the password epoch must be accepted") + } +} diff --git a/server/login_limit.go b/server/login_limit.go index 51dec5af6..fcc0d1e6a 100644 --- a/server/login_limit.go +++ b/server/login_limit.go @@ -105,16 +105,34 @@ func (l *loginLimiter) sweep(now time.Time) { } } -// evictOldest drops the least recently seen entry to stay under loginMaxEntries. +// evictOldest drops the least recently seen entry that is not inside a block. +// A block that is still running stays, so filling the map cannot clear an +// active lockout. When every entry is blocked, the one whose block ends soonest +// is the one that goes. func (l *loginLimiter) evictOldest() { + now := l.now() var oldest string var at time.Time + found := false for ip, e := range l.entries { - if oldest == "" || e.lastSeen.Before(at) { - oldest, at = ip, e.lastSeen + if now.Before(e.blockedUntil) { + continue + } + if !found || e.lastSeen.Before(at) { + oldest, at, found = ip, e.lastSeen, true } } - delete(l.entries, oldest) + if !found { + var until time.Time + for ip, e := range l.entries { + if oldest == "" || e.blockedUntil.Before(until) { + oldest, until = ip, e.blockedUntil + } + } + } + if oldest != "" { + delete(l.entries, oldest) + } } // peerIP is the host part of the TCP peer address. diff --git a/server/login_limit_test.go b/server/login_limit_test.go index 255b64c8c..d0a033a91 100644 --- a/server/login_limit_test.go +++ b/server/login_limit_test.go @@ -274,6 +274,36 @@ func TestLoginLimiterCapsEntries(t *testing.T) { } } +func TestEvictOldestKeepsBlockedEntries(t *testing.T) { + clk := newFakeClock() + l := newLoginLimiter(clk.now) + now := clk.now() + l.entries["blocked"] = &loginEntry{lastSeen: now.Add(-2 * time.Hour), blockedUntil: now.Add(time.Hour), block: time.Minute} + l.entries["idle"] = &loginEntry{lastSeen: now.Add(-time.Hour)} + l.evictOldest() + if _, ok := l.entries["blocked"]; !ok { + t.Fatal("evicted a blocked address while an idle one existed") + } + if _, ok := l.entries["idle"]; ok { + t.Fatal("kept the idle address") + } +} + +func TestEvictOldestDropsSoonestBlockWhenAllBlocked(t *testing.T) { + clk := newFakeClock() + l := newLoginLimiter(clk.now) + now := clk.now() + l.entries["long"] = &loginEntry{lastSeen: now, blockedUntil: now.Add(2 * time.Hour)} + l.entries["short"] = &loginEntry{lastSeen: now.Add(-time.Hour), blockedUntil: now.Add(time.Minute)} + l.evictOldest() + if _, ok := l.entries["short"]; ok { + t.Fatal("kept the block that ends sooner") + } + if _, ok := l.entries["long"]; !ok { + t.Fatal("evicted the longer block") + } +} + func TestHealthHidesVersionWithoutToken(t *testing.T) { key := []byte("0123456789abcdef0123456789abcdef") s := &Server{jwtKey: key} diff --git a/server/server.go b/server/server.go index aa8872882..f6b468ce6 100644 --- a/server/server.go +++ b/server/server.go @@ -19,6 +19,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/Autumn-27/artex/agent" @@ -53,6 +54,10 @@ type Server struct { setupMu sync.Mutex setupToken string // one-time token POST /api/auth/init requires; empty when none is active + // pwdEpoch is auth.password_epoch in Unix seconds. Zero means the setting + // is absent and every valid token is accepted. A token issued before the + // stored second is rejected. + pwdEpoch atomic.Int64 loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP @@ -170,6 +175,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi o(s) } s.initSetupToken() + s.loadPwdEpoch() s.initSideQuestions() // Circuit-breaker thresholds/cooldowns are hot parameters on the failure path; push the global retry policy to the Registry once at startup, // and again on every policy save (saveLLMRetryPolicy). @@ -1033,7 +1039,7 @@ func (s *Server) Handler() http.Handler { // with a valid token gets the service name and version; the web UI's top bar // reads the version, and sends its token. func (s *Server) health(w http.ResponseWriter, r *http.Request) { - if !verifyJWT(extractToken(r), s.jwtKey) { + if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) { writeJSON(w, 200, map[string]any{"ok": true}) return } diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 76bb2c83b..32202928e 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -181,7 +181,9 @@ export async function http(path: string, init?: RequestInit): Promise { // to the Go backend on :8787, whose CORS is open. // // Override either default with NEXT_PUBLIC_SSE_BASE (set it to "" to force same-origin). -// Token is appended as ?token= because SSE can't carry cookies cross-origin. +// A same-origin stream sends the artex_token cookie. The query token is added only +// when base is non-empty, which is the dev connection to :8787: that origin cannot +// send the cookie. // mockReport returns a canned Markdown report for the demo. function mockReport(_task?: string): string { return `# ARTEX Penetration Test Report — Acme Corp @@ -211,6 +213,9 @@ export function sseUrl(path: string): string { (process.env.NODE_ENV !== "production" && typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8787` : ""); + if (!base) { + return path; + } const token = getToken(); const sep = path.includes("?") ? "&" : "?"; return token ? `${base}${path}${sep}token=${encodeURIComponent(token)}` : `${base}${path}`; From ebc54b8751bd3c00016529c4ebc2aba77a18487e Mon Sep 17 00:00:00 2001 From: protonmatter Date: Tue, 17 Nov 2026 15:48:18 -0500 Subject: [PATCH 2/4] Bind sessions to a password version so revocation cannot tie inside one second. The hash and version commit together, a failed read rejects tokens, and the reset script tells the operator to restart. --- CHANGELOG.md | 1 + db/settings.go | 78 +++++++++++- db/settings_insert_test.go | 49 ++++++++ reset-password.sh | 21 +++- server/auth.go | 174 ++++++++++++++++--------- server/auth_epoch_test.go | 251 +++++++++++++++++++++++++++++++++++-- server/auth_test.go | 2 +- server/server.go | 44 +++++-- server/side_questions.go | 8 ++ 9 files changed, 549 insertions(+), 79 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5279232c8..38b39b46e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ All notable changes to this project are documented in this file. The format is b ### Changed +- **Password changes revoke sessions**: a password change stores a monotonic `auth.password_version` in the same transaction as the hash. Tokens carry that version, so a token from an older version is rejected, including when two changes land in the same second. `reset-password.sh` writes the same counter and requires an ARTEX restart, because the process reads the version at startup. A failed write leaves the previous session valid. Log, activity, and side-question streams re-check the token and close after the version moves. If the version cannot be read at startup, sessions are rejected until a read succeeds. - **Untrusted-output boundary is now on by default**: Norma frames tool results for the worker, planner, chat and main agent unless `ARTEX_UNTRUSTED_BOUNDARY` is set to `0`, `false`, `off` or `no`. It was opt-in via `ARTEX_UNTRUSTED_BOUNDARY=1` in 0.6.0 (#166); the default flips here (#203). - **Versioned migrations**: the `db` package applies numbered `db/migrations/NNNN_slug.sql` files once, in order, under the schema advisory lock, and records a SHA-256 checksum in `schema_migrations`; missing, renamed, changed or out-of-order migrations fail closed (#226). - **Coverage graph performance**: the coverage graph batches its connector lookups (three queries instead of one per root and per company) and adds the partial index `idx_ts_icp`; on a task of about 3,000 assets the p50 dropped from 126 ms to 27 ms and the queries per call from 221 to 3 (#230). diff --git a/db/settings.go b/db/settings.go index 7b3a3073f..8ba339a8b 100644 --- a/db/settings.go +++ b/db/settings.go @@ -1,6 +1,9 @@ package db -import "database/sql" +import ( + "database/sql" + "strconv" +) // Settings is a tiny key-value store for global app config the UI toggles at // runtime (e.g. traffic_capture). Missing keys fall back to caller defaults. @@ -66,6 +69,79 @@ ON CONFLICT (key) DO NOTHING`, key, value) return n > 0, nil } +// RotatePassword stores hash and increments the monotonic version in one +// transaction. A failure leaves both rows unchanged. The returned version is +// the value new sessions must carry. +func (d *DB) RotatePassword(hashKey, hash, versionKey string) (int64, error) { + tx, err := d.Begin() + if err != nil { + return 0, err + } + defer tx.Rollback() + sealed, err := sealSetting(hashKey, hash) + if err != nil { + return 0, err + } + if _, err := tx.Exec(` +INSERT INTO settings(key, value) VALUES ($1, $2) +ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, hashKey, sealed); err != nil { + return 0, err + } + var raw string + if err := tx.QueryRow(` +INSERT INTO settings(key, value) VALUES ($1, '1') +ON CONFLICT (key) DO UPDATE +SET value = (settings.value::bigint + 1)::text, updated_at = now() +RETURNING value`, versionKey).Scan(&raw); err != nil { + return 0, err + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return 0, err + } + if err := tx.Commit(); err != nil { + return 0, err + } + return n, nil +} + +// InsertPassword writes the hash only when that key is absent, and sets the +// version to 1 in the same transaction. inserted is false when the hash +// already exists; the version row is then left as it was. +func (d *DB) InsertPassword(hashKey, hash, versionKey string) (version int64, inserted bool, err error) { + tx, err := d.Begin() + if err != nil { + return 0, false, err + } + defer tx.Rollback() + sealed, err := sealSetting(hashKey, hash) + if err != nil { + return 0, false, err + } + res, err := tx.Exec(` +INSERT INTO settings(key, value) VALUES ($1, $2) +ON CONFLICT (key) DO NOTHING`, hashKey, sealed) + if err != nil { + return 0, false, err + } + n, err := res.RowsAffected() + if err != nil { + return 0, false, err + } + if n == 0 { + return 0, false, nil + } + if _, err := tx.Exec(` +INSERT INTO settings(key, value) VALUES ($1, '1') +ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, versionKey); err != nil { + return 0, false, err + } + if err := tx.Commit(); err != nil { + return 0, false, err + } + return 1, true, nil +} + // GetBool returns the boolean setting, or def when unset/unparseable. func (d *DB) GetBool(key string, def bool) bool { v, ok, err := d.GetSetting(key) diff --git a/db/settings_insert_test.go b/db/settings_insert_test.go index 6fea3c9f4..fd8065720 100644 --- a/db/settings_insert_test.go +++ b/db/settings_insert_test.go @@ -45,3 +45,52 @@ func TestInsertSettingIfAbsentDoesNotOverwrite(t *testing.T) { t.Fatalf("value was overwritten to %q, should stay %q", got, "first") } } + +// A version row that cannot increment must roll the hash write back with it. +func TestRotatePasswordRollsBackHashWhenVersionCannotIncrement(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + t.Skipf("postgres unavailable (%v)", err) + } + defer d.Close() + + stamp := time.Now().UnixNano() + hashKey := fmt.Sprintf("test.rotate_hash.%d", stamp) + versionKey := fmt.Sprintf("test.rotate_version.%d", stamp) + freshKey := fmt.Sprintf("test.rotate_fresh.%d", stamp) + defer func() { + _, _ = d.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2 OR key=$3`, hashKey, versionKey, freshKey) + }() + if err := d.SetSetting(hashKey, "old-hash"); err != nil { + t.Fatal(err) + } + if err := d.SetSetting(versionKey, "not-a-number"); err != nil { + t.Fatal(err) + } + if _, err := d.RotatePassword(hashKey, "new-hash", versionKey); err == nil { + t.Fatal("increment of a non-numeric version should fail") + } + got, ok, err := d.GetSetting(hashKey) + if err != nil || !ok || got != "old-hash" { + t.Fatalf("hash=%q ok=%v err=%v, want the previous hash", got, ok, err) + } + ver, _, err := d.GetSetting(versionKey) + if err != nil || ver != "not-a-number" { + t.Fatalf("version=%q err=%v, want the previous value", ver, err) + } + + n, err := d.RotatePassword(hashKey, "new-hash", freshKey) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("first version=%d want 1", n) + } + n, err = d.RotatePassword(hashKey, "newer-hash", freshKey) + if err != nil { + t.Fatal(err) + } + if n != 2 { + t.Fatalf("second version=%d want 2", n) + } +} diff --git a/reset-password.sh b/reset-password.sh index ab34d109a..70bf515a1 100755 --- a/reset-password.sh +++ b/reset-password.sh @@ -3,8 +3,10 @@ # ARTEX admin password reset script # # The login username is fixed as ARTEX; the password is stored as a bcrypt hash in -# the auth.password_hash key of the settings table. This script uses pgcrypto to -# generate the bcrypt hash in-database — compatible with the backend (x/crypto/bcrypt). +# the auth.password_hash key of the settings table. The same transaction increments +# auth.password_version. This script uses pgcrypto to generate the bcrypt hash +# in-database, compatible with the backend (x/crypto/bcrypt). The running process +# reads that version only at startup, so ARTEX must be restarted after a reset. # # Two deployments: # local (default) — host connects to the database directly with psql. Connection @@ -26,6 +28,7 @@ set -euo pipefail PASS_KEY="auth.password_hash" +VERSION_KEY="auth.password_version" BCRYPT_COST=10 MODE="" # local | docker (empty = auto-detect) @@ -138,15 +141,23 @@ NEWPASS_CHARS=$(printf '%s' "$NEWPASS" | LC_ALL=C tr -d '\200-\277' | wc -c) # Hand the password to psql via environment variable (read with \getenv, never in argv/ps) export ARTEX_RESET_NEWPASS="$NEWPASS" -# Generate bcrypt in-database and upsert; the password is auto-escaped with :'newpw'. CREATE EXTENSION is idempotent; -# if the database role lacks permission to create extensions it errors here (see the hint in the run failure branch below). +# Generate bcrypt in-database and upsert the hash and the password version in one +# transaction. The password is auto-escaped with :'newpw'. CREATE EXTENSION is +# idempotent; if the database role lacks permission to create extensions it errors +# here (see the hint in the run failure branch below). SQL=$(cat < 0 && (claims.IssuedAt == nil || claims.IssuedAt.Unix() < notBefore) { + if version > 0 && claims.Pwd != version { return false } return true } +// sessionOK reports whether token is still a session for the password version +// this process has loaded. A failed version read rejects every token. +func (s *Server) sessionOK(token string) bool { + if s.pwdState.Load() == pwdUnreadable { + return false + } + return verifyJWT(token, s.jwtKey, s.pwdVersion.Load()) +} + +func (s *Server) passwordHashKey() string { + if s.authHashKey != "" { + return s.authHashKey + } + return authPassKey +} + +func (s *Server) passwordVersionKey() string { + if s.authVersionKey != "" { + return s.authVersionKey + } + return authPwdVersionKey +} + +// applyPasswordVersion records a version that was just committed. +func (s *Server) applyPasswordVersion(n int64) { + s.pwdVersion.Store(n) + s.pwdState.Store(pwdReady) +} + // jwtSubject returns the subject of tokenStr when it is a valid, non-expired // HS256 token, and "" otherwise. func jwtSubject(tokenStr string, key []byte) string { @@ -209,7 +262,7 @@ func jwtSubject(tokenStr string, key []byte) string { // request's session token. func (s *Server) approver(r *http.Request) string { tok := extractToken(r) - if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) { + if !s.sessionOK(tok) { return "" } return jwtSubject(tok, s.jwtKey) @@ -241,7 +294,7 @@ func (s *Server) requireAuth(h http.Handler) http.Handler { writeErr(w, 401, "Unauthorized") return } - if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) { + if !s.sessionOK(tok) { writeErr(w, 401, "token is invalid or expired") return } @@ -258,7 +311,7 @@ func (s *Server) authStatus(w http.ResponseWriter, r *http.Request) { if pg == nil { return } - hash, _, err := pg.GetSetting(authPassKey) + hash, _, err := pg.GetSetting(s.passwordHashKey()) if err != nil { writeErr(w, 503, errDataSourceUnavailable) return @@ -277,7 +330,7 @@ func (s *Server) initSetupToken() { var err error for attempt := 1; attempt <= 3; attempt++ { var ok bool - hash, ok, err = s.m.pg.GetSetting(authPassKey) + hash, ok, err = s.m.pg.GetSetting(s.passwordHashKey()) if err == nil { if ok && hash != "" { return @@ -304,41 +357,43 @@ func (s *Server) initSetupToken() { log.Printf("[auth] no admin password is set. Setup token for the /setup page: %s", token) } -// loadPwdEpoch reads auth.password_epoch. A missing key leaves the cutoff at -// zero, which accepts every valid token. -func (s *Server) loadPwdEpoch() { +// loadPasswordVersion reads auth.password_version. A missing key leaves the +// version at zero, which accepts every valid token. A read that still fails +// after three tries rejects every token until a later read succeeds. +func (s *Server) loadPasswordVersion() { if s.m == nil || s.m.pg == nil { return } - raw, ok, err := s.m.pg.GetSetting(authPwdEpochKey) + var raw string + var ok bool + var err error + for attempt := 1; attempt <= 3; attempt++ { + raw, ok, err = s.m.pg.GetSetting(s.passwordVersionKey()) + if err == nil { + break + } + log.Printf("[auth] password version attempt %d/3: %v", attempt, err) + if attempt < 3 { + time.Sleep(time.Duration(attempt) * 100 * time.Millisecond) + } + } if err != nil { - log.Printf("[auth] password epoch: %v", err) + log.Printf("[auth] password version unreadable; rejecting sessions until it can be read: %v", err) + s.pwdState.Store(pwdUnreadable) return } if !ok || raw == "" { + s.pwdVersion.Store(0) + s.pwdState.Store(pwdReady) return } n, err := strconv.ParseInt(raw, 10, 64) - if err != nil { - log.Printf("[auth] password epoch %q: %v", raw, err) - return - } - s.pwdEpoch.Store(n) -} - -// bumpPwdEpoch records the current second as the oldest token that is still -// valid. A token signed in that same second still passes. A failed write leaves -// the previous cutoff in place and is logged; the password change itself stands. -func (s *Server) bumpPwdEpoch(pg *db.DB) { - if pg == nil { - return - } - epoch := time.Now().Unix() - if err := pg.SetSetting(authPwdEpochKey, strconv.FormatInt(epoch, 10)); err != nil { - log.Printf("[auth] save password epoch: %v", err) + if err != nil || n < 0 { + log.Printf("[auth] password version %q is not a counter; rejecting sessions", raw) + s.pwdState.Store(pwdUnreadable) return } - s.pwdEpoch.Store(epoch) + s.applyPasswordVersion(n) } // checkSetupToken compares got with the active setup token in constant time. @@ -356,7 +411,7 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) { if pg == nil { return } - existing, _, err := pg.GetSetting(authPassKey) + existing, _, err := pg.GetSetting(s.passwordHashKey()) if err != nil { writeErr(w, 503, errDataSourceUnavailable) return @@ -387,10 +442,10 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, "Password encryption failed") return } - // INSERT ... ON CONFLICT DO NOTHING instead of an upsert: the GetSetting above is - // only a fast-fail path; the real "first-set-only" guarantee rests on the primary - // key. bcrypt runs tens of milliseconds, another request may set the password meanwhile, and the read check itself can fail under an outage. - inserted, err := pg.InsertSettingIfAbsent(authPassKey, string(hash)) + // The hash and version commit in one transaction. ON CONFLICT DO NOTHING on the + // hash keeps the first password: the GetSetting above is only a fast-fail path. + // bcrypt runs tens of milliseconds, another request may set the password meanwhile, and the read check itself can fail under an outage. + version, inserted, err := pg.InsertPassword(s.passwordHashKey(), string(hash), s.passwordVersionKey()) if err != nil { writeErr(w, 500, "Save failed: "+err.Error()) return @@ -402,8 +457,8 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) { s.setupMu.Lock() s.setupToken = "" s.setupMu.Unlock() - s.bumpPwdEpoch(pg) - tok, err := signJWT(s.jwtKey) + s.applyPasswordVersion(version) + tok, err := signJWTVersion(s.jwtKey, version) if err != nil { writeErr(w, 500, "token generation failed") return @@ -419,7 +474,7 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) { if pg == nil { return } - if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) { + if !s.sessionOK(extractToken(r)) { writeErr(w, 401, "Unauthorized") return } @@ -439,7 +494,7 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, msg) return } - hash, ok, err := pg.GetSetting(authPassKey) + hash, ok, err := pg.GetSetting(s.passwordHashKey()) if err != nil { writeErr(w, 503, errDataSourceUnavailable) return @@ -457,13 +512,14 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, "Password encryption failed") return } - if err := pg.SetSetting(authPassKey, string(newHash)); err != nil { + // Hash and version commit together. A failed write returns 500 and leaves + // the previous session valid. This response has no replacement token. + version, err := pg.RotatePassword(s.passwordHashKey(), string(newHash), s.passwordVersionKey()) + if err != nil { writeErr(w, 500, "Save failed: "+err.Error()) return } - // Sessions issued before this second stop working. This response does not - // include a replacement token; the next request asks for a new login. - s.bumpPwdEpoch(pg) + s.applyPasswordVersion(version) writeJSON(w, 200, map[string]any{"ok": true}) } @@ -500,7 +556,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request, getSetting func(s writeErr(w, 401, "Incorrect username or password") return } - hash, ok, err := getSetting(authPassKey) + hash, ok, err := getSetting(s.passwordHashKey()) if err != nil { writeErr(w, 503, errDataSourceUnavailable) return @@ -514,7 +570,11 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request, getSetting func(s return } s.loginLimit.reset(ip) - tok, err := signJWT(s.jwtKey) + if s.pwdState.Load() == pwdUnreadable { + writeErr(w, 503, errDataSourceUnavailable) + return + } + tok, err := signJWTVersion(s.jwtKey, s.pwdVersion.Load()) if err != nil { writeErr(w, 500, "token generation failed") return diff --git a/server/auth_epoch_test.go b/server/auth_epoch_test.go index 14e538661..2f0188c82 100644 --- a/server/auth_epoch_test.go +++ b/server/auth_epoch_test.go @@ -1,23 +1,260 @@ package server import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" "testing" "time" ) -func TestTokenBeforePasswordEpochIsRejected(t *testing.T) { +func TestPasswordVersionClaim(t *testing.T) { key := []byte("0123456789abcdef0123456789abcdef") + legacy, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + previous, err := signJWTVersion(key, 1) + if err != nil { + t.Fatal(err) + } + current, err := signJWTVersion(key, 2) + if err != nil { + t.Fatal(err) + } + if !verifyJWT(legacy, key, 0) { + t.Fatal("before any password change a token must be accepted") + } + if verifyJWT(legacy, key, 2) || verifyJWT(previous, key, 2) { + t.Fatal("a token from an older password version must be rejected") + } + if !verifyJWT(current, key, 2) { + t.Fatal("a token carrying the current version must be accepted") + } + // Two signatures in the same second still differ by version. + newest, err := signJWTVersion(key, 3) + if err != nil { + t.Fatal(err) + } + if verifyJWT(current, key, 3) { + t.Fatal("two changes in the same second must not leave the older token valid") + } + if !verifyJWT(newest, key, 3) { + t.Fatal("the newest version must be accepted") + } +} + +func TestChangePasswordRevokesOldTokenAndKeepsItWhenSaveFails(t *testing.T) { + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Skipf("postgres unavailable (%v)", err) + } + defer m.Close() + + stamp := time.Now().UnixNano() + s := &Server{ + m: m, + jwtKey: []byte("0123456789abcdef0123456789abcdef"), + loginLimit: newLoginLimiter(time.Now), + authHashKey: fmt.Sprintf("test.password_hash.%d", stamp), + authVersionKey: fmt.Sprintf("test.password_version.%d", stamp), + } + t.Cleanup(func() { + _, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, s.authHashKey, s.authVersionKey) + }) + + s.setupToken = "setup-ok" + initBody := `{"password":"correct-horse-1","setup_token":"setup-ok"}` + w := httptest.NewRecorder() + s.authInit(w, httptest.NewRequest("POST", "/api/auth/init", strings.NewReader(initBody))) + if w.Code != 200 { + t.Fatalf("init status=%d body=%s", w.Code, w.Body.String()) + } + var issued struct { + Token string `json:"token"` + } + if err := json.Unmarshal(w.Body.Bytes(), &issued); err != nil || issued.Token == "" { + t.Fatalf("init token: %v body=%s", err, w.Body.String()) + } + if !s.sessionOK(issued.Token) { + t.Fatal("token from init was rejected") + } + + change := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(`{"old_password":"correct-horse-1","new_password":"correct-horse-2"}`)) + change.Header.Set("Authorization", "Bearer "+issued.Token) + w = httptest.NewRecorder() + s.authChangePassword(w, change) + if w.Code != 200 { + t.Fatalf("change status=%d body=%s", w.Code, w.Body.String()) + } + if s.sessionOK(issued.Token) { + t.Fatal("token from before the password change is still accepted") + } + + w = httptest.NewRecorder() + s.authLogin(w, httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-2"}`))) + if w.Code != 200 { + t.Fatalf("login status=%d body=%s", w.Code, w.Body.String()) + } + var logged struct { + Token string `json:"token"` + } + if err := json.Unmarshal(w.Body.Bytes(), &logged); err != nil || logged.Token == "" { + t.Fatalf("login token: %v body=%s", err, w.Body.String()) + } + if !s.sessionOK(logged.Token) { + t.Fatal("replacement token was rejected") + } + + reached := false + s.requireAuth(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + reached = true + })).ServeHTTP(httptest.NewRecorder(), requestWithToken("GET", "/api/tasks", issued.Token)) + if reached { + t.Fatal("revoked token reached a protected handler") + } + + if _, err := m.pg.Exec(`UPDATE settings SET value='not-a-number' WHERE key=$1`, s.authVersionKey); err != nil { + t.Fatal(err) + } + before := s.pwdVersion.Load() + fail := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(`{"old_password":"correct-horse-2","new_password":"correct-horse-3"}`)) + fail.Header.Set("Authorization", "Bearer "+logged.Token) + w = httptest.NewRecorder() + s.authChangePassword(w, fail) + if w.Code != 500 { + t.Fatalf("failed save status=%d want 500 body=%s", w.Code, w.Body.String()) + } + if s.pwdVersion.Load() != before { + t.Fatalf("version moved from %d to %d after a failed save", before, s.pwdVersion.Load()) + } + if !s.sessionOK(logged.Token) { + t.Fatal("a failed save revoked the current token") + } + w = httptest.NewRecorder() + s.authLogin(w, httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-2"}`))) + if w.Code != 200 { + t.Fatalf("old password after a failed save: status=%d body=%s", w.Code, w.Body.String()) + } + w = httptest.NewRecorder() + s.authLogin(w, httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-3"}`))) + if w.Code == 200 { + t.Fatal("new password was stored even though the version write failed") + } +} + +func TestUnreadablePasswordVersionRejectsSessions(t *testing.T) { + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Skipf("postgres unavailable (%v)", err) + } + defer m.Close() + key := []byte("0123456789abcdef0123456789abcdef") + s := &Server{m: m, jwtKey: key, loginLimit: newLoginLimiter(time.Now)} + s.authVersionKey = fmt.Sprintf("test.password_version.%d", time.Now().UnixNano()) + tok, err := signJWTVersion(key, 1) + if err != nil { + t.Fatal(err) + } + s.applyPasswordVersion(1) + if !s.sessionOK(tok) { + t.Fatal("token was rejected before the read failed") + } + if err := m.pg.Close(); err != nil { + t.Fatal(err) + } + s.loadPasswordVersion() + if s.pwdState.Load() != pwdUnreadable { + t.Fatalf("state=%d want unreadable", s.pwdState.Load()) + } + if s.sessionOK(tok) { + t.Fatal("accepted a token while the password version was unreadable") + } + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(`{"old_password":"correct-horse-1","new_password":"correct-horse-2"}`)) + req.Header.Set("Authorization", "Bearer "+tok) + s.authChangePassword(w, req) + if w.Code != 401 { + t.Fatalf("change while unreadable: status=%d want 401 body=%s", w.Code, w.Body.String()) + } +} + +func TestAbsentPasswordVersionKeepsSessions(t *testing.T) { + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Skipf("postgres unavailable (%v)", err) + } + defer m.Close() + key := []byte("0123456789abcdef0123456789abcdef") + s := &Server{ + m: m, + jwtKey: key, + authVersionKey: fmt.Sprintf("test.missing.version.%d", time.Now().UnixNano()), + } + s.loadPasswordVersion() + if s.pwdState.Load() != pwdReady || s.pwdVersion.Load() != 0 { + t.Fatalf("state=%d version=%d, want ready at 0", s.pwdState.Load(), s.pwdVersion.Load()) + } tok, err := signJWT(key) if err != nil { t.Fatal(err) } - if !verifyJWT(tok, key, 0) { - t.Fatal("a token with no password epoch must be accepted") + if !s.sessionOK(tok) { + t.Fatal("a token was rejected when no password version is stored") + } +} + +func TestStreamLogsStopsWhenPasswordVersionChanges(t *testing.T) { + key := []byte("0123456789abcdef0123456789abcdef") + s := &Server{jwtKey: key} + s.applyPasswordVersion(1) + tok, err := signJWTVersion(key, 1) + if err != nil { + t.Fatal(err) + } + _, cursor := logSink.recent(0, 1) + ready := make(chan struct{}) + var once sync.Once + w := &flushNotify{ResponseWriter: httptest.NewRecorder(), notify: func() { + once.Do(func() { close(ready) }) + }} + req := requestWithToken("GET", fmt.Sprintf("/api/logs/stream?since=%d", cursor), tok) + done := make(chan struct{}) + go func() { + s.streamLogs(w, req) + close(done) + }() + select { + case <-ready: + case <-time.After(2 * time.Second): + t.Fatal("log stream did not start") } - if verifyJWT(tok, key, time.Now().Add(time.Minute).Unix()) { - t.Fatal("a token issued before the password epoch must be rejected") + s.applyPasswordVersion(2) + logSink.add(LogLine{Text: "after password change"}) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("log stream stayed open after the password version changed") } - if !verifyJWT(tok, key, time.Now().Add(-time.Minute).Unix()) { - t.Fatal("a token issued after the password epoch must be accepted") +} + +func requestWithToken(method, target, token string) *http.Request { + r := httptest.NewRequest(method, target, nil) + r.Header.Set("Authorization", "Bearer "+token) + return r +} + +type flushNotify struct { + http.ResponseWriter + notify func() +} + +func (f *flushNotify) Flush() { + f.notify() + if fl, ok := f.ResponseWriter.(http.Flusher); ok { + fl.Flush() } } diff --git a/server/auth_test.go b/server/auth_test.go index 597537702..9a3ad594f 100644 --- a/server/auth_test.go +++ b/server/auth_test.go @@ -249,7 +249,7 @@ func TestAuthInitRequiresSetupToken(t *testing.T) { } defer m.Close() clearPassword := func() { - if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, authPassKey); err != nil { + if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, authPassKey, authPwdVersionKey); err != nil { t.Fatal(err) } } diff --git a/server/server.go b/server/server.go index f6b468ce6..66d367fa8 100644 --- a/server/server.go +++ b/server/server.go @@ -54,10 +54,16 @@ type Server struct { setupMu sync.Mutex setupToken string // one-time token POST /api/auth/init requires; empty when none is active - // pwdEpoch is auth.password_epoch in Unix seconds. Zero means the setting - // is absent and every valid token is accepted. A token issued before the - // stored second is rejected. - pwdEpoch atomic.Int64 + // pwdVersion is auth.password_version, a counter. Zero means no password + // change is stored yet, and any valid token is accepted. pwdState is + // pwdUnreadable when that counter could not be read; every session is + // rejected until a later read succeeds. + pwdVersion atomic.Int64 + pwdState atomic.Int32 + // authHashKey and authVersionKey override the settings keys. Empty uses + // the production keys. Tests set unique keys so a shared database is left alone. + authHashKey string + authVersionKey string loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP @@ -175,7 +181,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi o(s) } s.initSetupToken() - s.loadPwdEpoch() + s.loadPasswordVersion() s.initSideQuestions() // Circuit-breaker thresholds/cooldowns are hot parameters on the failure path; push the global retry policy to the Registry once at startup, // and again on every policy save (saveLLMRetryPolicy). @@ -1039,7 +1045,7 @@ func (s *Server) Handler() http.Handler { // with a valid token gets the service name and version; the web UI's top bar // reads the version, and sends its token. func (s *Server) health(w http.ResponseWriter, r *http.Request) { - if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) { + if !s.sessionOK(extractToken(r)) { writeJSON(w, 200, map[string]any{"ok": true}) return } @@ -3244,6 +3250,11 @@ func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, "streaming unsupported") return } + tok := extractToken(r) + if !s.sessionOK(tok) { + writeErr(w, 401, "token is invalid or expired") + return + } since := int64(atoiDefault(r.URL.Query().Get("since"), 0)) w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") @@ -3259,6 +3270,9 @@ func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { } lines, cursor := logSink.recent(since, 1000) for _, l := range lines { + if !s.sessionOK(tok) { + return + } send(l) } if cursor > since { @@ -3274,7 +3288,7 @@ func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { case <-ctx.Done(): return case l, ok := <-ch: - if !ok { + if !ok || !s.sessionOK(tok) { return } if l.Seq <= since { @@ -3283,6 +3297,9 @@ func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { since = l.Seq send(l) case <-ping.C: + if !s.sessionOK(tok) { + return + } fmt.Fprint(w, ": ping\n\n") flusher.Flush() } @@ -3290,6 +3307,11 @@ func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { } func (s *Server) streamActivity(w http.ResponseWriter, r *http.Request) { + tok := extractToken(r) + if !s.sessionOK(tok) { + writeErr(w, 401, "token is invalid or expired") + return + } t := s.m.ResolveTask(r.URL.Query().Get("task")) if t == nil { writeErr(w, 404, "task not found") @@ -3350,6 +3372,9 @@ func (s *Server) streamActivity(w http.ResponseWriter, r *http.Request) { return } for _, a := range items { + if !s.sessionOK(tok) { + return + } sendSSE(a) } if cursor > since { @@ -3369,7 +3394,7 @@ func (s *Server) streamActivity(w http.ResponseWriter, r *http.Request) { case <-ctx.Done(): return case a, ok := <-ch: - if !ok { + if !ok || !s.sessionOK(tok) { return } if a.ID <= since { @@ -3381,6 +3406,9 @@ func (s *Server) streamActivity(w http.ResponseWriter, r *http.Request) { since = a.ID sendSSE(a) case <-ping.C: + if !s.sessionOK(tok) { + return + } fmt.Fprint(w, ": ping\n\n") flusher.Flush() } diff --git a/server/side_questions.go b/server/side_questions.go index 641170bc3..84c2d6ca4 100644 --- a/server/side_questions.go +++ b/server/side_questions.go @@ -526,6 +526,11 @@ func (s *Server) cancelSideRequest(w http.ResponseWriter, r *http.Request) { } func (s *Server) sideEvents(w http.ResponseWriter, r *http.Request) { + tok := extractToken(r) + if !s.sessionOK(tok) { + writeErr(w, 401, "token is invalid or expired") + return + } flusher, ok := w.(http.Flusher) if !ok { writeErr(w, 500, "streaming unavailable") @@ -550,6 +555,9 @@ func (s *Server) sideEvents(w http.ResponseWriter, r *http.Request) { heartbeat := time.NewTicker(15 * time.Second) defer heartbeat.Stop() for { + if !s.sessionOK(tok) { + return + } e := first first = nil if e == nil { From 7cac9c240b435d263373a1ce453f2151740cf872 Mon Sep 17 00:00:00 2001 From: protonmatter Date: Tue, 17 Nov 2026 16:25:54 -0500 Subject: [PATCH 3/4] Retry the password version on login when startup could not read it. --- CHANGELOG.md | 2 +- server/auth.go | 13 +++++--- server/auth_epoch_test.go | 63 +++++++++++++++++++++++++++++++++++++++ server/server.go | 2 +- 4 files changed, 74 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b39b46e..94aad22f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ All notable changes to this project are documented in this file. The format is b ### Changed -- **Password changes revoke sessions**: a password change stores a monotonic `auth.password_version` in the same transaction as the hash. Tokens carry that version, so a token from an older version is rejected, including when two changes land in the same second. `reset-password.sh` writes the same counter and requires an ARTEX restart, because the process reads the version at startup. A failed write leaves the previous session valid. Log, activity, and side-question streams re-check the token and close after the version moves. If the version cannot be read at startup, sessions are rejected until a read succeeds. +- **Password changes revoke sessions**: a password change stores a monotonic `auth.password_version` in the same transaction as the hash. Tokens carry that version, so a token from an older version is rejected, including when two changes land in the same second. `reset-password.sh` writes the same counter and requires an ARTEX restart, because the process reads the version at startup. A failed write leaves the previous session valid. Log, activity, and side-question streams re-check the token and close after the version moves. If the version cannot be read at startup, sessions are rejected until the next login reads it. - **Untrusted-output boundary is now on by default**: Norma frames tool results for the worker, planner, chat and main agent unless `ARTEX_UNTRUSTED_BOUNDARY` is set to `0`, `false`, `off` or `no`. It was opt-in via `ARTEX_UNTRUSTED_BOUNDARY=1` in 0.6.0 (#166); the default flips here (#203). - **Versioned migrations**: the `db` package applies numbered `db/migrations/NNNN_slug.sql` files once, in order, under the schema advisory lock, and records a SHA-256 checksum in `schema_migrations`; missing, renamed, changed or out-of-order migrations fail closed (#226). - **Coverage graph performance**: the coverage graph batches its connector lookups (three queries instead of one per root and per company) and adds the partial index `idx_ts_icp`; on a task of about 3,000 assets the p50 dropped from 126 ms to 27 ms and the queries per call from 221 to 3 (#230). diff --git a/server/auth.go b/server/auth.go index 3f186f981..006d5fca4 100644 --- a/server/auth.go +++ b/server/auth.go @@ -214,7 +214,8 @@ func verifyJWT(tokenStr string, key []byte, version int64) bool { } // sessionOK reports whether token is still a session for the password version -// this process has loaded. A failed version read rejects every token. +// this process has loaded. A failed version read rejects every token until +// login reads the counter again. func (s *Server) sessionOK(token string) bool { if s.pwdState.Load() == pwdUnreadable { return false @@ -359,7 +360,8 @@ func (s *Server) initSetupToken() { // loadPasswordVersion reads auth.password_version. A missing key leaves the // version at zero, which accepts every valid token. A read that still fails -// after three tries rejects every token until a later read succeeds. +// after three tries rejects every token. Login calls this again when the +// state is unreadable, and stays closed if that read fails too. func (s *Server) loadPasswordVersion() { if s.m == nil || s.m.pg == nil { return @@ -378,7 +380,7 @@ func (s *Server) loadPasswordVersion() { } } if err != nil { - log.Printf("[auth] password version unreadable; rejecting sessions until it can be read: %v", err) + log.Printf("[auth] password version unreadable; rejecting sessions until login can read it: %v", err) s.pwdState.Store(pwdUnreadable) return } @@ -389,7 +391,7 @@ func (s *Server) loadPasswordVersion() { } n, err := strconv.ParseInt(raw, 10, 64) if err != nil || n < 0 { - log.Printf("[auth] password version %q is not a counter; rejecting sessions", raw) + log.Printf("[auth] password version %q is not a counter; rejecting sessions until login can read it", raw) s.pwdState.Store(pwdUnreadable) return } @@ -570,6 +572,9 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request, getSetting func(s return } s.loginLimit.reset(ip) + if s.pwdState.Load() == pwdUnreadable { + s.loadPasswordVersion() + } if s.pwdState.Load() == pwdUnreadable { writeErr(w, 503, errDataSourceUnavailable) return diff --git a/server/auth_epoch_test.go b/server/auth_epoch_test.go index 2f0188c82..6ac3a9c9c 100644 --- a/server/auth_epoch_test.go +++ b/server/auth_epoch_test.go @@ -182,6 +182,69 @@ func TestUnreadablePasswordVersionRejectsSessions(t *testing.T) { } } +func TestLoginRereadsPasswordVersionWhenUnreadable(t *testing.T) { + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Skipf("postgres unavailable (%v)", err) + } + defer m.Close() + + stamp := time.Now().UnixNano() + s := &Server{ + m: m, + jwtKey: []byte("0123456789abcdef0123456789abcdef"), + loginLimit: newLoginLimiter(time.Now), + authHashKey: fmt.Sprintf("test.password_hash.%d", stamp), + authVersionKey: fmt.Sprintf("test.password_version.%d", stamp), + } + t.Cleanup(func() { + _, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, s.authHashKey, s.authVersionKey) + }) + s.setupToken = "setup-ok" + w := httptest.NewRecorder() + s.authInit(w, httptest.NewRequest("POST", "/api/auth/init", strings.NewReader(`{"password":"correct-horse-1","setup_token":"setup-ok"}`))) + if w.Code != 200 { + t.Fatalf("init status=%d body=%s", w.Code, w.Body.String()) + } + if _, err := m.pg.Exec(`UPDATE settings SET value='not-a-number' WHERE key=$1`, s.authVersionKey); err != nil { + t.Fatal(err) + } + s.pwdVersion.Store(99) + s.loadPasswordVersion() + if s.pwdState.Load() != pwdUnreadable { + t.Fatalf("state=%d want unreadable", s.pwdState.Load()) + } + w = httptest.NewRecorder() + s.authLogin(w, httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-1"}`))) + if w.Code != 503 { + t.Fatalf("login while unreadable: status=%d want 503 body=%s", w.Code, w.Body.String()) + } + if s.pwdState.Load() != pwdUnreadable { + t.Fatal("a failed reread opened sessions") + } + + if _, err := m.pg.Exec(`UPDATE settings SET value='1' WHERE key=$1`, s.authVersionKey); err != nil { + t.Fatal(err) + } + w = httptest.NewRecorder() + s.authLogin(w, httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-1"}`))) + if w.Code != 200 { + t.Fatalf("login after the version can be read: status=%d body=%s", w.Code, w.Body.String()) + } + if s.pwdState.Load() != pwdReady || s.pwdVersion.Load() != 1 { + t.Fatalf("state=%d version=%d, want ready at 1", s.pwdState.Load(), s.pwdVersion.Load()) + } + var logged struct { + Token string `json:"token"` + } + if err := json.Unmarshal(w.Body.Bytes(), &logged); err != nil || logged.Token == "" { + t.Fatalf("login token: %v body=%s", err, w.Body.String()) + } + if !s.sessionOK(logged.Token) { + t.Fatal("token from the healed login was rejected") + } +} + func TestAbsentPasswordVersionKeepsSessions(t *testing.T) { m, err := NewManager(t.TempDir(), "") if err != nil { diff --git a/server/server.go b/server/server.go index 66d367fa8..aeba273a4 100644 --- a/server/server.go +++ b/server/server.go @@ -57,7 +57,7 @@ type Server struct { // pwdVersion is auth.password_version, a counter. Zero means no password // change is stored yet, and any valid token is accepted. pwdState is // pwdUnreadable when that counter could not be read; every session is - // rejected until a later read succeeds. + // rejected until login reads it again. pwdVersion atomic.Int64 pwdState atomic.Int32 // authHashKey and authVersionKey override the settings keys. Empty uses From 134562c3d9c09fa0fb3e2be3e8efe806b6ccb360 Mon Sep 17 00:00:00 2001 From: protonmatter Date: Tue, 17 Nov 2026 16:39:44 -0500 Subject: [PATCH 4/4] Drop the unused database import and align the password constants. --- server/auth.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/auth.go b/server/auth.go index 006d5fca4..b3532d1ff 100644 --- a/server/auth.go +++ b/server/auth.go @@ -19,7 +19,6 @@ import ( "golang.org/x/crypto/bcrypt" "github.com/Autumn-27/artex/config" - "github.com/Autumn-27/artex/db" ) const ( @@ -27,7 +26,7 @@ const ( authPassKey = "auth.password_hash" authPwdVersionKey = "auth.password_version" jwtTTL = 7 * 24 * time.Hour - keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // The lower bound matches the setup page's frontend validation — validation that // lives only in the frontend is as good as none: hitting the API directly bypasses