siga

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

commit 870f09ed6f3dcb7b4876188577a9f0fcc52df565
parent 7065bc3eebd67115bd765ef2740b9e6c339ea018
Author: Gabriel G. de Brito <me@gboncoffee.dev.br>
Date:   Thu, 19 Nov 2026 14:29:01 -0300

Require authentication on event routes.

Add an auth module that validates `Authorization: Bearer <uuid>` tokens
against the Go auth service (GET /{uuid}). Only canonical UUIDs are put
in the URL, so a crafted token cannot reach other auth routes.

All event routes now answer 401 without a valid session and 503 when the
auth service is unreachable. The auth service URL comes from
SIGA_AUTH_URL (default http://localhost:8080). Adds a `zig build test`
step with unit tests for the token parsing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
Mevent_registration/build.zig | 15+++++++++++++++
Aevent_registration/src/auth/auth.zig | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mevent_registration/src/main.zig | 6+++++-
Mevent_registration/src/server/server.zig | 34++++++++++++++++++++++++++++++++--
4 files changed, 171 insertions(+), 3 deletions(-)

diff --git a/event_registration/build.zig b/event_registration/build.zig @@ -41,15 +41,30 @@ pub fn build(b: *std.Build) void { }), }); + const auth = b.addLibrary(.{ + .name = "auth", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/auth/auth.zig"), + .target = target, + .optimize = optimize, + }), + }); + exe.root_module.addImport("repository", repo.root_module); exe.root_module.addImport("server", server.root_module); + exe.root_module.addImport("auth", auth.root_module); repo.root_module.addImport("sqlite", sqlite.module("sqlite")); server.root_module.addImport("httpz", httpz.module("httpz")); server.root_module.addImport("repository", repo.root_module); + server.root_module.addImport("auth", auth.root_module); b.installArtifact(exe); const run_exe = b.addRunArtifact(exe); const run_step = b.step("run", "Run the program"); run_step.dependOn(&run_exe.step); + + const auth_tests = b.addTest(.{ .root_module = auth.root_module }); + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&b.addRunArtifact(auth_tests).step); } diff --git a/event_registration/src/auth/auth.zig b/event_registration/src/auth/auth.zig @@ -0,0 +1,119 @@ +//! Client for the SIGA authentication service (`auth/`, written in Go). +//! +//! The auth service hands out session tokens (UUIDs) on `POST /login` and +//! answers `GET /{uuid}` with 200 when the session exists, 401 when it does +//! not and 400 when the token is malformed. Clients of this service send the +//! token as `Authorization: Bearer <uuid>`. + +const std = @import("std"); + +pub const Auth = @This(); + +pub const default_url = "http://localhost:8080"; + +/// Canonical textual UUID length: 8-4-4-4-12 hex digits. +const uuid_len = 36; + +pub const Result = enum { + authenticated, + /// No `Authorization: Bearer` header, or the token is not a UUID. + missing_token, + /// The auth service does not know this session. + invalid_token, + /// The auth service could not be reached or gave an unexpected answer. + unavailable, +}; + +client: std.http.Client, +base_url: []const u8, + +/// `allocator` must be thread-safe: the client is shared by every worker. +/// `base_url` must outlive the returned value and have no trailing slash. +pub fn init(io: std.Io, allocator: std.mem.Allocator, base_url: []const u8) Auth { + return .{ + .client = .{ .io = io, .allocator = allocator }, + .base_url = std.mem.trimEnd(u8, base_url, "/"), + }; +} + +pub fn deinit(a: *Auth) void { + a.client.deinit(); +} + +/// Checks the value of an `Authorization` header against the auth service. +/// Safe to call from several threads at once. +pub fn authenticate(a: *Auth, authorization: ?[]const u8) Result { + const token = tokenFromHeader(authorization) orelse return .missing_token; + return a.validate(token); +} + +/// Asks the auth service whether `token` is an open session. +pub fn validate(a: *Auth, token: []const u8) Result { + // The token goes into the URL path, so only ever send a well-formed UUID. + if (!isUuid(token)) return .missing_token; + + var url_buf: [512]u8 = undefined; + const url = std.fmt.bufPrint(&url_buf, "{s}/{s}", .{ a.base_url, token }) catch { + std.log.err("auth: base url too long: {s}", .{a.base_url}); + return .unavailable; + }; + + const result = a.client.fetch(.{ + .location = .{ .url = url }, + .method = .GET, + .redirect_behavior = .unhandled, + }) catch |err| { + std.log.err("auth: request to {s} failed: {t}", .{ a.base_url, err }); + return .unavailable; + }; + + return switch (result.status) { + .ok => .authenticated, + .unauthorized, .bad_request => .invalid_token, + else => |status| { + std.log.err("auth: unexpected status {d}", .{@intFromEnum(status)}); + return .unavailable; + }, + }; +} + +/// Extracts the token from an `Authorization: Bearer <token>` header value. +pub fn tokenFromHeader(authorization: ?[]const u8) ?[]const u8 { + const value = std.mem.trim(u8, authorization orelse return null, " \t"); + const scheme = "bearer "; + if (value.len <= scheme.len) return null; + if (!std.ascii.eqlIgnoreCase(value[0..scheme.len], scheme)) return null; + + const token = std.mem.trim(u8, value[scheme.len..], " \t"); + return if (token.len == 0) null else token; +} + +/// Whether `s` is a UUID in canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` form. +pub fn isUuid(s: []const u8) bool { + if (s.len != uuid_len) return false; + for (s, 0..) |c, i| switch (i) { + 8, 13, 18, 23 => if (c != '-') return false, + else => if (!std.ascii.isHex(c)) return false, + }; + return true; +} + +test tokenFromHeader { + const t = std.testing; + try t.expectEqualStrings("abc", tokenFromHeader("Bearer abc").?); + try t.expectEqualStrings("abc", tokenFromHeader("bearer abc ").?); + try t.expectEqual(null, tokenFromHeader(null)); + try t.expectEqual(null, tokenFromHeader("Bearer ")); + try t.expectEqual(null, tokenFromHeader("Basic abc")); + try t.expectEqual(null, tokenFromHeader("abc")); +} + +test isUuid { + const t = std.testing; + try t.expect(isUuid("0b9f6a3e-8f1c-4c55-9d2e-3a7b1c2d4e5f")); + try t.expect(isUuid("0B9F6A3E-8F1C-4C55-9D2E-3A7B1C2D4E5F")); + try t.expect(!isUuid("0b9f6a3e8f1c4c559d2e3a7b1c2d4e5f")); + try t.expect(!isUuid("0b9f6a3e-8f1c-4c55-9d2e-3a7b1c2d4e5g")); + try t.expect(!isUuid("../login/aaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); + try t.expect(!isUuid("")); +} diff --git a/event_registration/src/main.zig b/event_registration/src/main.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Io = std.Io; const repository = @import("repository"); const server = @import("server"); +const auth = @import("auth"); pub fn main(init: std.process.Init) !void { const io = init.io; @@ -11,7 +12,10 @@ pub fn main(init: std.process.Init) !void { // std.debug.print("db: {any}\n", .{db}); // defer db.deinit(); - var server_future = Io.async(io, server.start, .{ io, allocator }); + // Base URL of the Go auth service. + const auth_url = init.environ_map.get("SIGA_AUTH_URL") orelse auth.default_url; + + var server_future = Io.async(io, server.start, .{ io, allocator, auth_url }); // const event = try db.find(57); // std.debug.print("found event => id: '{}', name: '{s}'\n", .{event.id, event.name}); diff --git a/event_registration/src/server/server.zig b/event_registration/src/server/server.zig @@ -1,6 +1,7 @@ const std = @import("std"); const httpz = @import("httpz"); const repository = @import("repository"); +const auth = @import("auth"); pub const Server = @This(); @@ -13,11 +14,16 @@ const Response = struct { }; var db: repository.Repository = undefined; +var authenticator: auth.Auth = undefined; -pub fn start(io: std.Io, allocator: std.mem.Allocator) !void { +pub fn start(io: std.Io, allocator: std.mem.Allocator, auth_url: []const u8) !void { db = try repository.init(); defer db.deinit(); + authenticator = auth.init(io, allocator, auth_url); + defer authenticator.deinit(); + std.log.info("using auth service at {s}", .{authenticator.base_url}); + var server = try httpz.Server(void).init( io, allocator, @@ -41,7 +47,27 @@ fn sendError(res: *httpz.Response, status: u16, message: []const u8) !void { try res.json(.{ .@"error" = message }, .{}); } -fn handleListEvents(_: *httpz.Request, res: *httpz.Response) !void { +/// Answers the request with an error and returns false unless it carries a +/// valid session token. +fn requireAuth(req: *httpz.Request, res: *httpz.Response) !bool { + switch (authenticator.authenticate(req.header("authorization"))) { + .authenticated => return true, + .missing_token => { + res.header("WWW-Authenticate", "Bearer"); + try sendError(res, 401, "missing or malformed token"); + }, + .invalid_token => { + res.header("WWW-Authenticate", "Bearer"); + try sendError(res, 401, "invalid token"); + }, + .unavailable => try sendError(res, 503, "auth service unavailable"), + } + return false; +} + +fn handleListEvents(req: *httpz.Request, res: *httpz.Response) !void { + if (!try requireAuth(req, res)) return; + const events = db.findAll(res.arena) catch |err| { std.log.err("findAll failed: {t}", .{err}); return sendError(res, 500, "internal error"); @@ -52,6 +78,8 @@ fn handleListEvents(_: *httpz.Request, res: *httpz.Response) !void { } fn handleGetEvent(req: *httpz.Request, res: *httpz.Response) !void { + if (!try requireAuth(req, res)) return; + const raw_id = req.param("id") orelse return sendError(res, 400, "missing id"); const id = std.fmt.parseInt(i32, raw_id, 10) catch { return sendError(res, 400, "invalid id"); @@ -71,6 +99,8 @@ fn handleGetEvent(req: *httpz.Request, res: *httpz.Response) !void { } fn handlePostEvent(req: *httpz.Request, res: *httpz.Response) !void { + if (!try requireAuth(req, res)) return; + const maybe_request = req.json(PostRequest) catch { return sendError(res, 400, "invalid body"); };