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 @@
## Runtime configuration (DESIGN 11.1). Keys FIXED owner-delegated, #16:
## --public-origin | FFF_VTT_PUBLIC_ORIGIN browser origin, exact match later for Origin checks
## --port | FFF_VTT_PORT listen port, 1..65535
## --state-dir | FFF_VTT_STATE_DIR directory holding state.db (and tiles later)
## Flags win over env, env wins over defaults. The listen address is NOT a key: the server always
## binds 127.0.0.1 (DESIGN 3.4 T15; nginx is the only public face).
import std/[os, strutils]
type
Config* = object
publicOrigin*: string
port*: int
stateDir*: string
help*: bool
ConfigError* = object of CatchableError
## Bad flag, bad env value or an incoherent combination; main() prints it and exits 2.
EnvLookup* = proc(key: string): string {.closure.}
## Environment reader, injected so tests do not touch the process env.
const
BindAddress* = "127.0.0.1"
DefaultPublicOrigin* = "http://localhost:8080"
DefaultPort* = 9000
DefaultStateDir* = "run"
proc processEnv(): EnvLookup =
result = proc(key: string): string = getEnv(key)
proc fail(msg: string) {.noreturn.} = raise newException(ConfigError, msg)
proc parsePort(key, value: string): int =
if value.len == 0 or value.len > 5 or not value.allCharsInSet(Digits):
fail key & ": expected a port number 1..65535, got \"" & value & "\""
let p = parseInt(value)
if p < 1 or p > 65535:
fail key & ": expected a port number 1..65535, got " & value
p
proc parseOrigin(key, value: string): string =
## scheme://host[:port], lowercased, no trailing slash: this string is compared byte for byte
## against the browser's Origin header (3.2), so it must be the canonical form.
var v = value.strip
if v.len == 0: fail key & ": expected http(s)://host[:port]"
var scheme = ""
for candidate in ["https://", "http://"]:
if v.toLowerAscii.startsWith(candidate):
scheme = candidate
v = v[candidate.len .. ^1]
break
if scheme.len == 0: fail key & ": expected an http:// or https:// origin, got \"" & value & "\""
if '?' in v or '#' in v or '@' in v or '[' in v or ']' in v:
fail key & ": origin must be scheme://host[:port] (no query, fragment, userinfo or IPv6 literal), got \"" & value & "\""
var hostPort = v
let slash = v.find('/')
if slash >= 0:
if v[slash .. ^1].strip(chars = {'/'}).len != 0:
fail key & ": origin must have no path, got \"" & value & "\""
hostPort = v[0 ..< slash]
if hostPort.len == 0: fail key & ": origin has no host, got \"" & value & "\""
var host = hostPort
let colon = hostPort.rfind(':')
if colon >= 0:
host = hostPort[0 ..< colon]
discard parsePort(key, hostPort[colon + 1 .. ^1])
const hostChars = {'a'..'z', 'A'..'Z', '0'..'9', '.', '-', '_'}
if host.len == 0 or not host.allCharsInSet(hostChars):
fail key & ": origin host must be a DNS name or IPv4 literal, got \"" & value & "\""
scheme & hostPort.toLowerAscii
proc parseStateDir(key, value: string): string =
var v = value.strip
if v.len == 0: fail key & ": expected a directory path"
while v.len > 1 and v[^1] == '/': v.setLen(v.len - 1)
v
proc usage*(): string =
"""fff-vtt - server-authoritative vision VTT
Usage: fff-vtt [options]
Options:
--public-origin=<url> Browser origin the site is served from (default: http://localhost:8080).
Env: FFF_VTT_PUBLIC_ORIGIN
--port=<n> Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT
--state-dir=<path> Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR
-h, --help Print this help and exit.
The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front.
"""
proc parseConfig*(args: openArray[string], envLookup: EnvLookup = nil): Config =
let lookup = if envLookup.isNil: processEnv() else: envLookup
result.publicOrigin = DefaultPublicOrigin
result.port = DefaultPort
result.stateDir = DefaultStateDir
# --help wins over everything, including a broken env: the usage text must always be reachable.
for arg in args:
if arg == "-h" or arg == "--help":
result.help = true
if result.help: return
let envOrigin = lookup("FFF_VTT_PUBLIC_ORIGIN")
if envOrigin.strip.len > 0: result.publicOrigin = parseOrigin("FFF_VTT_PUBLIC_ORIGIN", envOrigin)
let envPort = lookup("FFF_VTT_PORT")
if envPort.strip.len > 0: result.port = parsePort("FFF_VTT_PORT", envPort.strip)
let envState = lookup("FFF_VTT_STATE_DIR")
if envState.strip.len > 0: result.stateDir = parseStateDir("FFF_VTT_STATE_DIR", envState)
var i = 0
while i < args.len:
let arg = args[i]
inc i
if not arg.startsWith("--"):
fail "unexpected argument \"" & arg & "\" (see --help)"
var key = arg[2 .. ^1]
var value = ""
var hasValue = false
let eq = key.find('=')
if eq >= 0:
value = key[eq + 1 .. ^1]
key = key[0 ..< eq]
hasValue = true
if key notin ["public-origin", "port", "state-dir"]:
fail "unknown flag --" & key & " (see --help)"
if not hasValue:
if i >= args.len: fail "--" & key & ": missing value"
value = args[i]
inc i
case key
of "public-origin": result.publicOrigin = parseOrigin("--public-origin", value)
of "port": result.port = parsePort("--port", value.strip)
of "state-dir": result.stateDir = parseStateDir("--state-dir", value)
else: discard
proc dbPath*(c: Config): string = c.stateDir / "state.db"
+91
View File
@@ -0,0 +1,91 @@
## SQLite open + forward-only migration runner (DESIGN 4.4, H13). DDL and version rule FIXED
## owner-delegated, #16:
## - `schema_migration(version, name, applied_at)` is the history table; `PRAGMA user_version`
## carries the same latest version (external tools read it cheaply). They must agree, and
## history is contiguous from 1, otherwise startup refuses.
## - A DB whose user_version is above this build's latest is refused, never downgraded.
## - One transaction per step: DDL + history row + user_version together. A failing step leaves
## nothing behind; a fully migrated DB is not written to at all (re-open is a no-op).
## - Engine settings: WAL, synchronous=NORMAL (Q12), busy_timeout=5000, foreign_keys=ON.
## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[strutils, times]
import db_connector/db_sqlite
type
MigrationError* = object of CatchableError
## The DB cannot be brought to this build's schema: newer DB, inconsistent history, or a
## failed step (already rolled back).
Migration* = object
version*: int
name*: string
sql*: string
MigrationRow* = tuple[version: int, name: string]
const
MigrationHistoryDdl* = """
CREATE TABLE IF NOT EXISTS schema_migration (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at TEXT NOT NULL
)"""
migrations* = [
Migration(version: 1, name: "meta", sql: """
CREATE TABLE meta (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
)"""),
]
LatestVersion* = migrations[^1].version
## Derived, so adding a step cannot leave it stale.
proc openDatabase*(path: string): DbConn =
result = open(path, "", "", "")
discard result.getAllRows(sql"PRAGMA journal_mode=WAL")
result.exec(sql"PRAGMA synchronous=NORMAL")
result.exec(sql"PRAGMA busy_timeout=5000")
result.exec(sql"PRAGMA foreign_keys=ON")
proc schemaVersion*(db: DbConn): int =
parseInt(db.getValue(sql"PRAGMA user_version"))
proc appliedMigrations*(db: DbConn): seq[MigrationRow] =
for r in db.getAllRows(sql"SELECT version, name FROM schema_migration ORDER BY version"):
result.add (version: parseInt(r[0]), name: r[1])
proc migrate*(db: DbConn): int =
## Applies every step above the DB's version; returns how many ran (0 for an up-to-date DB).
db.exec(sql(MigrationHistoryDdl))
let version = schemaVersion(db)
if version > LatestVersion:
raise newException(MigrationError,
"database schema version " & $version & " is newer than this server (" & $LatestVersion &
"); refusing to run")
let history = appliedMigrations(db)
var historyProblem = ""
if history.len != version:
historyProblem = "user_version=" & $version & " but history has " & $history.len & " steps"
else:
for i, row in history:
if row.version != i + 1:
historyProblem = "history is not contiguous from 1 (found " & $row.version & " at step " & $(i + 1) & ")"
elif row.version > migrations.len or row.name != migrations[row.version - 1].name:
historyProblem = "step " & $row.version & " is recorded as \"" & row.name & "\""
if historyProblem.len > 0:
raise newException(MigrationError, "schema_migration and user_version disagree: " & historyProblem)
for m in migrations:
if m.version <= version: continue
db.exec(sql"BEGIN")
try:
db.exec(sql(m.sql))
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, ?)",
m.version, m.name, stamp)
db.exec(sql("PRAGMA user_version = " & $m.version)) # PRAGMA does not take bound values
db.exec(sql"COMMIT")
inc result
except CatchableError as e:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard # the original error is the one worth reporting
raise newException(MigrationError,
"migration " & $m.version & " (" & m.name & ") failed: " & e.msg)
+101
View File
@@ -0,0 +1,101 @@
## Structured logging to stdout (journald), with secret redaction (DESIGN 11.3, threat T6).
## Module name: `eventlog`, not `logging`: `import logging` resolves to the stdlib module when Nim
## gets absolute --path entries (nimble test), which would silently shadow this file.
## Mechanism FIXED owner-delegated, #16. Two independent nets, so no call site has to be trusted:
## 1. by value: every secret registered with `addSecret` is replaced by `[redacted]` wherever it
## appears on the line (field value, free text, event name). Shorter than MinSecretLen is
## refused: a 1-3 char "secret" would shred unrelated log lines.
## 2. by field name: a field whose name is sensitive (`isSensitiveField`) is masked even if the
## value was never registered, which covers a caller that forgets to register.
## One line per record, `ts LEVEL event key=value ...`, values quoted when they need it.
## Never log request bodies, keys, session tokens (3.2, 6.6); this module is the safety net.
import std/[strutils, times, locks]
type
Level* = enum
lvDebug, lvInfo, lvWarn, lvError
LogSink* = proc(line: string) {.closure.}
## Receives one complete line, newline included. nil = stdout, flushed per line.
Logger* = ref object
level*: Level
sink: LogSink
lock: Lock
secrets: seq[string]
const
MinSecretLen* = 8
## Shortest value worth registering: keys are 20 chars (3.2), session tokens are 32.
SensitiveFields* = ["key", "player_key", "gm_key", "secret", "session", "session_token",
"cookie", "set-cookie", "token_hash", "authorization"]
## Field names masked by name. Matched case-insensitively, exactly (so `monkey` is fine).
proc stdoutSink(line: string) =
stdout.write(line)
stdout.flushFile()
proc newLogger*(level = lvInfo, sink: LogSink = nil): Logger =
new(result)
result.level = level
result.sink = if sink.isNil: stdoutSink else: sink
initLock(result.lock)
proc isSensitiveField*(name: string): bool =
name.toLowerAscii in SensitiveFields
proc addSecret*(lg: Logger, secret: string) =
## Register a value that must never reach the log. Raises ValueError if it is too short.
if secret.len < MinSecretLen:
raise newException(ValueError,
"refusing to register a secret shorter than " & $MinSecretLen & " characters")
withLock lg.lock:
if secret notin lg.secrets: lg.secrets.add secret
proc redactedValue(lg: Logger, s: string): string =
## Caller holds the lock.
result = s
if lg.secrets.len == 0: return
# longest first, so a secret that is a prefix of another does not leave a tail behind
var ordered = lg.secrets
for i in 1 ..< ordered.len:
var j = i
while j > 0 and ordered[j].len > ordered[j - 1].len:
swap ordered[j], ordered[j - 1]
dec j
for secret in ordered:
result = result.replace(secret, "[redacted]")
proc redact*(lg: Logger, s: string): string =
withLock lg.lock:
result = lg.redactedValue(s)
proc quoteValue(v: string): string =
var needsQuote = v.len == 0
for c in v:
if c in {' ', '"', '='} or c < ' ':
needsQuote = true
break
if not needsQuote: return v
result = "\""
for c in v:
case c
of '"': result.add "\\\""
of '\t': result.add "\\t"
of '\n': result.add "\\n" # a value must never be able to forge a second log line
of '\r': result.add "\\r"
else:
if c < ' ': result.add "\\x" & toHex(ord(c), 2).toLowerAscii
else: result.add c
result.add "\""
const LevelNames: array[Level, string] = ["DEBUG", "INFO", "WARN", "ERROR"]
proc log*(lg: Logger, level: Level, event: string,
fields: openArray[(string, string)] = []) =
if level < lg.level: return
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
var raw = stamp & " " & LevelNames[level] & " " & event
for (name, value) in fields:
let v = if isSensitiveField(name): "[redacted]" else: value
raw.add " " & name & "=" & quoteValue(v)
withLock lg.lock:
lg.sink(lg.redactedValue(raw) & "\n")
+52
View File
@@ -0,0 +1,52 @@
## fff-vtt entrypoint. M3 slice 1 (#16): config, state dir, SQLite + migration runner, GET /healthz,
## logging. Nothing game-specific yet; later slices add /join, /ws, /tiles here.
## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face.
import std/os
import mummy, mummy/routers
import config, db, eventlog
proc healthz(request: Request) {.gcsafe.} =
## Liveness only in slice 1. M5 makes it report the global lock as well (DESIGN 11.3).
var headers: HttpHeaders
headers["Content-Type"] = "application/json"
request.respond(200, headers, """{"status":"ok"}""")
proc buildRouter(): Router =
result.get("/healthz", healthz)
proc main() =
var cfg: Config
try:
cfg = parseConfig(commandLineParams())
except ConfigError as e:
stderr.writeLine "fff-vtt: " & e.msg
quit 2
if cfg.help:
stdout.write usage()
quit 0
let lg = newLogger()
lg.log(lvInfo, "server_start", [("origin", cfg.publicOrigin), ("state_dir", cfg.stateDir),
("bind", BindAddress)])
try:
createDir(cfg.stateDir)
except CatchableError as e:
lg.log(lvError, "state_dir_failed", [("path", cfg.stateDir), ("error", e.msg)])
quit 1
let conn = try: openDatabase(cfg.dbPath)
except CatchableError as e:
lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)])
quit 1
let applied = try: migrate(conn)
except CatchableError as e:
lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)])
quit 1
lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)),
("applied", $applied)])
let server = newServer(buildRouter().toHandler())
lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)])
server.serve(Port(cfg.port), BindAddress)
when isMainModule:
main()