|
| 1 | +/// TurboDB — Authentication & Authorization |
| 2 | +/// |
| 3 | +/// API key authentication with HMAC-SHA256 verification. |
| 4 | +/// Keys are stored as BLAKE3 hashes — plaintext never persisted. |
| 5 | +/// |
| 6 | +/// Wire protocol: First frame after connect must be OP_AUTH with the API key. |
| 7 | +/// HTTP: X-Api-Key header on every request. |
| 8 | +/// |
| 9 | +/// No auth configured → open access (dev mode). |
| 10 | +const std = @import("std"); |
| 11 | +const crypto = @import("crypto.zig"); |
| 12 | +const Allocator = std.mem.Allocator; |
| 13 | + |
| 14 | +pub const MAX_KEYS = 64; |
| 15 | + |
| 16 | +/// Permission level for an API key. |
| 17 | +pub const Permission = enum(u8) { |
| 18 | + read_only = 0, |
| 19 | + read_write = 1, |
| 20 | + admin = 2, |
| 21 | +}; |
| 22 | + |
| 23 | +/// A registered API key (stored as hash, never plaintext). |
| 24 | +pub const KeyEntry = struct { |
| 25 | + hash: [32]u8, // BLAKE3 of the raw key |
| 26 | + name: [64]u8, |
| 27 | + name_len: u8, |
| 28 | + perm: Permission, |
| 29 | +}; |
| 30 | + |
| 31 | +/// Auth store. Thread-safe via RwLock. |
| 32 | +pub const AuthStore = struct { |
| 33 | + keys: [MAX_KEYS]KeyEntry = undefined, |
| 34 | + count: u32 = 0, |
| 35 | + enabled: bool = false, |
| 36 | + lock: std.Thread.RwLock = .{}, |
| 37 | + |
| 38 | + /// Add an API key. Returns the BLAKE3 hash for storage. |
| 39 | + pub fn addKey(self: *AuthStore, raw_key: []const u8, name: []const u8, perm: Permission) [32]u8 { |
| 40 | + self.lock.lock(); |
| 41 | + defer self.lock.unlock(); |
| 42 | + |
| 43 | + const hash = crypto.blake3(raw_key); |
| 44 | + if (self.count < MAX_KEYS) { |
| 45 | + var entry = KeyEntry{ |
| 46 | + .hash = hash, |
| 47 | + .name = undefined, |
| 48 | + .name_len = @intCast(@min(name.len, 64)), |
| 49 | + .perm = perm, |
| 50 | + }; |
| 51 | + @memcpy(entry.name[0..entry.name_len], name[0..entry.name_len]); |
| 52 | + self.keys[self.count] = entry; |
| 53 | + self.count += 1; |
| 54 | + self.enabled = true; |
| 55 | + } |
| 56 | + return hash; |
| 57 | + } |
| 58 | + |
| 59 | + /// Verify an API key. Returns the Permission if valid, null if rejected. |
| 60 | + pub fn verify(self: *AuthStore, raw_key: []const u8) ?Permission { |
| 61 | + if (!self.enabled) return .admin; // No auth → full access |
| 62 | + const hash = crypto.blake3(raw_key); |
| 63 | + |
| 64 | + self.lock.lockShared(); |
| 65 | + defer self.lock.unlockShared(); |
| 66 | + |
| 67 | + for (self.keys[0..self.count]) |*entry| { |
| 68 | + if (std.mem.eql(u8, &entry.hash, &hash)) return entry.perm; |
| 69 | + } |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + /// Check if auth is enabled. |
| 74 | + pub fn isEnabled(self: *AuthStore) bool { |
| 75 | + return self.enabled; |
| 76 | + } |
| 77 | + |
| 78 | + /// Extract API key from HTTP headers. |
| 79 | + pub fn extractHttpKey(request: []const u8) ?[]const u8 { |
| 80 | + const needle = "X-Api-Key: "; |
| 81 | + const pos = std.mem.indexOf(u8, request, needle) orelse return null; |
| 82 | + const start = pos + needle.len; |
| 83 | + const end = std.mem.indexOfScalarPos(u8, request, start, '\r') orelse |
| 84 | + std.mem.indexOfScalarPos(u8, request, start, '\n') orelse request.len; |
| 85 | + const key = request[start..end]; |
| 86 | + return if (key.len > 0) key else null; |
| 87 | + } |
| 88 | +}; |
| 89 | + |
| 90 | +// ── Wire protocol auth ────────────────────────────────────────────────────── |
| 91 | + |
| 92 | +pub const OP_AUTH: u8 = 0x10; |
| 93 | +pub const STATUS_UNAUTHORIZED: u8 = 0x03; |
| 94 | + |
| 95 | +// ── Tests ──────────────────────────────────────────────────────────────────── |
| 96 | + |
| 97 | +test "auth disabled returns admin" { |
| 98 | + var store = AuthStore{}; |
| 99 | + try std.testing.expectEqual(Permission.admin, store.verify("anything").?); |
| 100 | +} |
| 101 | + |
| 102 | +test "add and verify key" { |
| 103 | + var store = AuthStore{}; |
| 104 | + _ = store.addKey("my-secret-key", "test-key", .read_write); |
| 105 | + try std.testing.expectEqual(Permission.read_write, store.verify("my-secret-key").?); |
| 106 | + try std.testing.expectEqual(@as(?Permission, null), store.verify("wrong-key")); |
| 107 | +} |
| 108 | + |
| 109 | +test "read-only key cannot write" { |
| 110 | + var store = AuthStore{}; |
| 111 | + _ = store.addKey("reader", "reader", .read_only); |
| 112 | + const perm = store.verify("reader").?; |
| 113 | + try std.testing.expect(perm == .read_only); |
| 114 | +} |
| 115 | + |
| 116 | +test "extract HTTP key" { |
| 117 | + const req = "GET /db/users HTTP/1.1\r\nX-Api-Key: abc123\r\nHost: localhost\r\n\r\n"; |
| 118 | + const key = AuthStore.extractHttpKey(req).?; |
| 119 | + try std.testing.expectEqualStrings("abc123", key); |
| 120 | +} |
| 121 | + |
| 122 | +test "extract HTTP key missing" { |
| 123 | + const req = "GET /db/users HTTP/1.1\r\nHost: localhost\r\n\r\n"; |
| 124 | + try std.testing.expectEqual(@as(?[]const u8, null), AuthStore.extractHttpKey(req)); |
| 125 | +} |
0 commit comments