LINE1 10 20 30 40 50 60 70 80 90 100 110 120 1301//! Runtime configuration, read from environment variables once at startup.23const std = @import("std");45pub const default_lake_catalog = "https://data.deadlock-api.com/v1/catalog.ducklake";6pub const default_anthropic_url = "https://api.anthropic.com";7/// Divine's documented local development address.8pub const default_inference_api = "http://localhost:9090";9pub const default_model = "claude-sonnet-5-5";1011pub const Auth = enum { x_api_key, bearer };1213/// Web login. The admin account comes from the environment; everyone else joins14/// with a single-use invite created by an admin. Null disables login entirely.15pub const WebAuth = struct {16 admin_username: []const u8,17 admin_password: []const u8,18 /// How long a browser session stays valid.19 session_ttl_s: u64,20 /// Default lifetime of an invite.21 invite_ttl_s: u64,22 /// Mark the session cookie `Secure`. Also set automatically for HTTPS requests23 /// arriving through a proxy that sends `X-Forwarded-Proto: https`.24 cookie_secure: bool,25};2627pub const default_admin_username = "admin";28pub const default_ttl_hours = 7 * 24;2930/// The model provider the chat talks to. Null means chat is disabled and only `/sql` works.31pub const Llm = struct {32 api_key: []const u8,33 /// Base URL without a trailing slash. The client appends `/v1/messages`.34 base_url: []const u8,35 model: []const u8,36 auth: Auth,37};3839pub const Config = struct {40 port: u16,41 storage_dir: []const u8,42 /// DuckDB extension cache. Lives under the storage dir so it survives restarts.43 extension_dir: [:0]const u8,44 /// DuckDB spill directory. Also under the storage dir.45 temp_dir: [:0]const u8,46 /// HTTPS URL of the DuckLake catalog file.47 lake_catalog: []const u8,48 llm: ?Llm,49 /// Web login and signups. Null leaves the site open without a login.50 web_auth: ?WebAuth,51 query_timeout_ms: u64,52 /// Chats (LLM or `/sql`) allowed at once. Extra requests get HTTP 429.53 max_concurrent_requests: u32,54};5556/// Reads configuration from the environment. Allocations are never freed, which is57/// fine for values that live for the whole process.58///59/// Provider precedence: `INFERENCE_API_KEY` selects Divine (Anthropic Messages format,60/// bearer auth, under `INFERENCE_API`). Otherwise `ANTHROPIC_API_KEY` selects Anthropic directly.61pub fn load(allocator: std.mem.Allocator) !Config {62 // Both the map and its values live for the process, like the getEnvVarOwned63 // results this used to hold.64 var env = try std.process.getEnvMap(allocator);65 return loadFrom(allocator, &env);66}6768/// The testable half of `load`: `env` is anything with `get(key) ?[]const u8`,69/// typically a `std.process.EnvMap` or `std.StringHashMap([]const u8)`.70fn loadFrom(allocator: std.mem.Allocator, env: anytype) !Config {71 const storage_dir = try envOr(env, "STORAGE_PATH", "storage");72 const port = try std.fmt.parseInt(u16, try envOr(env, "PORT", "8080"), 10);73 const lake_catalog = try envOr(env, "LAKE_CATALOG", default_lake_catalog);74 if (!std.mem.startsWith(u8, lake_catalog, "https://") or std.mem.indexOfAny(u8, lake_catalog, "'\r\n ") != null) {75 return error.InvalidLakeCatalog;76 }7778 return .{79 .port = port,80 .storage_dir = storage_dir,81 .extension_dir = try std.fmt.allocPrintZ(allocator, "{s}/duckdb_extensions", .{storage_dir}),82 .temp_dir = try std.fmt.allocPrintZ(allocator, "{s}/duckdb_tmp", .{storage_dir}),83 .lake_catalog = lake_catalog,84 .llm = try loadLlm(allocator, env),85 .web_auth = try loadWebAuth(env),86 .query_timeout_ms = 30_000,87 .max_concurrent_requests = 4,88 };89}9091/// `ADMIN_PASSWORD` turns on login. The admin account is not stored on disk: it is92/// checked against the environment on every login, so rotating the password is a93/// restart with a new value.94fn loadWebAuth(env: anytype) !?WebAuth {95 const password = envValue(env, "ADMIN_PASSWORD") orelse return null;96 if (password.len < 8 or password.len > 256) return error.InvalidAdminPassword;9798 const username = try envOr(env, "ADMIN_USERNAME", default_admin_username);99 if (!validUsername(username)) return error.InvalidAdminUsername;100101 return .{102 .admin_username = username,103 .admin_password = password,104 .session_ttl_s = try envHours(env, "SESSION_TTL_HOURS", default_ttl_hours) * 3600,105 .invite_ttl_s = try envHours(env, "INVITE_TTL_HOURS", default_ttl_hours) * 3600,106 .cookie_secure = envBool(env, "COOKIE_SECURE"),107 };108}109110fn validUsername(name: []const u8) bool {111 if (name.len < 3 or name.len > 32) return false;112 for (name) |c| {113 if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-' and c != '.') return false;114 }115 return true;116}117118fn envHours(env: anytype, key: []const u8, default: u64) !u64 {119 const raw = try envOr(env, key, "");120 if (raw.len == 0) return default;121 const hours = std.fmt.parseInt(u64, raw, 10) catch return error.InvalidDuration;122 if (hours == 0 or hours > 24 * 365) return error.InvalidDuration;123 return hours;124}125126fn envBool(env: anytype, key: []const u8) bool {127 const raw = envValue(env, key) orelse return false;128 return std.ascii.eqlIgnoreCase(raw, "1") or129 std.ascii.eqlIgnoreCase(raw, "true") or130 std.ascii.eqlIgnoreCase(raw, "yes") or131 std.ascii.eqlIgnoreCase(raw, "on");132}133134fn loadLlm(allocator: std.mem.Allocator, env: anytype) !?Llm {135 if (envValue(env, "INFERENCE_API_KEY")) |api_key| {136 const base = try envOr(env, "INFERENCE_API", default_inference_api);137 return .{138 .api_key = api_key,139 .base_url = try std.fmt.allocPrint(allocator, "{s}/anthropic", .{std.mem.trimRight(u8, base, "/")}),140 .model = try envOr(env, "INFERENCE_MODEL", default_model),141 .auth = .bearer,142 };143 }144 if (envValue(env, "ANTHROPIC_API_KEY")) |api_key| {145 return .{146 .api_key = api_key,147 .base_url = try envOr(env, "ANTHROPIC_BASE_URL", default_anthropic_url),148 .model = try envOr(env, "ANTHROPIC_MODEL", default_model),149 .auth = .x_api_key,150 };151 }152 return null;153}154155fn envOr(env: anytype, key: []const u8, default: []const u8) ![]const u8 {156 return envValue(env, key) orelse default;157}158159fn envValue(env: anytype, key: []const u8) ?[]const u8 {160 const value = env.get(key) orelse return null;161 if (value.len == 0) return null;162 return value;163}164165const testing = std.testing;166const TestEnv = std.StringHashMap([]const u8);167168fn testConfig(allocator: std.mem.Allocator, pairs: []const [2][]const u8) !Config {169 var env = TestEnv.init(allocator);170 defer env.deinit();171 for (pairs) |pair| try env.put(pair[0], pair[1]);172 return loadFrom(allocator, &env);173}174175fn expectConfigError(pairs: []const [2][]const u8, expected: anyerror) !void {176 var arena = std.heap.ArenaAllocator.init(testing.allocator);177 defer arena.deinit();178 try testing.expectError(expected, testConfig(arena.allocator(), pairs));179}180181test "defaults without any environment variables" {182 var arena = std.heap.ArenaAllocator.init(testing.allocator);183 defer arena.deinit();184 const cfg = try testConfig(arena.allocator(), &.{});185186 try testing.expectEqual(@as(u16, 8080), cfg.port);187 try testing.expectEqualStrings("storage", cfg.storage_dir);188 try testing.expectEqualStrings("storage/duckdb_extensions", cfg.extension_dir);189 try testing.expectEqualStrings("storage/duckdb_tmp", cfg.temp_dir);190 try testing.expectEqualStrings(default_lake_catalog, cfg.lake_catalog);191 try testing.expect(cfg.llm == null);192 try testing.expect(cfg.web_auth == null);193 try testing.expectEqual(@as(u64, 30_000), cfg.query_timeout_ms);194 try testing.expectEqual(@as(u32, 4), cfg.max_concurrent_requests);195}196197test "port and storage path come from the environment" {198 var arena = std.heap.ArenaAllocator.init(testing.allocator);199 defer arena.deinit();200 const cfg = try testConfig(arena.allocator(), &.{201 .{ "PORT", "9090" },202 .{ "STORAGE_PATH", "/var/lib/totenschloss" },203 });204 try testing.expectEqual(@as(u16, 9090), cfg.port);205 try testing.expectEqualStrings("/var/lib/totenschloss/duckdb_extensions", cfg.extension_dir);206207 try expectConfigError(&.{.{ "PORT", "eighty" }}, error.InvalidCharacter);208 try expectConfigError(&.{.{ "PORT", "70000" }}, error.Overflow);209}210211test "the lake catalog must be an https url without quoting or whitespace" {212 var arena = std.heap.ArenaAllocator.init(testing.allocator);213 defer arena.deinit();214215 const good = try testConfig(arena.allocator(), &.{216 .{ "LAKE_CATALOG", "https://example.com/catalog.ducklake" },217 });218 try testing.expectEqualStrings("https://example.com/catalog.ducklake", good.lake_catalog);219220 try expectConfigError(&.{.{ "LAKE_CATALOG", "http://example.com/x" }}, error.InvalidLakeCatalog);221 try expectConfigError(&.{.{ "LAKE_CATALOG", "https://example.com/a b" }}, error.InvalidLakeCatalog);222 try expectConfigError(&.{.{ "LAKE_CATALOG", "https://example.com/a'b" }}, error.InvalidLakeCatalog);223 try expectConfigError(&.{.{ "LAKE_CATALOG", "https://example.com/a\nb" }}, error.InvalidLakeCatalog);224}225226test "admin login configuration is validated" {227 var arena = std.heap.ArenaAllocator.init(testing.allocator);228 defer arena.deinit();229230 const cfg = try testConfig(arena.allocator(), &.{231 .{ "ADMIN_PASSWORD", "correct horse" },232 });233 const admin = cfg.web_auth.?;234 try testing.expectEqualStrings("admin", admin.admin_username);235 try testing.expectEqualStrings("correct horse", admin.admin_password);236 try testing.expectEqual(@as(u64, 168 * 3600), admin.session_ttl_s);237 try testing.expectEqual(@as(u64, 168 * 3600), admin.invite_ttl_s);238 try testing.expect(!admin.cookie_secure);239240 const custom = try testConfig(arena.allocator(), &.{241 .{ "ADMIN_PASSWORD", "correct horse" },242 .{ "ADMIN_USERNAME", "host.one" },243 .{ "SESSION_TTL_HOURS", "1" },244 .{ "INVITE_TTL_HOURS", "24" },245 .{ "COOKIE_SECURE", "YES" },246 });247 try testing.expectEqualStrings("host.one", custom.web_auth.?.admin_username);248 try testing.expectEqual(@as(u64, 3600), custom.web_auth.?.session_ttl_s);249 try testing.expectEqual(@as(u64, 24 * 3600), custom.web_auth.?.invite_ttl_s);250 try testing.expect(custom.web_auth.?.cookie_secure);251252 try expectConfigError(&.{.{ "ADMIN_PASSWORD", "short" }}, error.InvalidAdminPassword);253 try expectConfigError(&.{ .{ "ADMIN_PASSWORD", "correct horse" }, .{ "ADMIN_USERNAME", "ab" } }, error.InvalidAdminUsername);254 try expectConfigError(&.{ .{ "ADMIN_PASSWORD", "correct horse" }, .{ "ADMIN_USERNAME", "bad name" } }, error.InvalidAdminUsername);255 try expectConfigError(&.{ .{ "ADMIN_PASSWORD", "correct horse" }, .{ "SESSION_TTL_HOURS", "0" } }, error.InvalidDuration);256 try expectConfigError(&.{ .{ "ADMIN_PASSWORD", "correct horse" }, .{ "SESSION_TTL_HOURS", "8761" } }, error.InvalidDuration);257 try expectConfigError(&.{ .{ "ADMIN_PASSWORD", "correct horse" }, .{ "INVITE_TTL_HOURS", "soon" } }, error.InvalidDuration);258}259260test "an empty admin password leaves login disabled" {261 var arena = std.heap.ArenaAllocator.init(testing.allocator);262 defer arena.deinit();263 const cfg = try testConfig(arena.allocator(), &.{264 .{ "ADMIN_PASSWORD", "" },265 .{ "ADMIN_USERNAME", "not-validated-while-disabled" },266 });267 try testing.expect(cfg.web_auth == null);268}269270test "cookie_secure accepts the usual spellings" {271 var arena = std.heap.ArenaAllocator.init(testing.allocator);272 defer arena.deinit();273 for ([_][]const u8{ "1", "true", "TRUE", "yes", "on" }) |value| {274 const cfg = try testConfig(arena.allocator(), &.{275 .{ "ADMIN_PASSWORD", "correct horse" },276 .{ "COOKIE_SECURE", value },277 });278 try testing.expect(cfg.web_auth.?.cookie_secure);279 }280 for ([_][]const u8{ "0", "false", "off", "anything else" }) |value| {281 const cfg = try testConfig(arena.allocator(), &.{282 .{ "ADMIN_PASSWORD", "correct horse" },283 .{ "COOKIE_SECURE", value },284 });285 try testing.expect(!cfg.web_auth.?.cookie_secure);286 }287}288289test "inference provider wins over anthropic and builds its base url" {290 var arena = std.heap.ArenaAllocator.init(testing.allocator);291 defer arena.deinit();292293 const inference = try testConfig(arena.allocator(), &.{294 .{ "INFERENCE_API_KEY", "divine-key" },295 });296 const llm_cfg = inference.llm.?;297 try testing.expectEqualStrings("divine-key", llm_cfg.api_key);298 try testing.expectEqualStrings("http://localhost:9090/anthropic", llm_cfg.base_url);299 try testing.expectEqualStrings(default_model, llm_cfg.model);300 try testing.expectEqual(Auth.bearer, llm_cfg.auth);301302 const trailing = try testConfig(arena.allocator(), &.{303 .{ "INFERENCE_API_KEY", "divine-key" },304 .{ "INFERENCE_API", "https://divine.example///" },305 .{ "INFERENCE_MODEL", "fast-model" },306 });307 try testing.expectEqualStrings("https://divine.example/anthropic", trailing.llm.?.base_url);308 try testing.expectEqualStrings("fast-model", trailing.llm.?.model);309310 const both = try testConfig(arena.allocator(), &.{311 .{ "INFERENCE_API_KEY", "divine-key" },312 .{ "ANTHROPIC_API_KEY", "anthropic-key" },313 });314 try testing.expectEqual(Auth.bearer, both.llm.?.auth);315 try testing.expectEqualStrings("divine-key", both.llm.?.api_key);316}317318test "anthropic is the fallback provider" {319 var arena = std.heap.ArenaAllocator.init(testing.allocator);320 defer arena.deinit();321322 const cfg = try testConfig(arena.allocator(), &.{323 .{ "ANTHROPIC_API_KEY", "anthropic-key" },324 });325 try testing.expectEqualStrings("anthropic-key", cfg.llm.?.api_key);326 try testing.expectEqualStrings(default_anthropic_url, cfg.llm.?.base_url);327 try testing.expectEqualStrings(default_model, cfg.llm.?.model);328 try testing.expectEqual(Auth.x_api_key, cfg.llm.?.auth);329330 const custom = try testConfig(arena.allocator(), &.{331 .{ "ANTHROPIC_API_KEY", "anthropic-key" },332 .{ "ANTHROPIC_BASE_URL", "https://proxy.example" },333 .{ "ANTHROPIC_MODEL", "other-model" },334 });335 try testing.expectEqualStrings("https://proxy.example", custom.llm.?.base_url);336 try testing.expectEqualStrings("other-model", custom.llm.?.model);337}