mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-18 22:20:56 +08:00
Merge pull request #301 from Protonmatter/protonmatter/session-epoch
Reject sessions issued before a password change
This commit is contained in:
@@ -28,6 +28,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 the next login reads it.
|
||||
- **Task budgets survive a restart**: planner, worker, judge, and compactor rows in `llm_usage` are counted back into `ARTEX_TASK_BUDGET_*`. A restored task already inside the wrap-up reserve only has that reserve left, so the run wraps up instead of starting another worker. The per-worker estimate is not restored and starts from the defaults (50,000 tokens and 10 turns) until a worker finishes in this process. Chat, goal decomposition, and side questions stay outside the cap.
|
||||
- **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).
|
||||
|
||||
+77
-1
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+16
-5
@@ -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 <<SQL
|
||||
\\set ON_ERROR_STOP on
|
||||
\\getenv newpw ARTEX_RESET_NEWPASS
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
BEGIN;
|
||||
INSERT INTO settings(key, value)
|
||||
VALUES ('$PASS_KEY', crypt(:'newpw', gen_salt('bf', $BCRYPT_COST)))
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now();
|
||||
INSERT INTO settings(key, value)
|
||||
VALUES ('$VERSION_KEY', '1')
|
||||
ON CONFLICT (key) DO UPDATE
|
||||
SET value = (settings.value::bigint + 1)::text, updated_at = now();
|
||||
COMMIT;
|
||||
SQL
|
||||
)
|
||||
|
||||
@@ -236,4 +247,4 @@ else
|
||||
fi
|
||||
|
||||
unset ARTEX_RESET_NEWPASS
|
||||
echo "✓ ARTEX admin password has been reset. Log in with username ARTEX + the new password (no service restart needed)."
|
||||
echo "✓ ARTEX admin password has been reset. Restart ARTEX, then log in with username ARTEX and the new password. Sessions from before the restart stop working."
|
||||
|
||||
+169
-29
@@ -22,10 +22,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
jwtKeyFilename = "jwt.key"
|
||||
authPassKey = "auth.password_hash"
|
||||
jwtTTL = 7 * 24 * time.Hour
|
||||
keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
jwtKeyFilename = "jwt.key"
|
||||
authPassKey = "auth.password_hash"
|
||||
authPwdVersionKey = "auth.password_version"
|
||||
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
|
||||
@@ -41,6 +42,14 @@ const (
|
||||
// unauthenticated request through on a database error, overwriting the admin password.
|
||||
const errDataSourceUnavailable = "Data source temporarily unavailable, please retry later"
|
||||
|
||||
// pwdState values. The zero value is unread, which still accepts a valid token
|
||||
// at version 0. unreadable means a startup read failed and every token is rejected.
|
||||
const (
|
||||
pwdUnread int32 = iota
|
||||
pwdReady
|
||||
pwdUnreadable
|
||||
)
|
||||
|
||||
// validatePassword returns an empty string when passing, otherwise a reason ready to show the user.
|
||||
func validatePassword(pw string) string {
|
||||
if utf8.RuneCountInString(pw) < minPasswordRunes {
|
||||
@@ -158,24 +167,79 @@ func samePath(a, b string) bool {
|
||||
return a == b
|
||||
}
|
||||
|
||||
// signJWT issues a 7-day HS256 token for user ARTEX.
|
||||
// sessionClaims carries the password version the token was signed under.
|
||||
// Two changes in the same second get different versions, so a cutoff based on
|
||||
// the issued-at second cannot leave the older token valid.
|
||||
type sessionClaims struct {
|
||||
Pwd int64 `json:"pwd"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// signJWT issues a 7-day HS256 token for user ARTEX at password version 0.
|
||||
func signJWT(key []byte) (string, error) {
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
|
||||
Subject: "ARTEX",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtTTL)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
return signJWTVersion(key, 0)
|
||||
}
|
||||
|
||||
// signJWTVersion issues a 7-day HS256 token bound to a password version.
|
||||
func signJWTVersion(key []byte, version int64) (string, error) {
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, sessionClaims{
|
||||
Pwd: version,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: "ARTEX",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtTTL)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}).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) {
|
||||
// version 0 means no password change is stored yet, and any valid token is
|
||||
// accepted. A later version requires the token's pwd claim to equal it.
|
||||
func verifyJWT(tokenStr string, key []byte, version int64) bool {
|
||||
claims := &sessionClaims{}
|
||||
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 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 until
|
||||
// login reads the counter again.
|
||||
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
|
||||
@@ -197,7 +261,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 !s.sessionOK(tok) {
|
||||
return ""
|
||||
}
|
||||
return jwtSubject(tok, s.jwtKey)
|
||||
}
|
||||
|
||||
// extractToken reads the JWT from Authorization: Bearer header,
|
||||
@@ -226,7 +294,7 @@ func (s *Server) requireAuth(h http.Handler) http.Handler {
|
||||
writeErr(w, 401, "Unauthorized")
|
||||
return
|
||||
}
|
||||
if !verifyJWT(tok, s.jwtKey) {
|
||||
if !s.sessionOK(tok) {
|
||||
writeErr(w, 401, "token is invalid or expired")
|
||||
return
|
||||
}
|
||||
@@ -243,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
|
||||
@@ -258,15 +326,75 @@ 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(s.passwordHashKey())
|
||||
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)
|
||||
}
|
||||
|
||||
// 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. 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
|
||||
}
|
||||
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 version unreadable; rejecting sessions until login can read it: %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 || n < 0 {
|
||||
log.Printf("[auth] password version %q is not a counter; rejecting sessions until login can read it", raw)
|
||||
s.pwdState.Store(pwdUnreadable)
|
||||
return
|
||||
}
|
||||
s.applyPasswordVersion(n)
|
||||
}
|
||||
|
||||
// checkSetupToken compares got with the active setup token in constant time.
|
||||
@@ -284,7 +412,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
|
||||
@@ -315,10 +443,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
|
||||
@@ -330,7 +458,8 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) {
|
||||
s.setupMu.Lock()
|
||||
s.setupToken = ""
|
||||
s.setupMu.Unlock()
|
||||
tok, err := signJWT(s.jwtKey)
|
||||
s.applyPasswordVersion(version)
|
||||
tok, err := signJWTVersion(s.jwtKey, version)
|
||||
if err != nil {
|
||||
writeErr(w, 500, "token generation failed")
|
||||
return
|
||||
@@ -346,7 +475,7 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
if !verifyJWT(extractToken(r), s.jwtKey) {
|
||||
if !s.sessionOK(extractToken(r)) {
|
||||
writeErr(w, 401, "Unauthorized")
|
||||
return
|
||||
}
|
||||
@@ -366,7 +495,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
|
||||
@@ -384,10 +513,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
|
||||
}
|
||||
s.applyPasswordVersion(version)
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
@@ -424,7 +557,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
|
||||
@@ -438,7 +571,14 @@ 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 {
|
||||
s.loadPasswordVersion()
|
||||
}
|
||||
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
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
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 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 {
|
||||
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 !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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+22
-4
@@ -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.
|
||||
|
||||
@@ -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}
|
||||
|
||||
+37
-3
@@ -19,6 +19,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
@@ -53,6 +54,16 @@ type Server struct {
|
||||
|
||||
setupMu sync.Mutex
|
||||
setupToken string // one-time token POST /api/auth/init requires; empty when none is active
|
||||
// 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 login reads it again.
|
||||
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
|
||||
@@ -173,6 +184,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
|
||||
o(s)
|
||||
}
|
||||
s.initSetupToken()
|
||||
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).
|
||||
@@ -1036,7 +1048,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 !s.sessionOK(extractToken(r)) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
return
|
||||
}
|
||||
@@ -3241,6 +3253,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")
|
||||
@@ -3256,6 +3273,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 {
|
||||
@@ -3271,7 +3291,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 {
|
||||
@@ -3280,6 +3300,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()
|
||||
}
|
||||
@@ -3287,6 +3310,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")
|
||||
@@ -3347,6 +3375,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 {
|
||||
@@ -3366,7 +3397,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 {
|
||||
@@ -3378,6 +3409,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()
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+6
-1
@@ -181,7 +181,9 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// 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}`;
|
||||
|
||||
Reference in New Issue
Block a user