Skip to content
1        10        20        30        40        50        60        70        80        90        100       1101//! Accounts, invites and browser sessions for the web UI.2//!3//! The admin account is defined by `ADMIN_USERNAME`/`ADMIN_PASSWORD` and is checked4//! against the environment on every login, so rotating the password is a restart with5//! a new value. Everyone else joins by redeeming a single-use invite created by an6//! admin. Users and invites are persisted as JSON under the storage directory; the7//! file is replaced atomically on every change.8//!9//! Passwords and invites are never stored in the clear: passwords use PBKDF2-HMAC-10//! SHA256 with a random per-user salt, and invites are stored as their SHA-256 hash.1112const std = @import("std");13const config = @import("config.zig");1415const log = std.log.scoped(.auth);1617pub const session_cookie = "totenschloss_session";18pub const min_password_len = 8;19pub const max_password_len = 128;20pub const min_username_len = 3;21pub const max_username_len = 32;2223const salt_len = 16;24const hash_len = 32;25const hash_rounds: u32 = 210_000;26const admin_salt = "totenschloss-admin";27const invite_code_bytes = 16;28const invite_id_bytes = 8;29const session_token_bytes = 32;30const max_auth_file_bytes = 1 << 20;3132const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256;33const Sha256 = std.crypto.hash.sha2.Sha256;34const pwhash = std.crypto.pwhash.pbkdf2;3536/// A signed-in identity. `username` stays valid for the life of the process37/// (config memory or an append-only user list), or until the caller's arena ends.38pub const Principal = struct {39    username: []const u8,40    is_admin: bool,41};4243pub const InviteView = struct {44    id: []const u8,45    created_by: []const u8,46    created_at: i64,47    expires_at: i64,48    used_by: ?[]const u8,49    /// "active", "used" or "expired".50    status: []const u8,51};5253pub const CreatedInvite = struct {54    id: []const u8,55    code: []const u8,56    expires_at: i64,57};5859const User = struct {60    username: []const u8,61    salt: [salt_len]u8,62    hash: [hash_len]u8,63    created_at: i64,64};6566const Invite = struct {67    id: []const u8,68    code_hash: [hash_len]u8,69    created_by: []const u8,70    created_at: i64,71    expires_at: i64,72    used_by: ?[]const u8,73};7475const StoredUser = struct {76    username: []const u8,77    salt: []const u8,78    hash: []const u8,79    created_at: i64 = 0,80};8182const StoredInvite = struct {83    id: []const u8,84    code_hash: []const u8,85    created_by: []const u8,86    created_at: i64 = 0,87    expires_at: i64 = 0,88    used_by: ?[]const u8 = null,89};9091const StoredFile = struct {92    version: u32 = 1,93    users: []const StoredUser = &.{},94    invites: []const StoredInvite = &.{},95};9697pub fn validateUsername(name: []const u8) bool {98    if (name.len < min_username_len or name.len > max_username_len) return false;99    for (name) |c| {100        if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-' and c != '.') return false;101    }102    return true;103}104105pub fn validatePassword(password: []const u8) bool {106    return password.len >= min_password_len and password.len <= max_password_len;107}108109/// Persistent users and invites. All methods are safe to call from connection threads.110pub const Store = struct {111    allocator: std.mem.Allocator,112    mutex: std.Thread.Mutex = .{},113    path: []const u8,114    tmp_path: []const u8,115    /// Null when login is disabled.116    auth: ?config.WebAuth,117    users: std.ArrayList(User),118    invites: std.ArrayList(Invite),119    /// PBKDF2 of the admin password, also giving failed admin logins a deliberate cost.120    admin_hash: [hash_len]u8 = [_]u8{0} ** hash_len,121122    pub fn init(allocator: std.mem.Allocator, auth_config: ?config.WebAuth, storage_dir: []const u8) !Store {123        const path = try std.fs.path.join(allocator, &.{ storage_dir, "auth.json" });124        const tmp_path = std.fmt.allocPrint(allocator, "{s}.tmp", .{path}) catch |err| {125            allocator.free(path);126            return err;127        };128129        var store = Store{130            .allocator = allocator,131            .path = path,132            .tmp_path = tmp_path,133            .auth = auth_config,134            .users = std.ArrayList(User).init(allocator),135            .invites = std.ArrayList(Invite).init(allocator),136        };137        errdefer store.deinit();138139        if (auth_config) |cfg| store.admin_hash = try hashPassword(cfg.admin_password, admin_salt);140        store.load() catch |err| {141            log.err("could not load {s}: {s}", .{ path, @errorName(err) });142            return err;143        };144        return store;145    }146147    pub fn deinit(self: *Store) void {148        for (self.users.items) |user| self.allocator.free(user.username);149        self.users.deinit();150        for (self.invites.items) |invite| {151            self.allocator.free(invite.id);152            self.allocator.free(invite.created_by);153            if (invite.used_by) |used_by| self.allocator.free(used_by);154        }155        self.invites.deinit();156        self.allocator.free(self.path);157        self.allocator.free(self.tmp_path);158    }159160    /// Checks the environment admin first, then stored users. Null means bad credentials.161    pub fn authenticate(self: *Store, username: []const u8, password: []const u8) !?Principal {162        if (self.auth) |cfg| {163            if (std.ascii.eqlIgnoreCase(username, cfg.admin_username)) {164                if (!try verifyPassword(password, admin_salt, self.admin_hash)) return null;165                return .{ .username = cfg.admin_username, .is_admin = true };166            }167        }168169        self.mutex.lock();170        const snapshot = blk: {171            const user = self.findUserLocked(username) orelse {172                self.mutex.unlock();173                // Spend the same PBKDF2 time as a real check so response timing174                // does not reveal which usernames exist.175                _ = hashPassword(password, admin_salt) catch {};176                return null;177            };178            break :blk .{ .username = user.username, .salt = user.salt, .hash = user.hash };179        };180        self.mutex.unlock();181182        if (!try verifyPassword(password, &snapshot.salt, snapshot.hash)) return null;183        return .{ .username = snapshot.username, .is_admin = false };184    }185186    /// Redeems an invite and creates the account in one step.187    pub fn signupWithInvite(188        self: *Store,189        code: []const u8,190        username: []const u8,191        password: []const u8,192    ) !Principal {193        const name = std.mem.trim(u8, username, " \t\r\n");194        if (!validateUsername(name)) return error.InvalidUsername;195        if (!validatePassword(password)) return error.WeakPassword;196197        const trimmed_code = std.mem.trim(u8, code, " \t\r\n");198        if (trimmed_code.len == 0) return error.InvalidInvite;199        var code_hash: [hash_len]u8 = undefined;200        Sha256.hash(trimmed_code, &code_hash, .{});201202        // Hashing is deliberately slow, so do it before taking the lock.203        var salt: [salt_len]u8 = undefined;204        std.crypto.random.bytes(&salt);205        const hash = try hashPassword(password, &salt);206        const now = std.time.timestamp();207208        self.mutex.lock();209        defer self.mutex.unlock();210211        if (self.usernameReservedLocked(name)) return error.UsernameTaken;212        const invite_index = self.findInviteLocked(code_hash, now) orelse return error.InvalidInvite;213214        const owned_name = try self.allocator.dupe(u8, name);215        errdefer self.allocator.free(owned_name);216        const owned_used_by = try self.allocator.dupe(u8, name);217        errdefer self.allocator.free(owned_used_by);218219        try self.users.append(.{220            .username = owned_name,221            .salt = salt,222            .hash = hash,223            .created_at = now,224        });225        const user_index = self.users.items.len - 1;226        const previous_used_by = self.invites.items[invite_index].used_by;227        self.invites.items[invite_index].used_by = owned_used_by;228        self.saveLocked() catch |err| {229            _ = self.users.pop();230            self.invites.items[invite_index].used_by = previous_used_by;231            return err;232        };233234        return .{ .username = self.users.items[user_index].username, .is_admin = false };235    }236237    /// Creates a single-use invite. The plaintext code is returned once and never stored.238    pub fn createInvite(239        self: *Store,240        allocator: std.mem.Allocator,241        created_by: []const u8,242        ttl_s: u64,243    ) !CreatedInvite {244        var code_raw: [invite_code_bytes]u8 = undefined;245        std.crypto.random.bytes(&code_raw);246        const code_hex = std.fmt.bytesToHex(code_raw, .lower);247248        var id_raw: [invite_id_bytes]u8 = undefined;249        std.crypto.random.bytes(&id_raw);250        const id_hex = std.fmt.bytesToHex(id_raw, .lower);251252        var code_hash: [hash_len]u8 = undefined;253        Sha256.hash(&code_hex, &code_hash, .{});254255        const now = std.time.timestamp();256257        const out_id = try allocator.dupe(u8, &id_hex);258        errdefer allocator.free(out_id);259        const out_code = try allocator.dupe(u8, &code_hex);260        errdefer allocator.free(out_code);261262        self.mutex.lock();263        defer self.mutex.unlock();264265        const stored_id = try self.allocator.dupe(u8, &id_hex);266        const stored_by = self.allocator.dupe(u8, created_by) catch |err| {267            self.allocator.free(stored_id);268            return err;269        };270        self.invites.append(.{271            .id = stored_id,272            .code_hash = code_hash,273            .created_by = stored_by,274            .created_at = now,275            .expires_at = deadline(now, ttl_s),276            .used_by = null,277        }) catch |err| {278            self.allocator.free(stored_id);279            self.allocator.free(stored_by);280            return err;281        };282283        self.saveLocked() catch |err| {284            _ = self.invites.pop();285            self.allocator.free(stored_id);286            self.allocator.free(stored_by);287            return err;288        };289290        return .{ .id = out_id, .code = out_code, .expires_at = deadline(now, ttl_s) };291    }292293    pub fn listInvites(self: *Store, allocator: std.mem.Allocator) ![]InviteView {294        self.mutex.lock();295        defer self.mutex.unlock();296297        const now = std.time.timestamp();298        const views = try allocator.alloc(InviteView, self.invites.items.len);299        for (self.invites.items, 0..) |invite, i| {300            views[i] = .{301                .id = try allocator.dupe(u8, invite.id),302                .created_by = try allocator.dupe(u8, invite.created_by),303                .created_at = invite.created_at,304                .expires_at = invite.expires_at,305                .used_by = if (invite.used_by) |used_by| try allocator.dupe(u8, used_by) else null,306                .status = if (invite.used_by != null)307                    "used"308                else if (invite.expires_at <= now)309                    "expired"310                else311                    "active",312            };313        }314        return views;315    }316317    pub fn revokeInvite(self: *Store, id: []const u8) !void {318        self.mutex.lock();319        defer self.mutex.unlock();320321        var index: ?usize = null;322        for (self.invites.items, 0..) |invite, i| {323            if (std.mem.eql(u8, invite.id, id)) {324                index = i;325                break;326            }327        }328        const i = index orelse return error.UnknownInvite;329        if (self.invites.items[i].used_by != null) return error.InviteUsed;330331        const removed = self.invites.orderedRemove(i);332        self.saveLocked() catch |err| {333            self.invites.append(removed) catch {};334            return err;335        };336        self.allocator.free(removed.id);337        self.allocator.free(removed.created_by);338        if (removed.used_by) |used_by| self.allocator.free(used_by);339    }340341    fn findUserLocked(self: *Store, username: []const u8) ?*User {342        for (self.users.items) |*user| {343            if (std.ascii.eqlIgnoreCase(user.username, username)) return user;344        }345        return null;346    }347348    fn usernameReservedLocked(self: *Store, name: []const u8) bool {349        if (self.auth) |cfg| {350            if (std.ascii.eqlIgnoreCase(name, cfg.admin_username)) return true;351        }352        return self.findUserLocked(name) != null;353    }354355    fn findInviteLocked(self: *Store, code_hash: [hash_len]u8, now: i64) ?usize {356        for (self.invites.items, 0..) |invite, i| {357            if (invite.used_by != null or invite.expires_at <= now) continue;358            if (std.crypto.timing_safe.eql([hash_len]u8, invite.code_hash, code_hash)) return i;359        }360        return null;361    }362363    fn load(self: *Store) !void {364        const file = std.fs.cwd().openFile(self.path, .{}) catch |err| switch (err) {365            error.FileNotFound => return,366            else => return err,367        };368        defer file.close();369370        var arena = std.heap.ArenaAllocator.init(self.allocator);371        defer arena.deinit();372        const a = arena.allocator();373        const body = try file.readToEndAlloc(a, max_auth_file_bytes);374        if (std.mem.trim(u8, body, " \t\r\n").len == 0) return;375376        const doc = std.json.parseFromSliceLeaky(StoredFile, a, body, .{ .ignore_unknown_fields = true }) catch377            return error.InvalidAuthFile;378379        for (doc.users) |stored| {380            const username = try self.allocator.dupe(u8, stored.username);381            const salt = decodeFixed(salt_len, stored.salt) catch |err| {382                self.allocator.free(username);383                return err;384            };385            const hash = decodeFixed(hash_len, stored.hash) catch |err| {386                self.allocator.free(username);387                return err;388            };389            self.users.append(.{390                .username = username,391                .salt = salt,392                .hash = hash,393                .created_at = stored.created_at,394            }) catch |err| {395                self.allocator.free(username);396                return err;397            };398        }399400        for (doc.invites) |stored| {401            const id = try self.allocator.dupe(u8, stored.id);402            const created_by = self.allocator.dupe(u8, stored.created_by) catch |err| {403                self.allocator.free(id);404                return err;405            };406            const used_by = if (stored.used_by) |used_by| self.allocator.dupe(u8, used_by) catch |err| {407                self.allocator.free(id);408                self.allocator.free(created_by);409                return err;410            } else null;411            const code_hash = decodeFixed(hash_len, stored.code_hash) catch |err| {412                self.allocator.free(id);413                self.allocator.free(created_by);414                if (used_by) |u| self.allocator.free(u);415                return err;416            };417            self.invites.append(.{418                .id = id,419                .code_hash = code_hash,420                .created_by = created_by,421                .created_at = stored.created_at,422                .expires_at = stored.expires_at,423                .used_by = used_by,424            }) catch |err| {425                self.allocator.free(id);426                self.allocator.free(created_by);427                if (used_by) |u| self.allocator.free(u);428                return err;429            };430        }431    }432433    /// Must be called with the mutex held.434    fn saveLocked(self: *Store) !void {435        var arena = std.heap.ArenaAllocator.init(self.allocator);436        defer arena.deinit();437        const a = arena.allocator();438439        const stored_users = try a.alloc(StoredUser, self.users.items.len);440        for (self.users.items, 0..) |user, i| {441            const salt_hex = std.fmt.bytesToHex(user.salt, .lower);442            const hash_hex = std.fmt.bytesToHex(user.hash, .lower);443            stored_users[i] = .{444                .username = user.username,445                .salt = try a.dupe(u8, &salt_hex),446                .hash = try a.dupe(u8, &hash_hex),447                .created_at = user.created_at,448            };449        }450451        const stored_invites = try a.alloc(StoredInvite, self.invites.items.len);452        for (self.invites.items, 0..) |invite, i| {453            const code_hash_hex = std.fmt.bytesToHex(invite.code_hash, .lower);454            stored_invites[i] = .{455                .id = invite.id,456                .code_hash = try a.dupe(u8, &code_hash_hex),457                .created_by = invite.created_by,458                .created_at = invite.created_at,459                .expires_at = invite.expires_at,460                .used_by = invite.used_by,461            };462        }463464        const json = try std.json.stringifyAlloc(a, StoredFile{465            .users = stored_users,466            .invites = stored_invites,467        }, .{ .whitespace = .indent_2 });468469        var file = try std.fs.cwd().createFile(self.tmp_path, .{ .truncate = true, .mode = 0o600 });470        defer file.close();471        try file.writeAll(json);472        try file.sync();473        try std.fs.cwd().rename(self.tmp_path, self.path);474    }475};476477/// In-memory browser sessions. Tokens are random 256-bit values and only live in478/// this process, so a restart signs everyone out.479pub const Sessions = struct {480    allocator: std.mem.Allocator,481    mutex: std.Thread.Mutex = .{},482    entries: std.StringHashMap(Session),483484    const Session = struct {485        username: []const u8,486        is_admin: bool,487        expires_at: i64,488    };489490    pub fn init(allocator: std.mem.Allocator) Sessions {491        return .{ .allocator = allocator, .entries = std.StringHashMap(Session).init(allocator) };492    }493494    pub fn deinit(self: *Sessions) void {495        var it = self.entries.iterator();496        while (it.next()) |entry| {497            self.allocator.free(entry.key_ptr.*);498            self.allocator.free(entry.value_ptr.username);499        }500        self.entries.deinit();501    }502503    /// Returns a token owned by the session store. Do not free it.504    pub fn create(self: *Sessions, ttl_s: u64, principal: Principal) ![]const u8 {505        var raw: [session_token_bytes]u8 = undefined;506        std.crypto.random.bytes(&raw);507        const hex = std.fmt.bytesToHex(raw, .lower);508        const token = try self.allocator.dupe(u8, &hex);509        errdefer self.allocator.free(token);510        const username = try self.allocator.dupe(u8, principal.username);511        errdefer self.allocator.free(username);512513        self.mutex.lock();514        defer self.mutex.unlock();515        const now = std.time.timestamp();516        self.pruneLocked(now);517        try self.entries.putNoClobber(token, .{518            .username = username,519            .is_admin = principal.is_admin,520            .expires_at = deadline(now, ttl_s),521        });522        return token;523    }524525    /// Copies the username into `allocator` so the caller can use it outside the lock.526    pub fn get(self: *Sessions, allocator: std.mem.Allocator, token: []const u8) !?Principal {527        self.mutex.lock();528        defer self.mutex.unlock();529530        const session = self.entries.get(token) orelse return null;531        if (session.expires_at <= std.time.timestamp()) {532            if (self.entries.fetchRemove(token)) |removed| {533                self.allocator.free(removed.key);534                self.allocator.free(removed.value.username);535            }536            return null;537        }538539        const username = try allocator.dupe(u8, session.username);540        return .{ .username = username, .is_admin = session.is_admin };541    }542543    pub fn destroy(self: *Sessions, token: []const u8) void {544        self.mutex.lock();545        defer self.mutex.unlock();546        if (self.entries.fetchRemove(token)) |removed| {547            self.allocator.free(removed.key);548            self.allocator.free(removed.value.username);549        }550    }551552    fn pruneLocked(self: *Sessions, now: i64) void {553        var expired = std.ArrayList([]const u8).init(self.allocator);554        defer expired.deinit();555556        var it = self.entries.iterator();557        while (it.next()) |entry| {558            if (entry.value_ptr.expires_at <= now) expired.append(entry.key_ptr.*) catch return;559        }560        for (expired.items) |token| {561            if (self.entries.fetchRemove(token)) |removed| {562                self.allocator.free(removed.key);563                self.allocator.free(removed.value.username);564            }565        }566    }567};568569/// The complete auth state owned by the server: configuration, accounts, sessions.570pub const State = struct {571    config: ?config.WebAuth,572    store: Store,573    sessions: Sessions,574575    pub fn init(576        allocator: std.mem.Allocator,577        auth_config: ?config.WebAuth,578        storage_dir: []const u8,579    ) !State {580        return .{581            .config = auth_config,582            .store = try Store.init(allocator, auth_config, storage_dir),583            .sessions = Sessions.init(allocator),584        };585    }586587    pub fn deinit(self: *State) void {588        self.store.deinit();589        self.sessions.deinit();590    }591592    pub fn enabled(self: *const State) bool {593        return self.config != null;594    }595};596597fn hashPassword(password: []const u8, salt: []const u8) ![hash_len]u8 {598    var hash: [hash_len]u8 = undefined;599    try pwhash(&hash, password, salt, hash_rounds, HmacSha256);600    return hash;601}602603fn verifyPassword(password: []const u8, salt: []const u8, expected: [hash_len]u8) !bool {604    const actual = try hashPassword(password, salt);605    return std.crypto.timing_safe.eql([hash_len]u8, actual, expected);606}607608fn deadline(now: i64, ttl_s: u64) i64 {609    const ttl: i64 = std.math.cast(i64, ttl_s) orelse std.math.maxInt(i64);610    return std.math.add(i64, now, ttl) catch std.math.maxInt(i64);611}612613fn decodeFixed(comptime n: usize, text: []const u8) ![n]u8 {614    if (text.len != n * 2) return error.InvalidAuthFile;615    var out: [n]u8 = undefined;616    _ = std.fmt.hexToBytes(&out, text) catch return error.InvalidAuthFile;617    return out;618}619620test "username and password validation" {621    try std.testing.expect(validateUsername("player-one"));622    try std.testing.expect(validateUsername("a.b_c"));623    try std.testing.expect(!validateUsername("ab"));624    try std.testing.expect(!validateUsername("has space"));625    try std.testing.expect(!validateUsername("emoji🙂"));626    try std.testing.expect(!validatePassword("short"));627    try std.testing.expect(validatePassword("long enough"));628}629630test "admin login, invite signup, persistence and sessions" {631    const allocator = std.testing.allocator;632633    var tmp = std.testing.tmpDir(.{});634    defer tmp.cleanup();635    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");636    defer allocator.free(storage_dir);637638    const auth_config = config.WebAuth{639        .admin_username = "admin",640        .admin_password = "correct horse battery",641        .session_ttl_s = 3600,642        .invite_ttl_s = 3600,643        .cookie_secure = false,644    };645646    var state = try State.init(allocator, auth_config, storage_dir);647    defer state.deinit();648649    const admin = (try state.store.authenticate("admin", "correct horse battery")).?;650    try std.testing.expect(admin.is_admin);651    try std.testing.expectEqualStrings("admin", admin.username);652    try std.testing.expect((try state.store.authenticate("admin", "wrong password")) == null);653    try std.testing.expect((try state.store.authenticate("nobody", "whatever!")) == null);654655    const invite = try state.store.createInvite(allocator, "admin", 3600);656    defer allocator.free(invite.id);657    defer allocator.free(invite.code);658    try std.testing.expectEqual(@as(usize, 32), invite.code.len);659660    const player = try state.store.signupWithInvite(invite.code, "player-one", "hunter2!!");661    try std.testing.expect(!player.is_admin);662    try std.testing.expectEqualStrings("player-one", player.username);663664    // The invite is single-use.665    try std.testing.expectError(666        error.InvalidInvite,667        state.store.signupWithInvite(invite.code, "other-player", "hunter2!!"),668    );669    // Names are unique case-insensitively, and the admin name is reserved.670    const second = try state.store.createInvite(allocator, "admin", 3600);671    defer allocator.free(second.id);672    defer allocator.free(second.code);673    try std.testing.expectError(674        error.UsernameTaken,675        state.store.signupWithInvite(second.code, "Player-One", "hunter2!!"),676    );677    try std.testing.expectError(678        error.UsernameTaken,679        state.store.signupWithInvite(second.code, "ADMIN", "hunter2!!"),680    );681682    const views = try state.store.listInvites(allocator);683    defer {684        for (views) |view| {685            allocator.free(view.id);686            allocator.free(view.created_by);687            if (view.used_by) |used_by| allocator.free(used_by);688        }689        allocator.free(views);690    }691    try std.testing.expectEqual(@as(usize, 2), views.len);692    try std.testing.expectEqualStrings("used", views[0].status);693    try std.testing.expectEqualStrings("active", views[1].status);694695    // Sessions resolve back to the principal.696    const token = try state.sessions.create(3600, player);697    const from_session = (try state.sessions.get(allocator, token)).?;698    defer allocator.free(from_session.username);699    try std.testing.expectEqualStrings("player-one", from_session.username);700    try std.testing.expect(!from_session.is_admin);701    state.sessions.destroy(token);702    try std.testing.expect((try state.sessions.get(allocator, token)) == null);703704    // Accounts survive a restart (sessions do not).705    state.deinit();706    state = try State.init(allocator, auth_config, storage_dir);707    const again = (try state.store.authenticate("player-one", "hunter2!!")).?;708    try std.testing.expectEqualStrings("player-one", again.username);709    try std.testing.expect((try state.store.authenticate("player-one", "wrong password")) == null);710}711712test "expired and revoked invites are rejected" {713    const allocator = std.testing.allocator;714715    var tmp = std.testing.tmpDir(.{});716    defer tmp.cleanup();717    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");718    defer allocator.free(storage_dir);719720    var state = try State.init(allocator, null, storage_dir);721    defer state.deinit();722723    const expired = try state.store.createInvite(allocator, "admin", 0);724    defer allocator.free(expired.id);725    defer allocator.free(expired.code);726    try std.testing.expectError(727        error.InvalidInvite,728        state.store.signupWithInvite(expired.code, "late-player", "hunter2!!"),729    );730731    const revoked = try state.store.createInvite(allocator, "admin", 3600);732    defer allocator.free(revoked.id);733    defer allocator.free(revoked.code);734    try state.store.revokeInvite(revoked.id);735    try std.testing.expectError(736        error.InvalidInvite,737        state.store.signupWithInvite(revoked.code, "revoked-player", "hunter2!!"),738    );739}740741fn freeInviteViews(allocator: std.mem.Allocator, views: []InviteView) void {742    for (views) |view| {743        allocator.free(view.id);744        allocator.free(view.created_by);745        if (view.used_by) |used_by| allocator.free(used_by);746    }747    allocator.free(views);748}749750test "validation boundaries" {751    try std.testing.expect(!validateUsername("ab"));752    try std.testing.expect(validateUsername("abc"));753    try std.testing.expect(validateUsername("a" ** 32));754    try std.testing.expect(!validateUsername("a" ** 33));755    try std.testing.expect(validateUsername("a.b-c_9"));756    try std.testing.expect(validatePassword("12345678"));757    try std.testing.expect(!validatePassword("1234567"));758    try std.testing.expect(validatePassword("x" ** 128));759    try std.testing.expect(!validatePassword("x" ** 129));760}761762test "sessions expire and are pruned" {763    const allocator = std.testing.allocator;764    var sessions = Sessions.init(allocator);765    defer sessions.deinit();766767    const principal = Principal{ .username = "player-one", .is_admin = false };768    const expired = try sessions.create(0, principal);769    try std.testing.expect((try sessions.get(allocator, expired)) == null);770    try std.testing.expectEqual(@as(usize, 0), sessions.entries.count());771772    const live = try sessions.create(3600, principal);773    const found = (try sessions.get(allocator, live)).?;774    defer allocator.free(found.username);775    try std.testing.expectEqualStrings("player-one", found.username);776    try std.testing.expect(!found.is_admin);777778    // Creating a session prunes the entries that expired in the meantime.779    const second = try sessions.create(0, principal);780    try std.testing.expect((try sessions.get(allocator, second)) == null);781    sessions.destroy(live);782    try std.testing.expectEqual(@as(usize, 0), sessions.entries.count());783    sessions.destroy("never-issued");784}785786test "revoking unknown and used invites fails" {787    const allocator = std.testing.allocator;788789    var tmp = std.testing.tmpDir(.{});790    defer tmp.cleanup();791    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");792    defer allocator.free(storage_dir);793794    var store = try Store.init(allocator, null, storage_dir);795    defer store.deinit();796797    try std.testing.expectError(error.UnknownInvite, store.revokeInvite("missing"));798    try std.testing.expectError(error.UnknownInvite, store.revokeInvite(""));799800    const invite = try store.createInvite(allocator, "admin", 3600);801    defer allocator.free(invite.id);802    defer allocator.free(invite.code);803    _ = try store.signupWithInvite(invite.code, "player-one", "hunter2!!");804    try std.testing.expectError(error.InviteUsed, store.revokeInvite(invite.id));805}806807test "the invite list reports expired invites" {808    const allocator = std.testing.allocator;809810    var tmp = std.testing.tmpDir(.{});811    defer tmp.cleanup();812    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");813    defer allocator.free(storage_dir);814815    var store = try Store.init(allocator, null, storage_dir);816    defer store.deinit();817818    const invite = try store.createInvite(allocator, "admin", 0);819    defer allocator.free(invite.id);820    defer allocator.free(invite.code);821822    const views = try store.listInvites(allocator);823    defer freeInviteViews(allocator, views);824    try std.testing.expectEqual(@as(usize, 1), views.len);825    try std.testing.expectEqualStrings("expired", views[0].status);826    try std.testing.expectEqualStrings("admin", views[0].created_by);827    try std.testing.expect(views[0].used_by == null);828}829830test "signup trims the username and invite code, and admin names are case-insensitive" {831    const allocator = std.testing.allocator;832833    var tmp = std.testing.tmpDir(.{});834    defer tmp.cleanup();835    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");836    defer allocator.free(storage_dir);837838    const auth_config = config.WebAuth{839        .admin_username = "admin",840        .admin_password = "correct horse battery",841        .session_ttl_s = 3600,842        .invite_ttl_s = 3600,843        .cookie_secure = false,844    };845    var store = try Store.init(allocator, auth_config, storage_dir);846    defer store.deinit();847848    const admin = (try store.authenticate("ADMIN", "correct horse battery")).?;849    try std.testing.expect(admin.is_admin);850    try std.testing.expectEqualStrings("admin", admin.username);851852    const invite = try store.createInvite(allocator, "admin", 3600);853    defer allocator.free(invite.id);854    defer allocator.free(invite.code);855    const padded_code = try std.fmt.allocPrint(allocator, "  {s}  ", .{invite.code});856    defer allocator.free(padded_code);857    const player = try store.signupWithInvite(padded_code, "  player-one  ", "hunter2!!");858    try std.testing.expectEqualStrings("player-one", player.username);859860    // The plaintext password and invite code never reach the file.861    const body = try std.fs.cwd().readFileAlloc(allocator, store.path, max_auth_file_bytes);862    defer allocator.free(body);863    try std.testing.expect(std.mem.indexOf(u8, body, "hunter2!!") == null);864    try std.testing.expect(std.mem.indexOf(u8, body, invite.code) == null);865    try std.testing.expect(std.mem.indexOf(u8, body, "player-one") != null);866    try std.testing.expect(std.mem.indexOf(u8, body, invite.id) != null);867}868869test "a corrupt auth file is rejected instead of trusted" {870    const allocator = std.testing.allocator;871872    var tmp = std.testing.tmpDir(.{});873    defer tmp.cleanup();874    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");875    defer allocator.free(storage_dir);876877    var store = try Store.init(allocator, null, storage_dir);878    defer store.deinit();879880    try tmp.dir.writeFile(.{ .sub_path = "auth.json", .data = "not json" });881    try std.testing.expectError(error.InvalidAuthFile, store.load());882883    try tmp.dir.writeFile(.{884        .sub_path = "auth.json",885        .data = "{\"version\":1,\"users\":[{\"username\":\"x\",\"salt\":\"00\",\"hash\":\"00\"}]}",886    });887    try std.testing.expectError(error.InvalidAuthFile, store.load());888}889890test "an empty auth file is treated as a fresh store" {891    const allocator = std.testing.allocator;892893    var tmp = std.testing.tmpDir(.{});894    defer tmp.cleanup();895    const storage_dir = try tmp.dir.realpathAlloc(allocator, ".");896    defer allocator.free(storage_dir);897898    try tmp.dir.writeFile(.{ .sub_path = "auth.json", .data = "  \n" });899    var state = try State.init(allocator, null, storage_dir);900    defer state.deinit();901    try std.testing.expect(!state.enabled());902    try std.testing.expect(state.store.users.items.len == 0);903    try std.testing.expect((try state.store.authenticate("nobody", "hunter2!!")) == null);904}