Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
78 changes: 77 additions & 1 deletion db/settings.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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)
Expand Down
49 changes: 49 additions & 0 deletions db/settings_insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
21 changes: 16 additions & 5 deletions reset-password.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
)

Expand Down Expand Up @@ -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."
Loading
Loading