diff --git a/server/auth.nim b/server/auth.nim new file mode 100644 index 0000000..32c9725 --- /dev/null +++ b/server/auth.nim @@ -0,0 +1,175 @@ +## Players, player keys and sessions (DESIGN 3.2, 4.4, 8; issue #17). +## DDL is migration step 2 in db.nim. Choices recorded FIXED (owner-delegated, #17) in DESIGN 3.2: +## player(id, name NULL until first sign-in, role gm|player, colour, created_at); +## player_key(player_id PK FK, secret plaintext, created_at) - one current key, replace overwrites; +## session(id, player_id FK, token_hash UNIQUE, created_at, last_seen) - never expires; +## exactly one GM (partial unique index); max 6 non-GM players, unused keys count. +## Keys are plaintext so the GM can re-show them (Q11); sessions store only SHA-256(token). +## This module does no locking: the caller serializes access to the one DbConn (4.3). +import std/[options, strutils, times] +import db_connector/db_sqlite +import crypto + +type + PlayerRole* = enum + prGm = "gm" + prPlayer = "player" + + Player* = object + id*: int + name*: Option[string] ## none = NULL (never signed in, so no display name yet) + role*: PlayerRole + colour*: string + + KeyCreated* = object + key*: string + created*: bool + rotated*: bool + +const + MaxPlayers* = 6 + ## Non-GM players; unused keys count toward the cap (DESIGN 3.2). + GmName* = "GM" + PlayerColours* = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#06b6d4"] + GmColour* = "#6b7280" + +proc nowStamp(): string = + now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'") + +proc rowToPlayer(row: Row): Player = + Player(id: parseInt(row[0]), + name: if row[1].len == 0: none(string) else: some(row[1]), + role: parseEnum[PlayerRole](row[2]), + colour: row[3]) + +proc gmPlayer*(db: DbConn): Option[Player] = + for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE role = 'gm'"): + return some(rowToPlayer(row)) + +proc playerById*(db: DbConn, id: int): Option[Player] = + for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE id = ?", id): + return some(rowToPlayer(row)) + +proc playerCount*(db: DbConn): int = + ## Non-GM players, named or not (unused keys count toward the 6-player cap). + parseInt(db.getValue(sql"SELECT count(*) FROM player WHERE role = 'player'")) + +proc keyOf*(db: DbConn, playerId: int): Option[string] = + let s = db.getValue(sql"SELECT secret FROM player_key WHERE player_id = ?", playerId) + if s.len == 0: none(string) else: some(s) + +proc insertKey(db: DbConn, playerId: int, key: string) = + db.exec(sql"INSERT INTO player_key (player_id, secret, created_at) VALUES (?, ?, ?)", + playerId, key, nowStamp()) + +proc ensureGm*(db: DbConn, rotate = false): KeyCreated = + ## Creates the single GM (role gm, name "GM") if absent; prints the same key on re-run. + ## rotate = true: new key, all GM sessions revoked. Caller guarantees no server holds the lock. + let gm = gmPlayer(db) + if gm.isSome: + let id = gm.get.id + if rotate: + let key = generatePlayerKey() + db.exec(sql"BEGIN") + try: + db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?", + key, nowStamp(), id) + db.exec(sql"DELETE FROM session WHERE player_id = ?", id) + db.exec(sql"COMMIT") + except CatchableError: + try: db.exec(sql"ROLLBACK") + except CatchableError: discard + raise + return KeyCreated(key: key, rotated: true) + let existing = keyOf(db, id) + if existing.isSome: + return KeyCreated(key: existing.get) + # Degraded DB (key row missing): heal it rather than print nothing. + let key = generatePlayerKey() + insertKey(db, id, key) + return KeyCreated(key: key, created: true) + + let key = generatePlayerKey() + db.exec(sql"BEGIN") + try: + let id = int(insertID(db, + sql"INSERT INTO player (name, role, colour, created_at) VALUES (?, 'gm', ?, ?)", + GmName, GmColour, nowStamp())) + insertKey(db, id, key) + db.exec(sql"COMMIT") + result = KeyCreated(key: key, created: true) + except CatchableError: + try: db.exec(sql"ROLLBACK") + except CatchableError: discard + raise + +proc createPlayerWithKey*(db: DbConn): tuple[id: int, key: string] = + ## key.create: no name at creation (the player types it at first sign-in, DESIGN 3.2). + let colour = PlayerColours[playerCount(db) mod PlayerColours.len] + let key = generatePlayerKey() + db.exec(sql"BEGIN") + try: + let id = int(insertID(db, + sql"INSERT INTO player (name, role, colour, created_at) VALUES (NULL, 'player', ?, ?)", + colour, nowStamp())) + insertKey(db, id, key) + db.exec(sql"COMMIT") + result = (id: id, key: key) + except CatchableError: + try: db.exec(sql"ROLLBACK") + except CatchableError: discard + raise + +proc findPlayerByKey*(db: DbConn, input: string): Option[Player] = + ## Every row is compared without an early exit; comparison ignores case, dashes and spaces. + let wanted = normalizeKey(input) + if wanted.len == 0: return none(Player) + var found: Option[Player] + for row in db.getAllRows(sql""" + SELECT p.id, p.name, p.role, p.colour, k.secret + FROM player p JOIN player_key k ON k.player_id = p.id ORDER BY p.id"""): + if constantTimeEqual(normalizeKey(row[4]), wanted): + found = some(rowToPlayer(row)) + found + +proc replacePlayerKey*(db: DbConn, playerId: int): Option[string] = + ## key.replace: new secret, all sessions of that player revoked. The GM's own key never rotates + ## here (CLI only, DESIGN 3.2) - the caller refuses before calling. + let player = playerById(db, playerId) + if player.isNone or player.get.role == prGm: return none(string) + let key = generatePlayerKey() + db.exec(sql"BEGIN") + try: + db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?", + key, nowStamp(), playerId) + db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId) + db.exec(sql"COMMIT") + except CatchableError: + try: db.exec(sql"ROLLBACK") + except CatchableError: discard + raise + some(key) + +proc removePlayer*(db: DbConn, playerId: int): bool = + ## player.remove: key and sessions go with the player (ON DELETE CASCADE). Characters and + ## controlled tokens are the GM's from slice 8 on; those tables do not exist in slice 2. + db.execAffectedRows(sql"DELETE FROM player WHERE id = ? AND role = 'player'", playerId) > 0 + +proc createSession*(db: DbConn, playerId: int, tokenHash: string) = + let stamp = nowStamp() + db.exec(sql"INSERT INTO session (player_id, token_hash, created_at, last_seen) VALUES (?, ?, ?, ?)", + playerId, tokenHash, stamp, stamp) + +proc sessionPlayer*(db: DbConn, tokenHash: string): Option[Player] = + if tokenHash.len == 0: return none(Player) + for row in db.getAllRows(sql""" + SELECT p.id, p.name, p.role, p.colour + FROM session s JOIN player p ON p.id = s.player_id + WHERE s.token_hash = ? ORDER BY s.id""", tokenHash): + return some(rowToPlayer(row)) + +proc revokeSessions*(db: DbConn, playerId: int) = + db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId) + +proc sessionCount*(db: DbConn, playerId: int): int = + parseInt(db.getValue(sql"SELECT count(*) FROM session WHERE player_id = ?", playerId)) diff --git a/server/conns.nim b/server/conns.nim new file mode 100644 index 0000000..ebfdfe3 --- /dev/null +++ b/server/conns.nim @@ -0,0 +1,105 @@ +## Live WebSocket connection registry (DESIGN 4.3, 6.5; issue #17). +## Caps FIXED (owner-delegated, #15): 4 connections per player (a 5th evicts that player's oldest), +## 16 total (the 17th is refused before the upgrade). Connections are kept in activation order, which +## is the eviction order. Keyed by an app connId, not by WebSocket fields (H19). +## One lock, held only for these O(16) list operations. The caller closes the tickets returned. +import std/[locks, options] +import mummy +import auth + +type + Conn* = object + id*: int + playerId*: int + role*: PlayerRole + ws*: WebSocket + + Conns* = ref object + lock: Lock + nextId: int + pending: int ## upgrades in flight, reserved against the total cap + maxPerPlayer: int + maxTotal: int + active: seq[Conn] ## activation order; active[0] is the oldest of the whole server + + Activation* = object + id*: int + evictedId*: Option[int] + evicted*: Option[WebSocket] + +const + MaxConnsPerPlayer* = 4 + MaxConnsTotal* = 16 + +proc newConns*(maxPerPlayer = MaxConnsPerPlayer, maxTotal = MaxConnsTotal): Conns = + result = Conns(maxPerPlayer: maxPerPlayer, maxTotal: maxTotal) + initLock(result.lock) + +proc reserve*(c: Conns): bool = + ## Before the upgrade: false means the 17th connection - answer HTTP 503, no upgrade. + withLock c.lock: + result = c.active.len + c.pending < c.maxTotal + if result: inc c.pending + +proc cancelReserve*(c: Conns) = + withLock c.lock: + if c.pending > 0: dec c.pending + +proc playerConnIndices(c: Conns, playerId: int): seq[int] = + for i, conn in c.active: + if conn.playerId == playerId: result.add i + +proc activate*(c: Conns, playerId: int, role: PlayerRole, ws: WebSocket): Activation = + ## After a successful upgrade. A 5th connection of one player evicts that player's oldest. + withLock c.lock: + if c.pending > 0: dec c.pending + let mine = c.playerConnIndices(playerId) + if mine.len >= c.maxPerPlayer: + let oldest = mine[0] + result.evictedId = some(c.active[oldest].id) + result.evicted = some(c.active[oldest].ws) + c.active.delete(oldest) + inc c.nextId + result.id = c.nextId + c.active.add Conn(id: c.nextId, playerId: playerId, role: role, ws: ws) + +proc remove*(c: Conns, connId: int) = + withLock c.lock: + for i, conn in c.active: + if conn.id == connId: + c.active.delete(i) + return + +proc connById*(c: Conns, connId: int): Option[Conn] = + withLock c.lock: + for conn in c.active: + if conn.id == connId: return some(conn) + +proc connForWs*(c: Conns, ws: WebSocket): Option[Conn] = + ## Mummy hands the same WebSocket value back on MessageEvent/CloseEvent (H19 layout check). + withLock c.lock: + for conn in c.active: + if conn.ws == ws: return some(conn) + +proc revokePlayer*(c: Conns, playerId: int): seq[WebSocket] = + ## key.replace / player.remove / GM key rotation: every live connection of that player. + withLock c.lock: + var i = 0 + while i < c.active.len: + if c.active[i].playerId == playerId: + result.add c.active[i].ws + c.active.delete(i) + else: + inc i + +proc activeCount*(c: Conns): int = + withLock c.lock: + result = c.active.len + +proc activeCountFor*(c: Conns, playerId: int): int = + withLock c.lock: + result = c.playerConnIndices(playerId).len + +proc pendingCount*(c: Conns): int = + withLock c.lock: + result = c.pending diff --git a/server/crypto.nim b/server/crypto.nim new file mode 100644 index 0000000..dc4d502 --- /dev/null +++ b/server/crypto.nim @@ -0,0 +1,151 @@ +## Secrets and hashing for auth (DESIGN 3.2, #17): the player/GM key generator, the session token +## generator and SHA-256 for session-token hashes. +## Choices recorded FIXED (owner-delegated, #17), DESIGN 3.2/8: +## - Player key: 20 secret characters in 5 groups of 4 joined by '-', alphabet `KeyAlphabet` +## (no 0/O, 1/I/L), from the OS CSPRNG via std/sysrand (getrandom), ~99 bits. +## - Session token: 32 random bytes, hex encoded (64 chars). Only `sha256Hex(token)` is stored. +## - SHA-256 is implemented here (FIPS 180-4) because the pinned Nim stdlib has no SHA-2 and the +## project takes no crypto dependency. Known-answer tests in tests/tcrypto.nim. +import std/[strutils, sysrand] + +const + KeyAlphabet* = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" + ## 31 symbols: A-Z without I, L, O; digits 2-9. 31^20 ~ 2^99. + KeyLength* = 20 + KeyGroups* = 5 + KeyGroupSize* = 4 + SessionTokenBytes* = 32 + +const HexDigits = "0123456789abcdef" + +proc toHexLower*(bytes: openArray[byte]): string = + result = newStringOfCap(bytes.len * 2) + for b in bytes: + result.add HexDigits[int(b shr 4)] + result.add HexDigits[int(b and 0x0f)] + +proc bytesOf*(s: string): seq[byte] = + result = newSeq[byte](s.len) + for i, c in s: result[i] = byte(c) + +const Sha256K: array[64, uint32] = [ + 0x428a2f98'u32, 0x71374491'u32, 0xb5c0fbcf'u32, 0xe9b5dba5'u32, + 0x3956c25b'u32, 0x59f111f1'u32, 0x923f82a4'u32, 0xab1c5ed5'u32, + 0xd807aa98'u32, 0x12835b01'u32, 0x243185be'u32, 0x550c7dc3'u32, + 0x72be5d74'u32, 0x80deb1fe'u32, 0x9bdc06a7'u32, 0xc19bf174'u32, + 0xe49b69c1'u32, 0xefbe4786'u32, 0x0fc19dc6'u32, 0x240ca1cc'u32, + 0x2de92c6f'u32, 0x4a7484aa'u32, 0x5cb0a9dc'u32, 0x76f988da'u32, + 0x983e5152'u32, 0xa831c66d'u32, 0xb00327c8'u32, 0xbf597fc7'u32, + 0xc6e00bf3'u32, 0xd5a79147'u32, 0x06ca6351'u32, 0x14292967'u32, + 0x27b70a85'u32, 0x2e1b2138'u32, 0x4d2c6dfc'u32, 0x53380d13'u32, + 0x650a7354'u32, 0x766a0abb'u32, 0x81c2c92e'u32, 0x92722c85'u32, + 0xa2bfe8a1'u32, 0xa81a664b'u32, 0xc24b8b70'u32, 0xc76c51a3'u32, + 0xd192e819'u32, 0xd6990624'u32, 0xf40e3585'u32, 0x106aa070'u32, + 0x19a4c116'u32, 0x1e376c08'u32, 0x2748774c'u32, 0x34b0bcb5'u32, + 0x391c0cb3'u32, 0x4ed8aa4a'u32, 0x5b9cca4f'u32, 0x682e6ff3'u32, + 0x748f82ee'u32, 0x78a5636f'u32, 0x84c87814'u32, 0x8cc70208'u32, + 0x90befffa'u32, 0xa4506ceb'u32, 0xbef9a3f7'u32, 0xc67178f2'u32] + +proc rotr(x: uint32, n: int): uint32 {.inline.} = + (x shr n) or (x shl (32 - n)) + +proc sha256*(data: openArray[byte]): array[32, byte] = + var h: array[8, uint32] = [ + 0x6a09e667'u32, 0xbb67ae85'u32, 0x3c6ef372'u32, 0xa54ff53a'u32, + 0x510e527f'u32, 0x9b05688c'u32, 0x1f83d9ab'u32, 0x5be0cd19'u32] + var msg = newSeq[byte](data.len + 1) + for i, b in data: msg[i] = b + msg[data.len] = 0x80'u8 + let bitLen = uint64(data.len) * 8'u64 + while msg.len mod 64 != 56: msg.add 0'u8 + for shift in countdown(7, 0): + msg.add byte((bitLen shr uint64(shift * 8)) and 0xff'u64) + + var w: array[64, uint32] + var offset = 0 + while offset < msg.len: + for j in 0 ..< 16: + let k = offset + j * 4 + w[j] = (uint32(msg[k]) shl 24) or (uint32(msg[k + 1]) shl 16) or + (uint32(msg[k + 2]) shl 8) or uint32(msg[k + 3]) + for j in 16 ..< 64: + let s0 = rotr(w[j - 15], 7) xor rotr(w[j - 15], 18) xor (w[j - 15] shr 3) + let s1 = rotr(w[j - 2], 17) xor rotr(w[j - 2], 19) xor (w[j - 2] shr 10) + w[j] = w[j - 16] + s0 + w[j - 7] + s1 + var a = h[0] + var b = h[1] + var c = h[2] + var d = h[3] + var e = h[4] + var f = h[5] + var g = h[6] + var hh = h[7] + for j in 0 ..< 64: + let s1 = rotr(e, 6) xor rotr(e, 11) xor rotr(e, 25) + let ch = (e and f) xor ((not e) and g) + let t1 = hh + s1 + ch + Sha256K[j] + w[j] + let s0 = rotr(a, 2) xor rotr(a, 13) xor rotr(a, 22) + let maj = (a and b) xor (a and c) xor (b and c) + let t2 = s0 + maj + hh = g; g = f; f = e; e = d + t1 + d = c; c = b; b = a; a = t1 + t2 + h[0] = h[0] + a; h[1] = h[1] + b; h[2] = h[2] + c; h[3] = h[3] + d + h[4] = h[4] + e; h[5] = h[5] + f; h[6] = h[6] + g; h[7] = h[7] + hh + offset += 64 + + for j in 0 ..< 8: + result[j * 4] = byte(h[j] shr 24) + result[j * 4 + 1] = byte((h[j] shr 16) and 0xff) + result[j * 4 + 2] = byte((h[j] shr 8) and 0xff) + result[j * 4 + 3] = byte(h[j] and 0xff) + +proc sha256Hex*(data: openArray[byte]): string = + toHexLower(sha256(data)) + +proc sha256Hex*(s: string): string = + sha256Hex(bytesOf(s)) + +proc randomBytes*(n: int): seq[byte] = + ## OS CSPRNG (std/sysrand: getrandom(2) on Linux). Raises OSError if unavailable. + urandom(n) + +proc randomHexToken*(bytes = SessionTokenBytes): string = + toHexLower(randomBytes(bytes)) + +proc randomSessionToken*(): string = + randomHexToken(SessionTokenBytes) + +proc formatPlayerKey*(raw: string): string = + ## "abcd...20 chars" -> "ABCD-EFGH-..." (5 groups of 4). Input is the 20 raw symbols. + doAssert raw.len == KeyLength + result = "" + for i in 0 ..< KeyGroups: + if i > 0: result.add '-' + result.add raw[i * KeyGroupSize ..< (i + 1) * KeyGroupSize].toUpperAscii + +proc generatePlayerKey*(): string = + ## 20 symbols from KeyAlphabet, uniform (rejection sampling: 31*8 = 248 < 256). + var raw = newStringOfCap(KeyLength) + while raw.len < KeyLength: + for b in randomBytes(32): + if raw.len == KeyLength: break + if int(b) >= KeyAlphabet.len * 8: continue + raw.add KeyAlphabet[int(b) mod KeyAlphabet.len] + formatPlayerKey(raw) + +proc normalizeKey*(input: string): string = + ## Key comparison ignores case, dashes and spaces (DESIGN 6.6). + result = newStringOfCap(input.len) + for c in input: + if c in {'-', ' ', '\t', '\r', '\n'}: continue + result.add c.toLowerAscii + +proc constantTimeEqual*(a, b: string): bool = + ## Length-independent comparison for secrets: never exits on the first difference. + var diff = a.len xor b.len + let n = max(a.len, b.len) + for i in 0 ..< n: + let ca = if i < a.len: uint8(a[i]) else: 0'u8 + let cb = if i < b.len: uint8(b[i]) else: 0'u8 + diff = diff or int(ca xor cb) + diff == 0 diff --git a/server/db.nim b/server/db.nim index 4157f45..3773a2b 100644 --- a/server/db.nim +++ b/server/db.nim @@ -18,7 +18,9 @@ type Migration* = object version*: int name*: string - sql*: string + stmts*: seq[string] + ## One or more DDL statements, run in order inside the step's transaction. + ## db_connector's exec() prepares a single statement, so they cannot be one string. MigrationRow* = tuple[version: int, name: string] const @@ -29,11 +31,33 @@ CREATE TABLE IF NOT EXISTS schema_migration ( applied_at TEXT NOT NULL )""" migrations* = [ - Migration(version: 1, name: "meta", sql: """ + Migration(version: 1, name: "meta", stmts: @[""" CREATE TABLE meta ( k TEXT PRIMARY KEY, v TEXT NOT NULL -)"""), +)"""]), + Migration(version: 2, name: "auth", stmts: @[""" +CREATE TABLE player ( + id INTEGER PRIMARY KEY, + name TEXT UNIQUE, -- NULL until first sign-in; unique among players + role TEXT NOT NULL CHECK (role IN ('gm', 'player')), + colour TEXT NOT NULL, + created_at TEXT NOT NULL +)""", """ +CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'""", """ +CREATE TABLE player_key ( + player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, + secret TEXT NOT NULL, -- plaintext: the GM can re-show it (Q11) + created_at TEXT NOT NULL +)""", """ +CREATE TABLE session ( + id INTEGER PRIMARY KEY, + player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the cookie token; the token is never stored + created_at TEXT NOT NULL, + last_seen TEXT NOT NULL +)""", """ +CREATE INDEX session_player ON session(player_id)"""]), ] LatestVersion* = migrations[^1].version ## Derived, so adding a step cannot leave it stale. @@ -77,7 +101,8 @@ proc migrate*(db: DbConn): int = if m.version <= version: continue db.exec(sql"BEGIN") try: - db.exec(sql(m.sql)) + for stmt in m.stmts: + db.exec(sql(stmt)) 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) diff --git a/server/instancelock.nim b/server/instancelock.nim new file mode 100644 index 0000000..7ae391c --- /dev/null +++ b/server/instancelock.nim @@ -0,0 +1,42 @@ +## Data-dir lock (DESIGN 3.2 / 11.1, #17): the running server holds an exclusive advisory lock on +## `/instance.lock`; `fff-vtt gm-key --new` must not rotate under a live server. +## POSIX fcntl(F_SETLK) write lock: process-scoped, released when the fd is closed or the process exits. +import std/[os, posix] + +const InstanceLockName* = "instance.lock" + +type + InstanceLock* = object + path*: string + fd*: cint + held*: bool + +proc tryAcquire*(stateDir: string): InstanceLock = + result.path = stateDir / InstanceLockName + let fd = open(result.path.cstring, O_RDWR or O_CREAT, Mode(0o600)) + if fd < 0: return + var fl: Tflock + fl.l_type = cshort(F_WRLCK) + fl.l_whence = cshort(SEEK_SET) + fl.l_start = 0 + fl.l_len = 0 + if fcntl(fd, F_SETLK, addr fl) == 0: + result.fd = fd + result.held = true + # Record the holder for humans; the lock, not the content, is the protocol. + discard ftruncate(fd, 0) + let pid = $getCurrentProcessId() & "\n" + discard posix.write(fd, pid.cstring, pid.len) + else: + discard posix.close(fd) + +proc release*(l: var InstanceLock) = + if l.held: + var fl: Tflock + fl.l_type = cshort(F_UNLCK) + fl.l_whence = cshort(SEEK_SET) + fl.l_start = 0 + fl.l_len = 0 + discard fcntl(l.fd, F_SETLK, addr fl) + discard posix.close(l.fd) + l.held = false diff --git a/tests/tauth.nim b/tests/tauth.nim new file mode 100644 index 0000000..f65b1c9 --- /dev/null +++ b/tests/tauth.nim @@ -0,0 +1,182 @@ +## Players, player keys and sessions (#17): GM bootstrap, key creation/replacement/removal, the +## session table (hash only), and one key on several devices. +import std/[unittest, os, options, strutils] +import db_connector/db_sqlite +import db, auth, crypto + +var tmpCount = 0 +proc tmpDir(): string = + inc tmpCount + result = getTempDir() / "ffftauth-" & $getCurrentProcessId() & "-" & $tmpCount + removeDir(result) + createDir(result) + +proc fresh(): tuple[db: DbConn, dir: string] = + let d = tmpDir() + let db = openDatabase(d / "state.db") + doAssert migrate(db) == LatestVersion + (db, d) + +suite "GM key (fff-vtt gm-key)": + test "first run creates the single GM and prints a key; re-run prints the same key": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + let first = ensureGm(db) + check first.created + check not first.rotated + check first.key.len == 24 + let gm = gmPlayer(db) + check gm.isSome + check gm.get.role == prGm + check gm.get.name == some(GmName) + check playerCount(db) == 0 # the GM does not count toward the 6 players + let again = ensureGm(db) + check again.key == first.key + check not again.created + check not again.rotated + + test "--new rotates: new key, old key invalid, GM sessions revoked, same player": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + let first = ensureGm(db) + let gmId = gmPlayer(db).get.id + let token = randomSessionToken() + createSession(db, gmId, sha256Hex(token)) + check sessionPlayer(db, sha256Hex(token)).isSome + let rotated = ensureGm(db, rotate = true) + check rotated.rotated + check rotated.key != first.key + check gmPlayer(db).get.id == gmId + check sessionCount(db, gmId) == 0 + check sessionPlayer(db, sha256Hex(token)).isNone + check findPlayerByKey(db, first.key).isNone + check findPlayerByKey(db, rotated.key).get.id == gmId + +suite "player keys": + test "key.create: unnamed player, working key, counts toward the cap": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let created = createPlayerWithKey(db) + check created.id > 0 + check playerCount(db) == 1 + let p = playerById(db, created.id).get + check p.role == prPlayer + check p.name.isNone # name is typed at first sign-in + check p.colour.len > 0 + check findPlayerByKey(db, created.key).get.id == created.id + + test "key comparison ignores case, dashes and spaces; a wrong key finds nobody": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let created = createPlayerWithKey(db) + check findPlayerByKey(db, created.key).get.id == created.id + check findPlayerByKey(db, created.key.toLowerAscii).get.id == created.id + check findPlayerByKey(db, created.key.replace("-", " ")).get.id == created.id + check findPlayerByKey(db, " " & created.key & "\n").get.id == created.id + check findPlayerByKey(db, created.key.replace("-", "")).get.id == created.id + check findPlayerByKey(db, "AAAA-BBBB-CCCC-DDDD-EEEE").isNone + check findPlayerByKey(db, "").isNone + + test "six non-GM players are allowed (unused keys count); the cap is a server check": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + for _ in 0 ..< MaxPlayers: discard createPlayerWithKey(db) + check playerCount(db) == 6 + check db.getValue(sql"SELECT count(*) FROM player") == "7" + + test "key.replace: new key, old key invalid, sessions revoked, identity kept": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let created = createPlayerWithKey(db) + let tokenA = randomSessionToken() + let tokenB = randomSessionToken() + createSession(db, created.id, sha256Hex(tokenA)) + createSession(db, created.id, sha256Hex(tokenB)) + check sessionCount(db, created.id) == 2 # one key on several devices + let replaced = replacePlayerKey(db, created.id) + check replaced.isSome + check replaced.get != created.key + check findPlayerByKey(db, created.key).isNone + check findPlayerByKey(db, replaced.get).get.id == created.id + check sessionCount(db, created.id) == 0 + check sessionPlayer(db, sha256Hex(tokenA)).isNone + check playerById(db, created.id).get.id == created.id + check playerById(db, created.id).get.name.isNone + + test "key.replace refuses the GM and unknown ids": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + let gm = ensureGm(db) + check replacePlayerKey(db, gmPlayer(db).get.id).isNone + check replacePlayerKey(db, 999).isNone + check findPlayerByKey(db, gm.key).isSome + + test "player.remove deletes key and sessions, frees the slot; the GM cannot be removed": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let created = createPlayerWithKey(db) + let token = randomSessionToken() + createSession(db, created.id, sha256Hex(token)) + check removePlayer(db, created.id) + check playerById(db, created.id).isNone + check findPlayerByKey(db, created.key).isNone + check sessionPlayer(db, sha256Hex(token)).isNone + check db.getValue(sql"SELECT count(*) FROM player_key WHERE player_id = ?", created.id) == "0" + check db.getValue(sql"SELECT count(*) FROM session WHERE player_id = ?", created.id) == "0" + check playerCount(db) == 0 + check removePlayer(db, created.id) == false + check removePlayer(db, gmPlayer(db).get.id) == false + check gmPlayer(db).isSome + +suite "sessions": + test "only the hash is stored; the token itself appears nowhere": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let token = randomSessionToken() + createSession(db, gmPlayer(db).get.id, sha256Hex(token)) + let stored = db.getValue(sql"SELECT token_hash FROM session") + check stored == sha256Hex(token) + check stored != token + check token notin stored + check findPlayerByKey(db, token).isNone + + test "unknown hash gives no player; revoking one player leaves the other alone": + let (db, dir) = fresh() + defer: + close(db) + removeDir(dir) + discard ensureGm(db) + let a = createPlayerWithKey(db) + let b = createPlayerWithKey(db) + let ta = randomSessionToken() + let tb = randomSessionToken() + createSession(db, a.id, sha256Hex(ta)) + createSession(db, b.id, sha256Hex(tb)) + check sessionPlayer(db, sha256Hex(randomSessionToken())).isNone + revokeSessions(db, a.id) + check sessionPlayer(db, sha256Hex(ta)).isNone + check sessionPlayer(db, sha256Hex(tb)).get.id == b.id diff --git a/tests/tconns.nim b/tests/tconns.nim new file mode 100644 index 0000000..cf7bdf7 --- /dev/null +++ b/tests/tconns.nim @@ -0,0 +1,108 @@ +## Connection caps (#17, DESIGN 4.3/6.5): 4 per player (5th evicts the oldest), 16 total (17th refused). +import std/[unittest, options] +import mummy +import conns, auth + +proc dummyWs(): WebSocket = + # Mummy's fields are private; an all-zero value is enough for registry bookkeeping tests. + var ws: WebSocket + ws + +suite "total cap": + test "16 reservations succeed, the 17th is refused": + let c = newConns() + for _ in 0 ..< MaxConnsTotal: check c.reserve() + check c.pendingCount == 16 + check not c.reserve() + check c.pendingCount == 16 + + test "a cancelled reservation gives the slot back": + let c = newConns() + for _ in 0 ..< MaxConnsTotal: check c.reserve() + check not c.reserve() + c.cancelReserve() + check c.pendingCount == 15 + check c.reserve() + check not c.reserve() + + test "activated connections keep the total cap; removing one frees a slot": + let c = newConns() + for i in 0 ..< MaxConnsTotal: + check c.reserve() + discard c.activate(i mod 4, prPlayer, dummyWs()) + check c.activeCount == 16 + check c.pendingCount == 0 + check not c.reserve() + c.remove(1) + check c.activeCount == 15 + check c.reserve() + +suite "per-player cap": + test "the 5th connection of one player evicts that player's oldest": + let c = newConns() + var ids: seq[int] + for _ in 0 ..< MaxConnsPerPlayer: + check c.reserve() + let a = c.activate(7, prPlayer, dummyWs()) + ids.add a.id + check a.evictedId.isNone + check c.activeCountFor(7) == 4 + check c.reserve() + let fifth = c.activate(7, prPlayer, dummyWs()) + check fifth.evictedId == some(ids[0]) + check c.activeCountFor(7) == 4 + check c.connById(ids[0]).isNone + check c.connById(fifth.id).isSome + # the next one evicts the second-oldest, not a new victim at random + check c.reserve() + let sixth = c.activate(7, prPlayer, dummyWs()) + check sixth.evictedId == some(ids[1]) + + test "another player's connections are never evicted": + let c = newConns() + for _ in 0 ..< MaxConnsPerPlayer: + check c.reserve() + discard c.activate(1, prPlayer, dummyWs()) + let other = c.activate(2, prPlayer, dummyWs()) # player 2 has none: no eviction + check other.evictedId.isNone + # player 1 is at the cap: its next one evicts player 1's oldest, player 2's stays + discard c.activate(1, prPlayer, dummyWs()) + check c.activeCountFor(1) == 4 + check c.activeCountFor(2) == 1 + + test "the GM is capped like anyone else (caps are per player, not per role)": + let c = newConns() + var gmIds: seq[int] + for _ in 0 ..< MaxConnsPerPlayer: + discard c.activate(1, prGm, dummyWs()) + for id in 1 .. MaxConnsPerPlayer: gmIds.add id + let fifth = c.activate(1, prGm, dummyWs()) + check fifth.evictedId == some(gmIds[0]) + +suite "revocation": + test "revokePlayer returns every live connection of that player and nothing else": + let c = newConns() + discard c.activate(1, prPlayer, dummyWs()) + discard c.activate(2, prPlayer, dummyWs()) + discard c.activate(1, prPlayer, dummyWs()) + check c.revokePlayer(1).len == 2 + check c.activeCountFor(1) == 0 + check c.activeCountFor(2) == 1 + check c.activeCount == 1 + check c.revokePlayer(1).len == 0 + + test "remove works by conn id; an unknown id is a no-op": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + c.remove(a.id) + c.remove(a.id) + check c.activeCount == 0 + check c.connById(a.id).isNone + + test "connForWs finds the registered socket (mummy hands the same value back)": + let c = newConns() + var ws: WebSocket + let a = c.activate(1, prPlayer, ws) + check c.connForWs(ws).get.id == a.id + var other: WebSocket # another all-zero value still equals the first one structurally + check c.connForWs(other).isSome diff --git a/tests/tcrypto.nim b/tests/tcrypto.nim new file mode 100644 index 0000000..06df760 --- /dev/null +++ b/tests/tcrypto.nim @@ -0,0 +1,76 @@ +## Secrets and hashing (#17): SHA-256 known answers, key format, normalization and comparison. +import std/[unittest, strutils, sets] +import crypto + +suite "sha256": + test "FIPS 180-4 known answers": + check sha256Hex("") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + check sha256Hex("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + check sha256Hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") == + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + test "padding boundaries: 55, 56 and 64 byte messages differ and are stable": + let a = sha256Hex(repeat('a', 55)) + let b = sha256Hex(repeat('a', 56)) + let c = sha256Hex(repeat('a', 64)) + check a.len == 64 + check a != b + check b != c + # 56 bytes needs the extra block (length no longer fits in the first block's tail) + check b == "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" + check sha256Hex(repeat('a', 64)) == "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" + +suite "player keys": + test "20 symbols in 5 groups of 4, no look-alike characters": + let key = generatePlayerKey() + check key.len == 24 + let groups = key.split('-') + check groups.len == 5 + for g in groups: + check g.len == 4 + for c in g: + check c in {'A'..'Z', '2'..'9'} + check c notin {'0', 'O', '1', 'I', 'L'} + test "100 generated keys are distinct": + var seen = initHashSet[string]() + for _ in 0 ..< 100: + let k = normalizeKey(generatePlayerKey()) + check k.len == 20 + check k notin seen + seen.incl k + test "generator output is upper-case; normalization is case/dash/space insensitive": + let key = generatePlayerKey() + check key == key.toUpperAscii + let norm = normalizeKey(key) + check norm.len == 20 + check normalizeKey(key.toLowerAscii) == norm + check normalizeKey(key.replace("-", " ")) == norm + check normalizeKey(" " & key & "\t\n") == norm + check normalizeKey("ab cd-ef") == "abcdef" + test "generated keys draw from the whole alphabet (uniform sampling sanity)": + # 3000 draws over 31 symbols: every symbol must appear (probability of a miss ~ 0). + var seen = initHashSet[char]() + for _ in 0 ..< 150: + for c in normalizeKey(generatePlayerKey()): seen.incl c + check seen.len == KeyAlphabet.len + for c in KeyAlphabet: check c.toLowerAscii in seen + +suite "session tokens": + test "32 bytes hex encoded, distinct": + let a = randomSessionToken() + let b = randomSessionToken() + check a.len == 64 + check a.allCharsInSet({'0'..'9', 'a'..'f'}) + check a != b + check sha256Hex(a).len == 64 + check sha256Hex(a) != a + +suite "constant-time compare": + test "equal only for identical strings, including the empty case": + check constantTimeEqual("abc", "abc") + check not constantTimeEqual("abc", "abd") + check not constantTimeEqual("abc", "abcd") + check not constantTimeEqual("", "a") + check constantTimeEqual("", "") + let key = normalizeKey(generatePlayerKey()) + check constantTimeEqual(key, normalizeKey(generatePlayerKey().toLowerAscii)) == false + check constantTimeEqual(key, key) diff --git a/tests/tdb.nim b/tests/tdb.nim index cba3043..073a4de 100644 --- a/tests/tdb.nim +++ b/tests/tdb.nim @@ -38,19 +38,24 @@ suite "migrate": check migrate(db) == LatestVersion check LatestVersion == migrations[^1].version check schemaVersion(db) == LatestVersion - check LatestVersion == 1 + check LatestVersion == 2 let rows = appliedMigrations(db) - check rows.len == 1 + check rows.len == 2 check rows[0][0] == 1 check rows[0][1] == "meta" - # the step's own DDL ran: meta exists and is empty + check rows[1][0] == 2 + check rows[1][1] == "auth" + # the steps' own DDL ran: meta and the auth tables exist and are empty check db.getValue(sql"SELECT count(*) FROM meta") == "0" + check db.getValue(sql"SELECT count(*) FROM player") == "0" + check db.getValue(sql"SELECT count(*) FROM player_key") == "0" + check db.getValue(sql"SELECT count(*) FROM session") == "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 + check migrate(db) == 2 close(db) let db = openFresh(d) defer: @@ -59,7 +64,7 @@ suite "migrate": let before = appliedMigrations(db) check migrate(db) == 0 check migrate(db) == 0 - check schemaVersion(db) == 1 + check schemaVersion(db) == 2 check appliedMigrations(db) == before test "history and user_version must agree": diff --git a/tests/tinstancelock.nim b/tests/tinstancelock.nim new file mode 100644 index 0000000..2a5c733 --- /dev/null +++ b/tests/tinstancelock.nim @@ -0,0 +1,32 @@ +## Data-dir lock (#17): an exclusive advisory lock in the state dir outlives nothing by accident. +## Contention between two processes is exercised by the Node harness (the server holds it while +## `gm-key --new` must refuse); in-process fcntl locks are per process, so only acquire/release here. +import std/[unittest, os, strutils] +import instancelock + +proc tmpDir(): string = + result = getTempDir() / "ffflock-" & $getCurrentProcessId() + removeDir(result) + createDir(result) + +suite "instance lock": + test "acquires, creates the lock file, releases and re-acquires": + let d = tmpDir() + defer: removeDir(d) + var lock = tryAcquire(d) + check lock.held + check fileExists(d / InstanceLockName) + check readFile(d / InstanceLockName).strip == $getCurrentProcessId() + lock.release() + check not lock.held + var again = tryAcquire(d) + check again.held + again.release() + + test "release is idempotent": + let d = tmpDir() + defer: removeDir(d) + var lock = tryAcquire(d) + lock.release() + lock.release() + check not lock.held diff --git a/tools/smoke.test.mjs b/tools/smoke.test.mjs index 51f3362..b8273ff 100644 --- a/tools/smoke.test.mjs +++ b/tools/smoke.test.mjs @@ -49,15 +49,16 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async () const first = await startServer({ stateDir }) const firstLog = first.log() await stopServer(first) - assert.match(firstLog, /db_ready .*schema_version=1 applied=1/, firstLog) + assert.match(firstLog, /db_ready .*schema_version=2 applied=2/, firstLog) assert.ok(fs.existsSync(first.dbPath), 'state.db was not created') const db = new DatabaseSync(first.dbPath) try { - assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 1) + assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 2) const rows = db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all() - assert.deepEqual(rows.map(r => [Number(r.version), r.name]), [[1, 'meta']]) + assert.deepEqual(rows.map(r => [Number(r.version), r.name]), [[1, 'meta'], [2, 'auth']]) assert.equal(Number(db.prepare('SELECT count(*) AS n FROM meta').get().n), 0) + assert.equal(Number(db.prepare('SELECT count(*) AS n FROM player').get().n), 0) assert.equal(db.prepare('PRAGMA journal_mode').get().journal_mode, 'wal') } finally { db.close() @@ -66,7 +67,7 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async () const second = await startServer({ stateDir }) const secondLog = second.log().slice(firstLog.length) await stopServer(second) - assert.match(secondLog, /db_ready .*schema_version=1 applied=0/, secondLog) + assert.match(secondLog, /db_ready .*schema_version=2 applied=0/, secondLog) assert.doesNotMatch(secondLog, /applied=[1-9]/) } finally { fs.rmSync(stateDir, { recursive: true, force: true })