diff --git a/.gitignore b/.gitignore index 2c6c885..eb3f94f 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ tests/t[a-z]* !tests/fixtures/ tools/bench tools/mkcorpus +run/ diff --git a/fff_vtt.nimble b/fff_vtt.nimble index fe95aab..21ff02f 100644 --- a/fff_vtt.nimble +++ b/fff_vtt.nimble @@ -5,3 +5,4 @@ license = "MIT" srcDir = "server" requires "nim >= 2.0" +requires "mummy == 0.4.8", "db_connector == 0.1.0" diff --git a/server/config.nim b/server/config.nim new file mode 100644 index 0000000..1402f6e --- /dev/null +++ b/server/config.nim @@ -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= Browser origin the site is served from (default: http://localhost:8080). + Env: FFF_VTT_PUBLIC_ORIGIN + --port= Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT + --state-dir= 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" diff --git a/server/db.nim b/server/db.nim new file mode 100644 index 0000000..4157f45 --- /dev/null +++ b/server/db.nim @@ -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) diff --git a/server/eventlog.nim b/server/eventlog.nim new file mode 100644 index 0000000..6b7e18c --- /dev/null +++ b/server/eventlog.nim @@ -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") diff --git a/server/main.nim b/server/main.nim new file mode 100644 index 0000000..477d5ff --- /dev/null +++ b/server/main.nim @@ -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() diff --git a/tests/tconfig.nim b/tests/tconfig.nim new file mode 100644 index 0000000..a3b6f5d --- /dev/null +++ b/tests/tconfig.nim @@ -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) + "" + 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 diff --git a/tests/tdb.nim b/tests/tdb.nim new file mode 100644 index 0000000..cba3043 --- /dev/null +++ b/tests/tdb.nim @@ -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" diff --git a/tests/tlogging.nim b/tests/tlogging.nim new file mode 100644 index 0000000..9bfc7b3 --- /dev/null +++ b/tests/tlogging.nim @@ -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]