server: config, migrations, redacted logging, /healthz entrypoint (#16)

This commit is contained in:
2026-11-14 21:40:39 +01:00
parent 143cb534dc
commit f376efdc39
9 changed files with 750 additions and 0 deletions
+138
View File
@@ -0,0 +1,138 @@
## Config keys (DESIGN 11.1; names FIXED owner-delegated, #16): flags win over env wins over defaults.
## The bind address is a constant, not a key: the server always listens on 127.0.0.1 (T15).
import std/[unittest, tables, strutils]
import config
proc envOf(pairs: openArray[(string, string)]): EnvLookup =
let t = pairs.toTable
result = proc(k: string): string {.closure.} =
if k in t: t[k] else: ""
let noEnv = envOf([])
proc parseErr(args: openArray[string], env: EnvLookup = noEnv): string =
try:
discard parseConfig(args, env)
"<none>"
except ConfigError as e:
e.msg
suite "config defaults":
test "defaults: dev origin, port 9000, state dir run":
let c = parseConfig([], noEnv)
check c.publicOrigin == DefaultPublicOrigin
check c.publicOrigin == "http://localhost:8080"
check c.port == DefaultPort
check c.port == 9000
check c.stateDir == DefaultStateDir
check c.stateDir == "run"
check c.dbPath == "run/state.db"
test "state dir is joined, not concatenated":
let c = parseConfig(["--state-dir", "/var/lib/fff-vtt"], noEnv)
check c.dbPath == "/var/lib/fff-vtt/state.db"
test "bind address is fixed 127.0.0.1 and not a config key":
check BindAddress == "127.0.0.1"
check "--bind" in parseErr(["--bind=0.0.0.0"])
suite "config env":
test "env sets all three keys":
let c = parseConfig([], envOf([
("FFF_VTT_PUBLIC_ORIGIN", "https://vtt.example"),
("FFF_VTT_PORT", "9100"),
("FFF_VTT_STATE_DIR", "/srv/fff")]))
check c.publicOrigin == "https://vtt.example"
check c.port == 9100
check c.stateDir == "/srv/fff"
test "empty env keys fall back to defaults":
let c = parseConfig([], envOf([("FFF_VTT_PORT", ""), ("FFF_VTT_STATE_DIR", " ")]))
check c.port == DefaultPort
check c.stateDir == DefaultStateDir
test "bad env port is an error, not a default":
check "FFF_VTT_PORT" in parseErr([], envOf([("FFF_VTT_PORT", "http")]))
suite "config flags":
test "flags override env":
let c = parseConfig(["--public-origin=https://a.example", "--port", "9200",
"--state-dir=/tmp/x"], envOf([
("FFF_VTT_PUBLIC_ORIGIN", "https://b.example"),
("FFF_VTT_PORT", "9100"),
("FFF_VTT_STATE_DIR", "/srv/old")]))
check c.publicOrigin == "https://a.example"
check c.port == 9200
check c.stateDir == "/tmp/x"
test "--key=value and --key value are both accepted":
check parseConfig(["--port=9301"], noEnv).port == 9301
check parseConfig(["--port", "9302"], noEnv).port == 9302
test "trailing slash on the origin and on the state dir is dropped":
let c = parseConfig(["--public-origin=https://vtt.example/", "--state-dir=run/test/"], noEnv)
check c.publicOrigin == "https://vtt.example"
check c.stateDir == "run/test"
test "root state dir is not mangled":
check parseConfig(["--state-dir=/"], noEnv).stateDir == "/"
test "last flag wins":
check parseConfig(["--port=9303", "--port=9304"], noEnv).port == 9304
suite "config validation":
test "unknown flag":
check "--nope" in parseErr(["--nope"])
check "--nope" in parseErr(["--nope=1"])
test "positional arguments are refused":
check "unexpected argument" in parseErr(["serve"])
test "port must be a number in 1..65535":
check "--port" in parseErr(["--port=0"])
check "--port" in parseErr(["--port=65536"])
check "--port" in parseErr(["--port=-1"])
check "--port" in parseErr(["--port=90x"])
check "--port" in parseErr(["--port", ""])
check "--port" in parseErr(["--port"]) # missing value
check parseConfig(["--port=1"], noEnv).port == 1
check parseConfig(["--port=65535"], noEnv).port == 65535
test "origin needs an http(s) scheme and a host":
check "--public-origin" in parseErr(["--public-origin=localhost:8080"])
check "--public-origin" in parseErr(["--public-origin=ftp://x"])
check "--public-origin" in parseErr(["--public-origin=http://"])
check "--public-origin" in parseErr(["--public-origin=https:///path"])
test "origin has no path, query or fragment":
check "--public-origin" in parseErr(["--public-origin=https://x.example/path"])
check "--public-origin" in parseErr(["--public-origin=https://x.example?q=1"])
check "--public-origin" in parseErr(["--public-origin=https://x.example#f"])
test "origin host is a DNS name or IPv4 literal, not arbitrary text":
check "--public-origin" in parseErr(["--public-origin=https://bad host"])
check "--public-origin" in parseErr(["--public-origin=https://x.example:abc"])
check parseConfig(["--public-origin=http://10.0.0.5:9000"], noEnv).publicOrigin ==
"http://10.0.0.5:9000"
test "origin keeps an explicit port and lowercases the scheme and host":
check parseConfig(["--public-origin=https://VTT.Example:8443"], noEnv).publicOrigin ==
"https://vtt.example:8443"
test "state dir must be non-empty":
check "--state-dir" in parseErr(["--state-dir="])
check "--state-dir" in parseErr(["--state-dir", " "])
test "--help is not an error and asks for usage, even with a broken env":
check parseConfig(["--help"], noEnv).help
check parseConfig(["-h"], noEnv).help
check not parseConfig([], noEnv).help
check parseConfig(["--help"], envOf([("FFF_VTT_PORT", "http")])).help
test "usage lists the three keys and says the bind is fixed":
let u = usage()
check "--public-origin" in u
check "--port" in u
check "--state-dir" in u
check "FFF_VTT_PUBLIC_ORIGIN" in u
check "127.0.0.1" in u
+115
View File
@@ -0,0 +1,115 @@
## Migration runner (DESIGN 4.4; DDL and version rule FIXED owner-delegated, #16).
## A fresh DB is created and migrated; re-opening is a no-op; a newer DB is refused; a failing
## migration leaves no trace (one transaction per step).
import std/[unittest, os, strutils]
import db_connector/db_sqlite
import db
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "ffftdb-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc openFresh(dir: string): DbConn = openDatabase(dir / "state.db")
suite "open":
test "creates the file, sets WAL, synchronous NORMAL, busy_timeout, foreign_keys":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
check fileExists(d / "state.db")
check db.getValue(sql"PRAGMA journal_mode").toLowerAscii == "wal"
check db.getValue(sql"PRAGMA synchronous") == "1" # NORMAL (Q12)
check db.getValue(sql"PRAGMA busy_timeout") == "5000"
check db.getValue(sql"PRAGMA foreign_keys") == "1"
suite "migrate":
test "fresh DB: applies every step, sets user_version and records history":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
check schemaVersion(db) == 0
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 1
let rows = appliedMigrations(db)
check rows.len == 1
check rows[0][0] == 1
check rows[0][1] == "meta"
# the step's own DDL ran: meta exists and is empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
block:
let db = openFresh(d)
check migrate(db) == 1
close(db)
let db = openFresh(d)
defer:
close(db)
removeDir(d)
let before = appliedMigrations(db)
check migrate(db) == 0
check migrate(db) == 0
check schemaVersion(db) == 1
check appliedMigrations(db) == before
test "history and user_version must agree":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
db.exec(sql"CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)")
db.exec(sql"INSERT INTO schema_migration VALUES (1, 'meta', 'x')")
db.exec(sql"PRAGMA user_version = 0")
var msg = ""
try:
discard migrate(db)
except MigrationError as e:
msg = e.msg
check "disagree" in msg
test "a DB from a newer server is refused, not downgraded":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
db.exec(sql"CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)")
db.exec(sql"PRAGMA user_version = 9")
var msg = ""
try:
discard migrate(db)
except MigrationError as e:
msg = e.msg
check "newer" in msg
check schemaVersion(db) == 9
check appliedMigrations(db).len == 0
test "a failing step rolls back: no DDL, no history, version unchanged":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
# step 1 creates meta; pre-creating it makes the step fail half-way through
db.exec(sql"CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)")
var raised = false
try:
discard migrate(db)
except MigrationError:
raised = true
check raised
check schemaVersion(db) == 0
check appliedMigrations(db).len == 0
# the runner's own bookkeeping table may exist, but the failed step left nothing else
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'meta'") == "1"
+113
View File
@@ -0,0 +1,113 @@
## Logging with secret redaction (DESIGN 11.3, threat T6; mechanism FIXED owner-delegated, #16).
## Secrets are never trusted to call-site discipline: registered values are scrubbed wherever they
## appear, and fields whose name is sensitive are masked even when the value was never registered.
import std/[unittest, strutils]
import eventlog
type Capture = ref object
lines: seq[string]
proc capture(): tuple[lg: Logger, cap: Capture] =
let cap = Capture()
let lg = newLogger(lvInfo, proc(line: string) = cap.lines.add line)
(lg, cap)
suite "redaction by value":
test "a secret passed as a field value never appears in the output":
let (lg, cap) = capture()
lg.addSecret("s3cr3t-value")
lg.log(lvInfo, "join", [("player", "anna"), ("key", "s3cr3t-value")])
check cap.lines.len == 1
check "s3cr3t-value" notin cap.lines[0]
check "[redacted]" in cap.lines[0]
check "player=anna" in cap.lines[0]
test "a secret inside free text, the event name or a nested value is scrubbed too":
let (lg, cap) = capture()
lg.addSecret("s3cr3t-value")
lg.log(lvInfo, "saw s3cr3t-value twice: s3cr3t-value", [("detail", "cookie=s3cr3t-value;")])
check "s3cr3t-value" notin cap.lines[0]
check cap.lines[0].count("[redacted]") == 3
test "redact() is usable on any string":
let (lg, _) = capture()
lg.addSecret("s3cr3t-value")
check lg.redact("a s3cr3t-value b") == "a [redacted] b"
check lg.redact("nothing here") == "nothing here"
test "two secrets, one a prefix of the other, are both removed":
let (lg, cap) = capture()
lg.addSecret("abcdefgh")
lg.addSecret("abcdefgh-1234")
lg.log(lvInfo, "x", [("a", "abcdefgh"), ("b", "abcdefgh-1234")])
check "abcdefgh" notin cap.lines[0]
check "[redacted]" in cap.lines[0]
test "registering a short value is refused: it would shred every line":
let (lg, _) = capture()
var raised = false
try:
lg.addSecret("abc")
except ValueError:
raised = true
check raised
lg.addSecret("abcd1234") # MinSecretLen
check MinSecretLen == 8
suite "redaction by field name":
test "sensitive field names are masked even for unregistered values":
let (lg, cap) = capture()
lg.log(lvInfo, "x", [("key", "plainvalue"), ("session", "plainvalue"),
("player_key", "plainvalue"), ("gm_key", "plainvalue"),
("secret", "plainvalue"), ("cookie", "plainvalue"),
("token_hash", "plainvalue"), ("set-cookie", "plainvalue"),
("authorization", "plainvalue")])
check "plainvalue" notin cap.lines[0]
check cap.lines[0].count("[redacted]") == 9
test "field names are matched case-insensitively and exactly":
let (lg, cap) = capture()
lg.log(lvInfo, "x", [("Cookie", "plainvalue"), ("monkey", "plainvalue")])
check "Cookie=[redacted]" in cap.lines[0]
check "monkey=plainvalue" in cap.lines[0] # a name that merely contains "key" is not sensitive
check isSensitiveField("PlayER_KEY")
check not isSensitiveField("monkey")
check not isSensitiveField("key_count")
suite "line format and levels":
test "every line carries an ISO-8601 UTC timestamp, the level and the event":
let (lg, cap) = capture()
lg.log(lvWarn, "slow", [("total_ms", "120")])
let line = cap.lines[0]
check line[0..3].allCharsInSet(Digits)
check "T" in line
check line.endsWith("Z") or "Z " in line
check " WARN slow " in line
check "total_ms=120" in line
test "values with spaces or quotes are quoted, so one line stays one record":
let (lg, cap) = capture()
lg.log(lvInfo, "x", [("note", "a b"), ("q", "he said \"hi\"")])
check "note=\"a b\"" in cap.lines[0]
check "q=\"he said \\\"hi\\\"\"" in cap.lines[0]
test "a value cannot forge a second log line":
let (lg, cap) = capture()
lg.log(lvInfo, "x", [("echo", "one\ntwo\r\u0000")])
check cap.lines.len == 1
check "one\\ntwo\\r\\x00" in cap.lines[0]
test "messages below the level are dropped":
let cap = Capture()
let lg = newLogger(lvWarn, proc(line: string) = cap.lines.add line)
lg.log(lvInfo, "dropped")
lg.log(lvDebug, "dropped")
lg.log(lvWarn, "kept")
check cap.lines.len == 1
check "kept" in cap.lines[0]
test "no fields is still one valid line":
let (lg, cap) = capture()
lg.log(lvInfo, "server_start")
check cap.lines.len == 1
check "INFO server_start" in cap.lines[0]