LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 1901//! HTTP layer: one thread per connection, keep-alive, and a small router.2//!3//! Routes:4//! GET /up health check (used by once)5//! GET / chat page (embedded assets)6//! POST /api/chat {"message": "...", "history": [{"role", "content"}]}7//! A message starting with "/sql " runs that SELECT directly, without the model.89const std = @import("std");10const assets = @import("assets.zig");11const auth = @import("auth.zig");12const chat = @import("chat.zig");13const config = @import("config.zig");14const llm = @import("llm.zig");15const session = @import("session.zig");1617const log = std.log.scoped(.server);1819const max_request_bytes = 16 * 1024;20const max_message_bytes = 2000;21const max_history_turns = 10;22const max_history_bytes = 4000;2324pub const App = struct {25 allocator: std.mem.Allocator,26 config: config.Config,27 model: ?llm.Client,28 active_chats: std.atomic.Value(u32),29 auth: auth.State,30};3132const ChatRequest = struct {33 message: []const u8 = "",34 history: []const chat.Message = &.{},35};3637const ChatResponse = struct {38 answer: []const u8,39 queries: []const session.QueryOutput,40};4142const ErrorResponse = struct {43 @"error": []const u8,44};4546pub fn serve(app: *App) !void {47 const address = try std.net.Address.parseIp4("0.0.0.0", app.config.port);48 var listener = try address.listen(.{ .reuse_address = true });49 defer listener.deinit();50 log.info("listening on http://0.0.0.0:{d}", .{app.config.port});51 acceptLoop(app, &listener, null);52}5354/// Accepts connections until `stop` is set. `serve` passes null and loops for the55/// process lifetime; tests pass a flag so they can run a real listener in a thread56/// and shut it down again.57fn acceptLoop(app: *App, listener: *std.net.Server, stop: ?*const std.atomic.Value(bool)) void {58 while (true) {59 const connection = listener.accept() catch |err| {60 if (stop) |flag| {61 if (flag.load(.acquire)) return;62 }63 log.warn("accept failed: {s}", .{@errorName(err)});64 continue;65 };66 if (stop) |flag| {67 if (flag.load(.acquire)) {68 connection.stream.close();69 return;70 }71 }72 const thread = std.Thread.spawn(.{}, handleConnection, .{ app, connection }) catch |err| {73 log.warn("spawn failed: {s}", .{@errorName(err)});74 connection.stream.close();75 continue;76 };77 thread.detach();78 }79}8081fn handleConnection(app: *App, connection: std.net.Server.Connection) void {82 defer connection.stream.close();83 var read_buffer: [16 * 1024]u8 = undefined;84 var http = std.http.Server.init(connection, &read_buffer);85 while (true) {86 var request = http.receiveHead() catch return;87 handleRequest(app, &request) catch |err| {88 log.err("request failed: {s}", .{@errorName(err)});89 return;90 };91 if (!request.head.keep_alive) return;92 }93}9495fn handleRequest(app: *App, request: *std.http.Server.Request) !void {96 var arena = std.heap.ArenaAllocator.init(app.allocator);97 defer arena.deinit();98 const allocator = arena.allocator();99100 const target = request.head.target;101 const path = target[0 .. std.mem.indexOfScalar(u8, target, '?') orelse target.len];102 const is_get = request.head.method == .GET;103 const is_post = request.head.method == .POST;104105 if (is_get and std.mem.eql(u8, path, "/up")) {106 return respond(request, .ok, "text/plain; charset=utf-8", "ok");107 }108 if (is_get and (std.mem.eql(u8, path, "/") or109 std.mem.eql(u8, path, "/index.html") or110 std.mem.eql(u8, path, "/login") or111 std.mem.eql(u8, path, "/signup")))112 {113 return respond(request, .ok, "text/html; charset=utf-8", assets.index_html);114 }115 if (is_get and std.mem.eql(u8, path, "/app.js")) {116 return respond(request, .ok, "text/javascript; charset=utf-8", assets.app_js);117 }118 if (is_get and std.mem.eql(u8, path, "/style.css")) {119 return respond(request, .ok, "text/css; charset=utf-8", assets.style_css);120 }121122 // Browsers attach the session cookie to cross-site POSTs; reject those, and123 // rely on SameSite=Lax + a JSON body as the second line of defence.124 if (is_post and std.mem.startsWith(u8, path, "/api/") and !sameOrigin(request)) {125 return respondJson(request, allocator, .forbidden, ErrorResponse{ .@"error" = "cross-site request refused" });126 }127128 if (is_get and std.mem.eql(u8, path, "/api/auth/me")) {129 return handleMe(app, allocator, request);130 }131 if (is_post and std.mem.eql(u8, path, "/api/auth/login")) {132 return handleLogin(app, allocator, request);133 }134 if (is_post and std.mem.eql(u8, path, "/api/auth/signup")) {135 return handleSignup(app, allocator, request);136 }137 if (is_post and std.mem.eql(u8, path, "/api/auth/logout")) {138 return handleLogout(app, allocator, request);139 }140 if (is_get and std.mem.eql(u8, path, "/api/invites")) {141 return handleListInvites(app, allocator, request);142 }143 if (is_post and std.mem.eql(u8, path, "/api/invites")) {144 return handleCreateInvite(app, allocator, request);145 }146 if (is_post and std.mem.eql(u8, path, "/api/invites/revoke")) {147 return handleRevokeInvite(app, allocator, request);148 }149150 if (is_post and std.mem.eql(u8, path, "/api/chat")) {151 return handleChat(app, allocator, request);152 }153 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "not found" });154}155156const LoginRequest = struct {157 username: []const u8 = "",158 password: []const u8 = "",159};160161const SignupRequest = struct {162 username: []const u8 = "",163 password: []const u8 = "",164 invite: []const u8 = "",165};166167const InviteCreateRequest = struct {168 expires_in_hours: ?u32 = null,169};170171const InviteRevokeRequest = struct {172 id: []const u8 = "",173};174175const UserResponse = struct {176 username: []const u8,177 is_admin: bool,178};179180const MeResponse = struct {181 auth_enabled: bool,182 authenticated: bool,183 user: ?UserResponse,184};185186const CreatedInviteResponse = struct {187 id: []const u8,188 code: []const u8,189 path: []const u8,190 expires_at: i64,191};192193const InvitesResponse = struct {194 invites: []const auth.InviteView,195};196197fn handleMe(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {198 if (!app.auth.enabled()) {199 return respondJson(request, allocator, .ok, MeResponse{200 .auth_enabled = false,201 .authenticated = true,202 .user = null,203 });204 }205 if (try currentPrincipal(app, allocator, request)) |principal| {206 return respondJson(request, allocator, .ok, MeResponse{207 .auth_enabled = true,208 .authenticated = true,209 .user = .{ .username = principal.username, .is_admin = principal.is_admin },210 });211 }212 return respondJson(request, allocator, .ok, MeResponse{213 .auth_enabled = true,214 .authenticated = false,215 .user = null,216 });217}218219fn handleLogin(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {220 const auth_config = app.auth.config orelse221 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "login is disabled on this server" });222223 const parsed = readJsonBody(LoginRequest, allocator, request) orelse224 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "body must be JSON with username and password" });225 const username = std.mem.trim(u8, parsed.username, " \t\r\n");226 if (username.len == 0 or parsed.password.len == 0) {227 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "username and password are required" });228 }229230 const principal = (app.auth.store.authenticate(username, parsed.password) catch |err| {231 log.err("login check failed: {s}", .{@errorName(err)});232 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not check that login" });233 }) orelse return respondJson(request, allocator, .unauthorized, ErrorResponse{ .@"error" = "wrong username or password" });234235 const token = app.auth.sessions.create(auth_config.session_ttl_s, principal) catch |err| {236 log.err("could not create session: {s}", .{@errorName(err)});237 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not start a session" });238 };239 const cookie = try sessionCookie(app, allocator, request, token);240 return respondJsonExtra(request, allocator, .ok, .{241 .user = UserResponse{ .username = principal.username, .is_admin = principal.is_admin },242 }, &.{.{ .name = "set-cookie", .value = cookie }});243}244245fn handleSignup(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {246 const auth_config = app.auth.config orelse247 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "signup is disabled on this server" });248249 const parsed = readJsonBody(SignupRequest, allocator, request) orelse250 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "body must be JSON" });251 const invite = std.mem.trim(u8, parsed.invite, " \t\r\n");252 if (invite.len == 0) {253 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "an invite code is required" });254 }255256 const principal = app.auth.store.signupWithInvite(invite, parsed.username, parsed.password) catch |err| switch (err) {257 error.InvalidInvite => return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "this invite is invalid, expired or already used" }),258 error.UsernameTaken => return respondJson(request, allocator, .conflict, ErrorResponse{ .@"error" = "that username is taken" }),259 error.InvalidUsername => return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "usernames are 3-32 letters, digits, dots, dashes or underscores" }),260 error.WeakPassword => return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "passwords must be 8-128 characters" }),261 else => {262 log.err("signup failed: {s}", .{@errorName(err)});263 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not create the account" });264 },265 };266267 const token = app.auth.sessions.create(auth_config.session_ttl_s, principal) catch |err| {268 log.err("could not create session: {s}", .{@errorName(err)});269 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "account created, but the session could not be started; sign in instead" });270 };271 const cookie = try sessionCookie(app, allocator, request, token);272 return respondJsonExtra(request, allocator, .ok, .{273 .user = UserResponse{ .username = principal.username, .is_admin = principal.is_admin },274 }, &.{.{ .name = "set-cookie", .value = cookie }});275}276277fn handleLogout(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {278 if (cookieValue(request, auth.session_cookie)) |token| {279 app.auth.sessions.destroy(token);280 }281 const expired = try std.fmt.allocPrint(allocator, "{s}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0", .{auth.session_cookie});282 return respondJsonExtra(request, allocator, .ok, .{ .ok = true }, &.{.{ .name = "set-cookie", .value = expired }});283}284285fn handleListInvites(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {286 if (!app.auth.enabled()) {287 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "login is disabled on this server" });288 }289 _ = try requireAdmin(app, allocator, request) orelse return;290291 const invites = app.auth.store.listInvites(allocator) catch |err| {292 log.err("could not list invites: {s}", .{@errorName(err)});293 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not list invites" });294 };295 return respondJson(request, allocator, .ok, InvitesResponse{ .invites = invites });296}297298fn handleCreateInvite(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {299 const auth_config = app.auth.config orelse300 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "login is disabled on this server" });301 const principal = try requireAdmin(app, allocator, request) orelse return;302303 const parsed = readJsonBody(InviteCreateRequest, allocator, request) orelse304 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "body must be JSON" });305 const ttl_s: u64 = if (parsed.expires_in_hours) |hours| blk: {306 if (hours == 0 or hours > 24 * 365) {307 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "expires_in_hours must be between 1 and 8760" });308 }309 break :blk @as(u64, hours) * 3600;310 } else auth_config.invite_ttl_s;311312 const invite = app.auth.store.createInvite(allocator, principal.username, ttl_s) catch |err| {313 log.err("could not create invite: {s}", .{@errorName(err)});314 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not create the invite" });315 };316 const path = try std.fmt.allocPrint(allocator, "/signup?invite={s}", .{invite.code});317 return respondJson(request, allocator, .ok, CreatedInviteResponse{318 .id = invite.id,319 .code = invite.code,320 .path = path,321 .expires_at = invite.expires_at,322 });323}324325fn handleRevokeInvite(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {326 if (!app.auth.enabled()) {327 return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "login is disabled on this server" });328 }329 _ = try requireAdmin(app, allocator, request) orelse return;330331 const parsed = readJsonBody(InviteRevokeRequest, allocator, request) orelse332 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "body must be JSON" });333 const id = std.mem.trim(u8, parsed.id, " \t\r\n");334 if (id.len == 0) {335 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "an invite id is required" });336 }337338 app.auth.store.revokeInvite(id) catch |err| switch (err) {339 error.UnknownInvite => return respondJson(request, allocator, .not_found, ErrorResponse{ .@"error" = "no such invite" }),340 error.InviteUsed => return respondJson(request, allocator, .conflict, ErrorResponse{ .@"error" = "an invite that was used cannot be revoked" }),341 else => {342 log.err("could not revoke invite: {s}", .{@errorName(err)});343 return respondJson(request, allocator, .internal_server_error, ErrorResponse{ .@"error" = "could not revoke the invite" });344 },345 };346 return respondJson(request, allocator, .ok, .{ .revoked = true });347}348349/// Returns null after writing a 401/403 response, so callers use `orelse return`.350fn requireAdmin(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !?auth.Principal {351 const principal = (try currentPrincipal(app, allocator, request)) orelse {352 _ = respondJson(request, allocator, .unauthorized, ErrorResponse{ .@"error" = "please sign in" }) catch {};353 return null;354 };355 if (!principal.is_admin) {356 _ = respondJson(request, allocator, .forbidden, ErrorResponse{ .@"error" = "admins only" }) catch {};357 return null;358 }359 return principal;360}361362fn currentPrincipal(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !?auth.Principal {363 if (!app.auth.enabled()) return null;364 const token = cookieValue(request, auth.session_cookie) orelse return null;365 return app.auth.sessions.get(allocator, token);366}367368fn sessionCookie(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request, token: []const u8) ![]const u8 {369 const auth_config = app.auth.config.?;370 const secure = auth_config.cookie_secure or isHttpsValue(requestHeader(request, "x-forwarded-proto"));371 return sessionCookieValue(allocator, auth_config.session_ttl_s, secure, token);372}373374fn sessionCookieValue(allocator: std.mem.Allocator, ttl_s: u64, secure: bool, token: []const u8) ![]const u8 {375 return std.fmt.allocPrint(allocator, "{s}={s}; Path=/; HttpOnly; SameSite=Lax; Max-Age={d}{s}", .{376 auth.session_cookie,377 token,378 ttl_s,379 if (secure) "; Secure" else "",380 });381}382383fn isHttpsValue(proto: ?[]const u8) bool {384 const value = proto orelse return false;385 return std.ascii.eqlIgnoreCase(std.mem.trim(u8, value, " \t"), "https");386}387388fn cookieValueFromHeader(header: ?[]const u8, name: []const u8) ?[]const u8 {389 const text = header orelse return null;390 var parts = std.mem.splitScalar(u8, text, ';');391 while (parts.next()) |part| {392 const item = std.mem.trim(u8, part, " \t");393 const equals = std.mem.indexOfScalar(u8, item, '=') orelse continue;394 if (std.mem.eql(u8, item[0..equals], name)) return item[equals + 1 ..];395 }396 return null;397}398399fn cookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 {400 return cookieValueFromHeader(requestHeader(request, "cookie"), name);401}402403/// Rejects cross-site form posts. Same-origin fetches send an Origin header that404/// matches Host; non-browser clients without an Origin header are let through.405fn sameOriginValues(site: ?[]const u8, origin_header: ?[]const u8, host_header: ?[]const u8) bool {406 if (site) |value| {407 if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, value, " \t"), "cross-site")) return false;408 }409410 const origin = origin_header orelse return true;411 const host = host_header orelse return true;412 const trimmed = std.mem.trim(u8, origin, " \t");413 const after_scheme = if (std.mem.startsWith(u8, trimmed, "https://"))414 trimmed["https://".len..]415 else if (std.mem.startsWith(u8, trimmed, "http://"))416 trimmed["http://".len..]417 else418 return false;419420 const origin_host = after_scheme[0 .. std.mem.indexOfScalar(u8, after_scheme, '/') orelse after_scheme.len];421 return std.ascii.eqlIgnoreCase(stripPort(origin_host), stripPort(std.mem.trim(u8, host, " \t")));422}423424fn sameOrigin(request: *std.http.Server.Request) bool {425 return sameOriginValues(426 requestHeader(request, "sec-fetch-site"),427 requestHeader(request, "origin"),428 requestHeader(request, "host"),429 );430}431432fn stripPort(host: []const u8) []const u8 {433 var colons: usize = 0;434 for (host) |c| {435 if (c == ':') colons += 1;436 }437 if (colons != 1) return host;438 return host[0..std.mem.indexOfScalar(u8, host, ':').?];439}440441fn readJsonBody(comptime T: type, allocator: std.mem.Allocator, request: *std.http.Server.Request) ?T {442 var reader = request.reader() catch return null;443 const body = reader.readAllAlloc(allocator, max_request_bytes) catch return null;444 return std.json.parseFromSliceLeaky(T, allocator, body, .{ .ignore_unknown_fields = true }) catch null;445}446447fn handleChat(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {448 if (app.auth.enabled()) {449 _ = (try currentPrincipal(app, allocator, request)) orelse450 return respondJson(request, allocator, .unauthorized, ErrorResponse{ .@"error" = "please sign in" });451 }452453 const body = blk: {454 var reader = try request.reader();455 break :blk reader.readAllAlloc(allocator, max_request_bytes) catch456 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "request body is too large" });457 };458 const parsed = std.json.parseFromSliceLeaky(ChatRequest, allocator, body, .{ .ignore_unknown_fields = true }) catch459 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "body must be JSON with a message field" });460461 const message = std.mem.trim(u8, parsed.message, " \t\r\n");462 if (message.len == 0) {463 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "message is empty" });464 }465 if (message.len > max_message_bytes) {466 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "message is too long" });467 }468469 // Admission control: every chat opens its own DuckDB and makes network calls.470 if (app.active_chats.fetchAdd(1, .acq_rel) >= app.config.max_concurrent_requests) {471 _ = app.active_chats.fetchSub(1, .acq_rel);472 return respondJson(request, allocator, .too_many_requests, ErrorResponse{ .@"error" = "busy, try again in a moment" });473 }474 defer _ = app.active_chats.fetchSub(1, .acq_rel);475476 const sql_prefix = "/sql ";477 if (std.mem.eql(u8, message, "/sql")) {478 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "usage: /sql SELECT ..." });479 }480 if (std.mem.startsWith(u8, message, sql_prefix)) {481 return runDirectSql(app, allocator, request, std.mem.trim(u8, message[sql_prefix.len..], " \t\r\n"));482 }483 if (std.mem.eql(u8, message, "/tables")) {484 return runDescribe(app, allocator, request);485 }486487 const model = if (app.model) |*client| client else {488 return respondJson(request, allocator, .service_unavailable, ErrorResponse{489 .@"error" = "chat needs ANTHROPIC_API_KEY on the server; use /sql <query> for direct queries",490 });491 };492493 const history = try sanitizeHistory(allocator, parsed.history);494 const answer = chat.answer(allocator, &app.config, model, history, message) catch |err| {495 log.err("chat failed: {s}", .{@errorName(err)});496 // The lake session fails with DuckDbFailed; anything else comes from the model request.497 if (err == error.DuckDbFailed) {498 return respondJson(request, allocator, .bad_gateway, ErrorResponse{499 .@"error" = "the data lake is unavailable right now (see server log)",500 });501 }502 const text = try std.fmt.allocPrint(allocator, "the model request failed with {s}; check that the inference provider is reachable", .{@errorName(err)});503 return respondJson(request, allocator, .bad_gateway, ErrorResponse{ .@"error" = text });504 };505 return respondJson(request, allocator, .ok, ChatResponse{ .answer = answer.text, .queries = answer.queries });506}507508fn requestHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 {509 var headers = request.iterateHeaders();510 while (headers.next()) |header| {511 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value;512 }513 return null;514}515516fn runDescribe(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request) !void {517 var sess = session.Session.open(allocator, &app.config) catch |err| {518 log.err("session open failed: {s}", .{@errorName(err)});519 return respondJson(request, allocator, .bad_gateway, ErrorResponse{ .@"error" = "the data lake is unavailable right now" });520 };521 defer sess.deinit();522 const listing = try sess.describe(allocator);523 return respondJson(request, allocator, .ok, ChatResponse{ .answer = listing, .queries = &.{} });524}525526fn runDirectSql(app: *App, allocator: std.mem.Allocator, request: *std.http.Server.Request, sql: []const u8) !void {527 if (sql.len == 0) {528 return respondJson(request, allocator, .bad_request, ErrorResponse{ .@"error" = "usage: /sql SELECT ..." });529 }530 var sess = session.Session.open(allocator, &app.config) catch |err| {531 log.err("session open failed: {s}", .{@errorName(err)});532 return respondJson(request, allocator, .bad_gateway, ErrorResponse{ .@"error" = "the data lake is unavailable right now" });533 };534 defer sess.deinit();535536 const output = try sess.runQuery(allocator, sql);537 const outputs = [_]session.QueryOutput{output};538 return respondJson(request, allocator, .ok, ChatResponse{ .answer = "", .queries = &outputs });539}540541/// Keeps only well-formed recent turns, so the model never sees an empty or542/// oversized message, and the conversation starts with a user turn.543fn sanitizeHistory(allocator: std.mem.Allocator, history: []const chat.Message) ![]const chat.Message {544 var kept = std.ArrayList(chat.Message).init(allocator);545 const start = history.len -| max_history_turns;546 for (history[start..]) |turn| {547 const valid_role = std.mem.eql(u8, turn.role, "user") or std.mem.eql(u8, turn.role, "assistant");548 const content = std.mem.trim(u8, turn.content, " \t\r\n");549 if (!valid_role or content.len == 0 or content.len > max_history_bytes) continue;550 if (kept.items.len == 0 and !std.mem.eql(u8, turn.role, "user")) continue;551 try kept.append(.{ .role = turn.role, .content = content });552 }553 return kept.items;554}555556fn respond(557 request: *std.http.Server.Request,558 status: std.http.Status,559 content_type: []const u8,560 body: []const u8,561) !void {562 return respondExtra(request, status, content_type, body, &.{});563}564565const security_headers = [_]std.http.Header{566 .{ .name = "content-security-policy", .value = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'" },567 .{ .name = "x-content-type-options", .value = "nosniff" },568 .{ .name = "referrer-policy", .value = "no-referrer" },569 .{ .name = "cache-control", .value = "no-store" },570};571572fn respondExtra(573 request: *std.http.Server.Request,574 status: std.http.Status,575 content_type: []const u8,576 body: []const u8,577 extra: []const std.http.Header,578) !void {579 var headers: [10]std.http.Header = undefined;580 headers[0] = .{ .name = "content-type", .value = content_type };581 var count: usize = 1;582 for (security_headers) |header| {583 headers[count] = header;584 count += 1;585 }586 for (extra) |header| {587 if (count == headers.len) break;588 headers[count] = header;589 count += 1;590 }591 try request.respond(body, .{ .status = status, .extra_headers = headers[0..count] });592}593594fn respondJson(request: *std.http.Server.Request, allocator: std.mem.Allocator, status: std.http.Status, value: anytype) !void {595 return respondJsonExtra(request, allocator, status, value, &.{});596}597598fn respondJsonExtra(599 request: *std.http.Server.Request,600 allocator: std.mem.Allocator,601 status: std.http.Status,602 value: anytype,603 extra: []const std.http.Header,604) !void {605 const body = try std.json.stringifyAlloc(allocator, value, .{});606 return respondExtra(request, status, "application/json; charset=utf-8", body, extra);607}608609const testing = std.testing;610611test "stripPort only strips a single port separator" {612 try testing.expectEqualStrings("example.com", stripPort("example.com:8080"));613 try testing.expectEqualStrings("example.com", stripPort("example.com"));614 try testing.expectEqualStrings("[::1]:8080", stripPort("[::1]:8080"));615 try testing.expectEqualStrings("a:b:c", stripPort("a:b:c"));616}617618test "cookieValueFromHeader finds exactly the named cookie" {619 try testing.expectEqualStrings(620 "abc",621 cookieValueFromHeader("theme=dark; totenschloss_session=abc; x=1", auth.session_cookie).?,622 );623 try testing.expectEqualStrings(624 "abc",625 cookieValueFromHeader("totenschloss_session=abc", auth.session_cookie).?,626 );627 try testing.expectEqualStrings(628 "abc=def",629 cookieValueFromHeader(" totenschloss_session=abc=def ;", auth.session_cookie).?,630 );631 try testing.expect(cookieValueFromHeader("session=abc", auth.session_cookie) == null);632 try testing.expect(cookieValueFromHeader("totenschloss_session", auth.session_cookie) == null);633 try testing.expect(cookieValueFromHeader(null, auth.session_cookie) == null);634}635636test "sameOriginValues accepts same hosts and rejects cross-site posts" {637 try testing.expect(sameOriginValues(null, null, null));638 try testing.expect(sameOriginValues(null, "https://example.com", "example.com"));639 // Ports are stripped on both sides because a reverse proxy may rewrite either.640 try testing.expect(sameOriginValues(null, " http://Example.com:8080/chat ", "example.com:9090"));641 try testing.expect(sameOriginValues("same-origin", "https://example.com", "example.com"));642 try testing.expect(!sameOriginValues("cross-site", "https://example.com", "example.com"));643 try testing.expect(!sameOriginValues("Cross-Site", null, null));644 try testing.expect(!sameOriginValues(null, "https://evil.example", "example.com"));645 try testing.expect(!sameOriginValues(null, "ftp://example.com", "example.com"));646 // A non-browser client without Host is let through, as before.647 try testing.expect(sameOriginValues(null, "https://evil.example", null));648}649650test "isHttpsValue accepts the proxy header spelling" {651 try testing.expect(isHttpsValue("https"));652 try testing.expect(isHttpsValue(" HTTPS "));653 try testing.expect(!isHttpsValue("http"));654 try testing.expect(!isHttpsValue("https,http"));655 try testing.expect(!isHttpsValue(null));656}657658test "sessionCookieValue marks the cookie secure only when asked" {659 var arena = std.heap.ArenaAllocator.init(testing.allocator);660 defer arena.deinit();661 const plain = try sessionCookieValue(arena.allocator(), 3600, false, "tok");662 try testing.expectEqualStrings(663 "totenschloss_session=tok; Path=/; HttpOnly; SameSite=Lax; Max-Age=3600",664 plain,665 );666 const secure = try sessionCookieValue(arena.allocator(), 60, true, "tok");667 try testing.expect(std.mem.endsWith(u8, secure, "; Secure"));668}669670test "sanitizeHistory keeps recent, well-formed turns" {671 var arena = std.heap.ArenaAllocator.init(testing.allocator);672 defer arena.deinit();673 const a = arena.allocator();674675 const oversized = "x" ** (max_history_bytes + 1);676 const history = [_]chat.Message{677 .{ .role = "assistant", .content = "leading assistant" },678 .{ .role = "user", .content = " hello " },679 .{ .role = "system", .content = "wrong role" },680 .{ .role = "assistant", .content = " " },681 .{ .role = "assistant", .content = "hi there" },682 .{ .role = "user", .content = oversized },683 .{ .role = "user", .content = "last" },684 };685 const kept = try sanitizeHistory(a, &history);686 try testing.expectEqual(@as(usize, 3), kept.len);687 try testing.expectEqualStrings("user", kept[0].role);688 try testing.expectEqualStrings("hello", kept[0].content);689 try testing.expectEqualStrings("hi there", kept[1].content);690 try testing.expectEqualStrings("last", kept[2].content);691692 try testing.expectEqual(@as(usize, 0), (try sanitizeHistory(a, &.{})).len);693}694695test "sanitizeHistory keeps only the last ten turns" {696 var arena = std.heap.ArenaAllocator.init(testing.allocator);697 defer arena.deinit();698 const a = arena.allocator();699700 var history: [15]chat.Message = undefined;701 for (&history, 0..) |*turn, index| {702 turn.* = .{ .role = "user", .content = try std.fmt.allocPrint(a, "turn {d}", .{index}) };703 }704 const kept = try sanitizeHistory(a, &history);705 try testing.expectEqual(@as(usize, max_history_turns), kept.len);706 try testing.expectEqualStrings("turn 5", kept[0].content);707 try testing.expectEqualStrings("turn 14", kept[kept.len - 1].content);708}709710// ---- HTTP integration tests -------------------------------------------------711712const TestListener = struct {713 listener: std.net.Server,714 stop: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),715 thread: ?std.Thread = null,716 port: u16,717718 fn init() !TestListener {719 const address = try std.net.Address.parseIp4("127.0.0.1", 0);720 var listener = try address.listen(.{ .reuse_address = true });721 errdefer listener.deinit();722 return .{ .listener = listener, .port = listener.listen_address.getPort() };723 }724725 fn run(self: *TestListener, app: *App) !void {726 self.thread = try std.Thread.spawn(.{}, acceptLoop, .{ app, &self.listener, &self.stop });727 }728729 fn deinit(self: *TestListener) void {730 if (self.thread) |thread| {731 self.stop.store(true, .release);732 // Unblock accept() so the loop can observe the flag.733 const address = std.net.Address.parseIp4("127.0.0.1", self.port) catch unreachable;734 if (std.net.tcpConnectToAddress(address)) |stream| {735 stream.close();736 } else |_| {}737 thread.join();738 }739 self.listener.deinit();740 }741};742743fn testApp(allocator: std.mem.Allocator, storage_dir: []const u8, auth_config: ?config.WebAuth) !App {744 return .{745 .allocator = allocator,746 .config = .{747 .port = 0,748 .storage_dir = storage_dir,749 .extension_dir = "/tmp",750 .temp_dir = "/tmp",751 .lake_catalog = config.default_lake_catalog,752 .llm = null,753 .web_auth = auth_config,754 .query_timeout_ms = 30_000,755 .max_concurrent_requests = 4,756 },757 .model = null,758 .active_chats = std.atomic.Value(u32).init(0),759 .auth = try auth.State.init(allocator, auth_config, storage_dir),760 };761}762763fn httpRequest(764 allocator: std.mem.Allocator,765 port: u16,766 method: []const u8,767 path: []const u8,768 headers: []const [2][]const u8,769 body: ?[]const u8,770) ![]u8 {771 const address = try std.net.Address.parseIp4("127.0.0.1", port);772 var stream = try std.net.tcpConnectToAddress(address);773 defer stream.close();774775 var bytes = std.ArrayList(u8).init(allocator);776 defer bytes.deinit();777 const writer = bytes.writer();778 try writer.print("{s} {s} HTTP/1.1\r\nHost: 127.0.0.1:{d}\r\nConnection: close\r\n", .{ method, path, port });779 for (headers) |header| try writer.print("{s}: {s}\r\n", .{ header[0], header[1] });780 if (body) |content| {781 try writer.print("Content-Type: application/json\r\nContent-Length: {d}\r\n", .{content.len});782 }783 try writer.writeAll("\r\n");784 if (body) |content| try writer.writeAll(content);785786 try stream.writeAll(bytes.items);787 var reader = stream.reader();788 return reader.readAllAlloc(allocator, 1 << 20);789}790791fn bodyOf(response: []const u8) []const u8 {792 const split = std.mem.indexOf(u8, response, "\r\n\r\n") orelse return "";793 return response[split + 4 ..];794}795796fn expectStatus(response: []const u8, status: u16) !void {797 var prefix: [24]u8 = undefined;798 const line = try std.fmt.bufPrint(&prefix, "HTTP/1.1 {d} ", .{status});799 try testing.expect(std.mem.startsWith(u8, response, line));800}801802fn headerValue(response: []const u8, name: []const u8) ?[]const u8 {803 const head_end = std.mem.indexOf(u8, response, "\r\n\r\n") orelse response.len;804 var lines = std.mem.splitSequence(u8, response[0..head_end], "\r\n");805 _ = lines.next(); // status line806 while (lines.next()) |line| {807 const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;808 if (std.ascii.eqlIgnoreCase(line[0..colon], name)) {809 return std.mem.trim(u8, line[colon + 1 ..], " \t");810 }811 }812 return null;813}814815fn cookieOf(response: []const u8) ?[]const u8 {816 const set_cookie = headerValue(response, "set-cookie") orelse return null;817 const end = std.mem.indexOfScalar(u8, set_cookie, ';') orelse set_cookie.len;818 return set_cookie[0..end];819}820821fn jsonOf(allocator: std.mem.Allocator, response: []const u8) !std.json.Value {822 return std.json.parseFromSliceLeaky(std.json.Value, allocator, bodyOf(response), .{});823}824825fn errorOf(allocator: std.mem.Allocator, response: []const u8) ![]const u8 {826 const value = try jsonOf(allocator, response);827 return value.object.get("error").?.string;828}829830fn expectError(response: []const u8, allocator: std.mem.Allocator, text: []const u8) !void {831 try testing.expectEqualStrings(text, try errorOf(allocator, response));832}833834test "serves pages and assets and rejects cross-site posts" {835 var arena = std.heap.ArenaAllocator.init(testing.allocator);836 defer arena.deinit();837 const a = arena.allocator();838839 var tmp = testing.tmpDir(.{});840 defer tmp.cleanup();841 const storage_dir = try tmp.dir.realpathAlloc(testing.allocator, ".");842 defer testing.allocator.free(storage_dir);843844 var app = try testApp(testing.allocator, storage_dir, null);845 defer app.auth.deinit();846 var server = try TestListener.init();847 try server.run(&app);848 defer server.deinit();849850 const up = try httpRequest(a, server.port, "GET", "/up", &.{}, null);851 try expectStatus(up, 200);852 try testing.expectEqualStrings("ok", bodyOf(up));853 try testing.expectEqualStrings("text/plain; charset=utf-8", headerValue(up, "content-type").?);854 try testing.expect(headerValue(up, "content-security-policy") != null);855 try testing.expectEqualStrings("no-store", headerValue(up, "cache-control").?);856857 for ([_][]const u8{ "/", "/index.html", "/login", "/signup" }) |path| {858 const page = try httpRequest(a, server.port, "GET", path, &.{}, null);859 try expectStatus(page, 200);860 try testing.expectEqualStrings("text/html; charset=utf-8", headerValue(page, "content-type").?);861 try testing.expect(std.mem.startsWith(u8, bodyOf(page), "<!doctype html>"));862 }863864 const script = try httpRequest(a, server.port, "GET", "/app.js", &.{}, null);865 try expectStatus(script, 200);866 try testing.expectEqualStrings("text/javascript; charset=utf-8", headerValue(script, "content-type").?);867868 const style = try httpRequest(a, server.port, "GET", "/style.css", &.{}, null);869 try expectStatus(style, 200);870 try testing.expectEqualStrings("text/css; charset=utf-8", headerValue(style, "content-type").?);871 try testing.expect(std.mem.indexOf(u8, bodyOf(style), "--bg:") != null);872873 const missing = try httpRequest(a, server.port, "GET", "/nope", &.{}, null);874 try expectStatus(missing, 404);875 try expectError(missing, a, "not found");876877 const blocked = try httpRequest(878 a,879 server.port,880 "POST",881 "/api/auth/logout",882 &.{.{ "Origin", "http://evil.example" }},883 "{}",884 );885 try expectStatus(blocked, 403);886 try expectError(blocked, a, "cross-site request refused");887888 const allowed = try httpRequest(889 a,890 server.port,891 "POST",892 "/api/auth/logout",893 &.{.{ "Origin", "http://127.0.0.1" }},894 "{}",895 );896 try expectStatus(allowed, 200);897 try testing.expect(std.mem.indexOf(u8, headerValue(allowed, "set-cookie").?, "Max-Age=0") != null);898}899900test "auth endpoints report that login is disabled" {901 var arena = std.heap.ArenaAllocator.init(testing.allocator);902 defer arena.deinit();903 const a = arena.allocator();904905 var tmp = testing.tmpDir(.{});906 defer tmp.cleanup();907 const storage_dir = try tmp.dir.realpathAlloc(testing.allocator, ".");908 defer testing.allocator.free(storage_dir);909910 var app = try testApp(testing.allocator, storage_dir, null);911 defer app.auth.deinit();912 var server = try TestListener.init();913 try server.run(&app);914 defer server.deinit();915916 const me = try httpRequest(a, server.port, "GET", "/api/auth/me", &.{}, null);917 try expectStatus(me, 200);918 const me_value = try jsonOf(a, me);919 try testing.expect(!me_value.object.get("auth_enabled").?.bool);920 try testing.expect(me_value.object.get("authenticated").?.bool);921 try testing.expect(me_value.object.get("user").? == .null);922923 const login = try httpRequest(a, server.port, "POST", "/api/auth/login", &.{}, "{}");924 try expectStatus(login, 404);925 try expectError(login, a, "login is disabled on this server");926927 const signup = try httpRequest(a, server.port, "POST", "/api/auth/signup", &.{}, "{}");928 try expectStatus(signup, 404);929 try expectError(signup, a, "signup is disabled on this server");930931 const list = try httpRequest(a, server.port, "GET", "/api/invites", &.{}, null);932 try expectStatus(list, 404);933 try expectError(list, a, "login is disabled on this server");934935 const create = try httpRequest(a, server.port, "POST", "/api/invites", &.{}, "{}");936 try expectStatus(create, 404);937 try expectError(create, a, "login is disabled on this server");938}939940test "chat rejects bad input before reaching the model or the lake" {941 var arena = std.heap.ArenaAllocator.init(testing.allocator);942 defer arena.deinit();943 const a = arena.allocator();944945 var tmp = testing.tmpDir(.{});946 defer tmp.cleanup();947 const storage_dir = try tmp.dir.realpathAlloc(testing.allocator, ".");948 defer testing.allocator.free(storage_dir);949950 var app = try testApp(testing.allocator, storage_dir, null);951 defer app.auth.deinit();952 var server = try TestListener.init();953 try server.run(&app);954 defer server.deinit();955956 const malformed = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "not json");957 try expectStatus(malformed, 400);958 try expectError(malformed, a, "body must be JSON with a message field");959960 const empty = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "{\"message\":\" \"}");961 try expectStatus(empty, 400);962 try expectError(empty, a, "message is empty");963964 const long_body = try std.fmt.allocPrint(a, "{{\"message\":\"{s}\"}}", .{"x" ** (max_message_bytes + 1)});965 const long = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, long_body);966 try expectStatus(long, 400);967 try expectError(long, a, "message is too long");968969 const usage = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "{\"message\":\"/sql \"}");970 try expectStatus(usage, 400);971 try expectError(usage, a, "usage: /sql SELECT ...");972973 const no_model = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "{\"message\":\"who is the best player?\"}");974 try expectStatus(no_model, 503);975 try testing.expect(std.mem.indexOf(u8, try errorOf(a, no_model), "ANTHROPIC_API_KEY") != null);976977 app.active_chats.store(app.config.max_concurrent_requests, .release);978 const busy = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "{\"message\":\"hi\"}");979 app.active_chats.store(0, .release);980 try expectStatus(busy, 429);981 try expectError(busy, a, "busy, try again in a moment");982}983984test "login, invite, signup, admin access and logout work end to end" {985 var arena = std.heap.ArenaAllocator.init(testing.allocator);986 defer arena.deinit();987 const a = arena.allocator();988989 var tmp = testing.tmpDir(.{});990 defer tmp.cleanup();991 const storage_dir = try tmp.dir.realpathAlloc(testing.allocator, ".");992 defer testing.allocator.free(storage_dir);993994 const auth_config = config.WebAuth{995 .admin_username = "admin",996 .admin_password = "correct horse battery",997 .session_ttl_s = 3600,998 .invite_ttl_s = 3600,999 .cookie_secure = false,1000 };1001 var app = try testApp(testing.allocator, storage_dir, auth_config);1002 defer app.auth.deinit();1003 var server = try TestListener.init();1004 try server.run(&app);1005 defer server.deinit();10061007 const anon = try jsonOf(a, try httpRequest(a, server.port, "GET", "/api/auth/me", &.{}, null));1008 try testing.expect(anon.object.get("auth_enabled").?.bool);1009 try testing.expect(!anon.object.get("authenticated").?.bool);10101011 const need_login = try httpRequest(a, server.port, "POST", "/api/chat", &.{}, "{\"message\":\"hi\"}");1012 try expectStatus(need_login, 401);1013 try expectError(need_login, a, "please sign in");10141015 const wrong = try httpRequest(1016 a,1017 server.port,1018 "POST",1019 "/api/auth/login",1020 &.{},1021 "{\"username\":\"admin\",\"password\":\"not the password\"}",1022 );1023 try expectStatus(wrong, 401);1024 try expectError(wrong, a, "wrong username or password");10251026 const login = try httpRequest(1027 a,1028 server.port,1029 "POST",1030 "/api/auth/login",1031 &.{},1032 "{\"username\":\"admin\",\"password\":\"correct horse battery\"}",1033 );1034 try expectStatus(login, 200);1035 const admin_cookie = cookieOf(login).?;1036 try testing.expect(std.mem.startsWith(u8, admin_cookie, "totenschloss_session="));1037 try testing.expect(std.mem.indexOf(u8, headerValue(login, "set-cookie").?, "HttpOnly") != null);1038 try testing.expect(std.mem.indexOf(u8, headerValue(login, "set-cookie").?, "Secure") == null);10391040 const me = try jsonOf(a, try httpRequest(1041 a,1042 server.port,1043 "GET",1044 "/api/auth/me",1045 &.{.{ "Cookie", admin_cookie }},1046 null,1047 ));1048 try testing.expect(me.object.get("authenticated").?.bool);1049 try testing.expect(me.object.get("user").?.object.get("is_admin").?.bool);1050 try testing.expectEqualStrings("admin", me.object.get("user").?.object.get("username").?.string);10511052 const list_empty = try jsonOf(a, try httpRequest(1053 a,1054 server.port,1055 "GET",1056 "/api/invites",1057 &.{.{ "Cookie", admin_cookie }},1058 null,1059 ));1060 try testing.expectEqual(@as(usize, 0), list_empty.object.get("invites").?.array.items.len);10611062 const created = try jsonOf(a, try httpRequest(1063 a,1064 server.port,1065 "POST",1066 "/api/invites",1067 &.{.{ "Cookie", admin_cookie }},1068 "{}",1069 ));1070 const invite_code = created.object.get("code").?.string;1071 const invite_id = created.object.get("id").?.string;1072 try testing.expectEqual(@as(usize, 32), invite_code.len);1073 try testing.expect(std.mem.startsWith(u8, created.object.get("path").?.string, "/signup?invite="));10741075 const signup_body = try std.fmt.allocPrint(1076 a,1077 "{{\"invite\":\"{s}\",\"username\":\"player-one\",\"password\":\"hunter2!!\"}}",1078 .{invite_code},1079 );1080 const signup = try httpRequest(a, server.port, "POST", "/api/auth/signup", &.{}, signup_body);1081 try expectStatus(signup, 200);1082 const player_cookie = cookieOf(signup).?;1083 const signup_value = try jsonOf(a, signup);1084 try testing.expectEqualStrings("player-one", signup_value.object.get("user").?.object.get("username").?.string);1085 try testing.expect(!signup_value.object.get("user").?.object.get("is_admin").?.bool);10861087 const reused = try httpRequest(1088 a,1089 server.port,1090 "POST",1091 "/api/auth/signup",1092 &.{},1093 try std.fmt.allocPrint(1094 a,1095 "{{\"invite\":\"{s}\",\"username\":\"player-two\",\"password\":\"hunter2!!\"}}",1096 .{invite_code},1097 ),1098 );1099 try expectStatus(reused, 400);1100 try expectError(reused, a, "this invite is invalid, expired or already used");11011102 const forbidden = try httpRequest(1103 a,1104 server.port,1105 "GET",1106 "/api/invites",1107 &.{.{ "Cookie", player_cookie }},1108 null,1109 );1110 try expectStatus(forbidden, 403);1111 try expectError(forbidden, a, "admins only");11121113 const revoke_used = try httpRequest(1114 a,1115 server.port,1116 "POST",1117 "/api/invites/revoke",1118 &.{.{ "Cookie", admin_cookie }},1119 try std.fmt.allocPrint(a, "{{\"id\":\"{s}\"}}", .{invite_id}),1120 );1121 try expectStatus(revoke_used, 409);1122 try expectError(revoke_used, a, "an invite that was used cannot be revoked");11231124 const revoke_unknown = try httpRequest(1125 a,1126 server.port,1127 "POST",1128 "/api/invites/revoke",1129 &.{.{ "Cookie", admin_cookie }},1130 "{\"id\":\"nope\"}",1131 );1132 try expectStatus(revoke_unknown, 404);1133 try expectError(revoke_unknown, a, "no such invite");11341135 const second = try jsonOf(a, try httpRequest(1136 a,1137 server.port,1138 "POST",1139 "/api/invites",1140 &.{.{ "Cookie", admin_cookie }},1141 "{\"expires_in_hours\":1}",1142 ));1143 const revoked = try httpRequest(1144 a,1145 server.port,1146 "POST",1147 "/api/invites/revoke",1148 &.{.{ "Cookie", admin_cookie }},1149 try std.fmt.allocPrint(a, "{{\"id\":\"{s}\"}}", .{second.object.get("id").?.string}),1150 );1151 try expectStatus(revoked, 200);1152 try testing.expect((try jsonOf(a, revoked)).object.get("revoked").?.bool);11531154 const list = try jsonOf(a, try httpRequest(1155 a,1156 server.port,1157 "GET",1158 "/api/invites",1159 &.{.{ "Cookie", admin_cookie }},1160 null,1161 ));1162 try testing.expectEqual(@as(usize, 1), list.object.get("invites").?.array.items.len);1163 try testing.expectEqualStrings("used", list.object.get("invites").?.array.items[0].object.get("status").?.string);11641165 const logout = try httpRequest(1166 a,1167 server.port,1168 "POST",1169 "/api/auth/logout",1170 &.{.{ "Cookie", player_cookie }},1171 "{}",1172 );1173 try expectStatus(logout, 200);1174 try testing.expect(std.mem.indexOf(u8, headerValue(logout, "set-cookie").?, "Max-Age=0") != null);11751176 const after_logout = try jsonOf(a, try httpRequest(1177 a,1178 server.port,1179 "GET",1180 "/api/auth/me",1181 &.{.{ "Cookie", player_cookie }},1182 null,1183 ));1184 try testing.expect(!after_logout.object.get("authenticated").?.bool);11851186 const https_login = try httpRequest(1187 a,1188 server.port,1189 "POST",1190 "/api/auth/login",1191 &.{.{ "X-Forwarded-Proto", "https" }},1192 "{\"username\":\"admin\",\"password\":\"correct horse battery\"}",1193 );1194 try expectStatus(https_login, 200);1195 try testing.expect(std.mem.endsWith(u8, headerValue(https_login, "set-cookie").?, "; Secure"));1196}