siga

Sistema Interativo de GerĂȘncia de Atividades.
Log | Files | Refs | README | LICENSE

auth.zig (4295B)


      1 //! Client for the SIGA authentication service (`auth/`, written in Go).
      2 //!
      3 //! The auth service hands out session tokens (UUIDs) on `POST /login` and
      4 //! answers `GET /{uuid}` with 200 when the session exists, 401 when it does
      5 //! not and 400 when the token is malformed. Clients of this service send the
      6 //! token as `Authorization: Bearer <uuid>`.
      7 
      8 const std = @import("std");
      9 
     10 pub const Auth = @This();
     11 
     12 pub const default_url = "http://localhost:8080";
     13 
     14 /// Canonical textual UUID length: 8-4-4-4-12 hex digits.
     15 const uuid_len = 36;
     16 
     17 pub const Result = enum {
     18     authenticated,
     19     /// No `Authorization: Bearer` header, or the token is not a UUID.
     20     missing_token,
     21     /// The auth service does not know this session.
     22     invalid_token,
     23     /// The auth service could not be reached or gave an unexpected answer.
     24     unavailable,
     25 };
     26 
     27 client: std.http.Client,
     28 base_url: []const u8,
     29 
     30 /// `allocator` must be thread-safe: the client is shared by every worker.
     31 /// `base_url` must outlive the returned value and have no trailing slash.
     32 pub fn init(io: std.Io, allocator: std.mem.Allocator, base_url: []const u8) Auth {
     33     return .{
     34         .client = .{ .io = io, .allocator = allocator },
     35         .base_url = std.mem.trimEnd(u8, base_url, "/"),
     36     };
     37 }
     38 
     39 pub fn deinit(a: *Auth) void {
     40     a.client.deinit();
     41 }
     42 
     43 /// Checks the value of an `Authorization` header against the auth service.
     44 /// Safe to call from several threads at once.
     45 pub fn authenticate(a: *Auth, authorization: ?[]const u8) Result {
     46     const token = tokenFromHeader(authorization) orelse return .missing_token;
     47     return a.validate(token);
     48 }
     49 
     50 /// Asks the auth service whether `token` is an open session.
     51 pub fn validate(a: *Auth, token: []const u8) Result {
     52     // The token goes into the URL path, so only ever send a well-formed UUID.
     53     if (!isUuid(token)) return .missing_token;
     54 
     55     var url_buf: [512]u8 = undefined;
     56     const url = std.fmt.bufPrint(&url_buf, "{s}/{s}", .{ a.base_url, token }) catch {
     57         std.log.err("auth: base url too long: {s}", .{a.base_url});
     58         return .unavailable;
     59     };
     60 
     61     const result = a.client.fetch(.{
     62         .location = .{ .url = url },
     63         .method = .GET,
     64         .redirect_behavior = .unhandled,
     65     }) catch |err| {
     66         std.log.err("auth: request to {s} failed: {t}", .{ a.base_url, err });
     67         return .unavailable;
     68     };
     69 
     70     return switch (result.status) {
     71         .ok => .authenticated,
     72         .unauthorized, .bad_request => .invalid_token,
     73         else => |status| {
     74             std.log.err("auth: unexpected status {d}", .{@intFromEnum(status)});
     75             return .unavailable;
     76         },
     77     };
     78 }
     79 
     80 /// Extracts the token from an `Authorization: Bearer <token>` header value.
     81 pub fn tokenFromHeader(authorization: ?[]const u8) ?[]const u8 {
     82     const value = std.mem.trim(u8, authorization orelse return null, " \t");
     83     const scheme = "bearer ";
     84     if (value.len <= scheme.len) return null;
     85     if (!std.ascii.eqlIgnoreCase(value[0..scheme.len], scheme)) return null;
     86 
     87     const token = std.mem.trim(u8, value[scheme.len..], " \t");
     88     return if (token.len == 0) null else token;
     89 }
     90 
     91 /// Whether `s` is a UUID in canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` form.
     92 pub fn isUuid(s: []const u8) bool {
     93     if (s.len != uuid_len) return false;
     94     for (s, 0..) |c, i| switch (i) {
     95         8, 13, 18, 23 => if (c != '-') return false,
     96         else => if (!std.ascii.isHex(c)) return false,
     97     };
     98     return true;
     99 }
    100 
    101 test tokenFromHeader {
    102     const t = std.testing;
    103     try t.expectEqualStrings("abc", tokenFromHeader("Bearer abc").?);
    104     try t.expectEqualStrings("abc", tokenFromHeader("bearer   abc ").?);
    105     try t.expectEqual(null, tokenFromHeader(null));
    106     try t.expectEqual(null, tokenFromHeader("Bearer "));
    107     try t.expectEqual(null, tokenFromHeader("Basic abc"));
    108     try t.expectEqual(null, tokenFromHeader("abc"));
    109 }
    110 
    111 test isUuid {
    112     const t = std.testing;
    113     try t.expect(isUuid("0b9f6a3e-8f1c-4c55-9d2e-3a7b1c2d4e5f"));
    114     try t.expect(isUuid("0B9F6A3E-8F1C-4C55-9D2E-3A7B1C2D4E5F"));
    115     try t.expect(!isUuid("0b9f6a3e8f1c4c559d2e3a7b1c2d4e5f"));
    116     try t.expect(!isUuid("0b9f6a3e-8f1c-4c55-9d2e-3a7b1c2d4e5g"));
    117     try t.expect(!isUuid("../login/aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
    118     try t.expect(!isUuid(""));
    119 }