const std = @import("std"); const zat = @import("zat"); const hegel = @import("hegel"); const sim = @import("sim_io.zig"); pub const std_options: std.Options = .{ .log_level = .err }; const Rule = enum { resource, refresh }; var tally: hegel.Tally(Rule) = .{}; const Reply = struct { kind: enum { ok, failed, body_challenge, header_challenge, reset }, nonce: ?[]const u8, }; const nonces = [_][]const u8{ "n-1", "n-2", "n-3" }; const resource_url = "http://pds.sim/xrpc/com.example.get?actor=alice#frag"; const token_url = "http://auth.sim/oauth/token"; const Seen = struct { htm: []const u8, htu: []const u8, nonce: ?[]const u8, ath: ?[]const u8, iat: i64, jti: []const u8, authorization: ?[]const u8 }; const World = struct { a: std.mem.Allocator, replies: []const Reply = &.{}, served: usize = 0, seen: std.ArrayList(Seen) = .empty, jtis: std.StringHashMapUnmanaged(void) = .empty, /// a jti seen before, other than a resend of the request whose /// connection the server just reset replayed_jti: bool = false, resent_after_reset: u64 = 0, malformed_proof: bool = false, fn handle(raw: *anyopaque, request: sim.Request) sim.Response { const self: *World = @ptrCast(@alignCast(raw)); self.record(request) catch { self.malformed_proof = true; }; if (self.served >= self.replies.len) return .{ .status = 599 }; const reply = self.replies[self.served]; self.served += 1; const nonce_header = if (reply.nonce) |nonce| std.fmt.allocPrint(self.a, "DPoP-Nonce: {s}\r\n", .{nonce}) catch "" else ""; return switch (reply.kind) { .ok => .{ .headers = nonce_header, .body = if (std.mem.eql(u8, request.host, "auth.sim")) "{\"access_token\":\"at-2\",\"refresh_token\":\"rt-2\",\"scope\":\"atproto transition:generic\",\"sub\":\"did:plc:abcdefghijklmnopqrstuvwx\",\"token_type\":\"DPoP\"}" else "{\"ok\":true}" }, .failed => .{ .status = 500, .headers = nonce_header, .body = "{\"error\":\"InternalServerError\"}" }, .body_challenge => .{ .status = 400, .headers = nonce_header, .body = "{\"error\":\"use_dpop_nonce\"}" }, .header_challenge => .{ .status = 401, .headers = std.fmt.allocPrint(self.a, "{s}WWW-Authenticate: DPoP error=\"use_dpop_nonce\"\r\n", .{nonce_header}) catch "", .body = "{}", }, .reset => .{ .fault = .reset_before_response }, }; } fn record(self: *World, request: sim.Request) !void { const proof = request.header("dpop") orelse return error.MissingProof; var parts = std.mem.splitScalar(u8, proof, '.'); _ = parts.next(); const payload = try zat.jwt.base64UrlDecode(self.a, parts.next() orelse return error.MalformedProof); const parsed = try std.json.parseFromSlice(std.json.Value, self.a, payload, .{}); const object = parsed.value.object; const jti = object.get("jti").?.string; if (self.jtis.contains(jti)) { const resent = self.served > 0 and self.replies[self.served - 1].kind == .reset and self.seen.items.len > 0 and std.mem.eql(u8, self.seen.items[self.seen.items.len - 1].jti, jti); if (resent) self.resent_after_reset += 1 else self.replayed_jti = true; } try self.jtis.put(self.a, jti, {}); try self.seen.append(self.a, .{ .htm = object.get("htm").?.string, .htu = object.get("htu").?.string, .nonce = if (object.get("nonce")) |v| v.string else null, .ath = if (object.get("ath")) |v| v.string else null, .iat = object.get("iat").?.integer, .jti = jti, .authorization = if (request.header("authorization")) |v| try self.a.dupe(u8, v) else null, }); } }; fn drawReply(case: *hegel.TestCase) !Reply { const Kind = @FieldType(Reply, "kind"); const kinds = [_]Kind{ .ok, .ok, .failed, .body_challenge, .body_challenge, .header_challenge, .header_challenge, .reset }; const kind = kinds[try case.index(kinds.len)]; const with_nonce = switch (kind) { .body_challenge, .header_challenge => try case.int(u8, 0, 5) != 0, .reset => false, else => try case.boolean(), }; return .{ .kind = kind, .nonce = if (with_nonce) nonces[try case.index(nonces.len)] else null }; } const Expected = union(enum) { status: u16, missing_nonce, exhausted, transport }; fn property(_: void, case: *hegel.TestCase) !void { var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena.deinit(); const a = arena.allocator(); var debug: std.heap.DebugAllocator(.{}) = .init; const gpa = debug.allocator(); var io_sim = sim.SimIo.init(try case.int(u32, 0, std.math.maxInt(u32)), try case.int(i64, 1_700_000_000, 1_900_000_000)); var world: World = .{ .a = a }; var network = sim.Network.init(a, &world, World.handle); network.max_read = try case.int(usize, 1, 512); try network.addHost("pds.sim", .{ 34, 4, 0, 1 }); try network.addHost("auth.sim", .{ 34, 4, 0, 2 }); io_sim.network = &network; var secret: [32]u8 = @splat(0); secret[31] = 7; const dpop_key = try zat.Keypair.fromSecretKey(.p256, secret); secret[31] = 9; const client_key = try zat.Keypair.fromSecretKey(.p256, secret); var current_nonce: ?[]const u8 = if (try case.boolean()) nonces[0] else null; { var transport = zat.HttpTransport.init(io_sim.io(), gpa); defer transport.deinit(); transport.keep_alive = try case.boolean(); sim.withoutGuards(&transport); var machine = try case.machine(Rule, &.{ 3, 2 }, 8); defer machine.deinit(); tally.case(); while (try machine.next()) |rule| { tally.step(rule); const replies = try a.alloc(Reply, 6); for (replies) |*reply| reply.* = try drawReply(case); world.replies = replies; world.served = 0; world.seen.clearRetainingCapacity(); const method: std.http.Method = if (rule == .refresh or try case.boolean()) .POST else .GET; case.note("{s} {s} nonce={?s} replies={any}", .{ @tagName(rule), @tagName(method), current_nonce, replies }); var expected_nonces: std.ArrayList(?[]const u8) = .empty; var nonce = current_nonce; var returned: ?[]const u8 = null; var reply_index: usize = 0; const expected: Expected = outer: for (0..2) |iteration| { var replays: usize = 0; while (true) { try expected_nonces.append(a, nonce); const reply = replies[reply_index]; reply_index += 1; switch (reply.kind) { .reset => { if (method == .GET and replays + 1 < transport.dead_connection_attempts) { replays += 1; continue; } break :outer .transport; }, .body_challenge, .header_challenge => { const fresh = reply.nonce orelse break :outer .missing_nonce; if (iteration == 1) break :outer .exhausted; nonce = fresh; break; }, .ok, .failed => { returned = reply.nonce orelse nonce; break :outer .{ .status = if (reply.kind == .ok) 200 else 500 }; }, } } } else unreachable; const now = @divFloor(io_sim.now_ns, std.time.ns_per_s); var actual: Expected = .transport; var actual_nonce: ?[]const u8 = null; switch (rule) { .resource => { if (zat.oauth.dpopRequest(gpa, io_sim.io(), &transport, .{ .url = resource_url, .method = method, .access_token = "at-1", .dpop_keypair = &dpop_key, .dpop_nonce = current_nonce, .payload = if (method == .POST) "{}" else null, })) |value| { var response = value; defer response.deinit(gpa); actual = .{ .status = @backingInt(response.status) }; actual_nonce = if (response.dpop_nonce) |n| try a.dupe(u8, n) else null; } else |err| actual = switch (err) { error.MissingDpopNonce => .missing_nonce, error.DpopNonceRetryExhausted => .exhausted, error.OutOfMemory => return err, else => .transport, }; }, .refresh => { if (zat.oauth.refreshAccessToken(gpa, io_sim.io(), &transport, .{ .token_url = token_url, .authserver_issuer = "http://auth.sim", .client_id = "http://client.sim/client-metadata.json", .refresh_token = "rt-1", .client_keypair = &client_key, .dpop_keypair = &dpop_key, .dpop_nonce = current_nonce, })) |value| { var token = value; defer token.deinit(gpa); actual = .{ .status = 200 }; actual_nonce = if (token.dpop_nonce) |n| try a.dupe(u8, n) else null; if (!std.mem.eql(u8, token.access_token, "at-2")) return case.fail("refreshed token differs from server"); } else |err| actual = switch (err) { error.MissingDpopNonce => .missing_nonce, error.DpopNonceRetryExhausted => .exhausted, error.TokenRequestFailed => .{ .status = 500 }, error.OutOfMemory => return err, else => .transport, }; }, } case.note("expected {any} nonce {?s}; actual {any} nonce {?s}", .{ expected, returned, actual, actual_nonce }); if (world.malformed_proof) return case.fail("request lacks a well-formed DPoP proof"); if (world.replayed_jti) return case.fail("a DPoP proof jti reached the server twice"); if (world.resent_after_reset > 0) { case.event("known: zttp replays a DPoP proof after a dead connection"); world.resent_after_reset = 0; } if (!std.meta.eql(expected, actual)) return case.fail("DPoP nonce flow outcome differs from model"); if (world.seen.items.len != expected_nonces.items.len) return case.fail("server saw a different number of DPoP requests"); const htu = if (rule == .resource) "http://pds.sim/xrpc/com.example.get" else token_url; for (world.seen.items, expected_nonces.items) |seen, nonce_expected| { if (!std.mem.eql(u8, seen.htm, @tagName(method))) return case.fail("DPoP htm differs from request method"); if (!std.mem.eql(u8, seen.htu, htu)) return case.fail("DPoP htu keeps query or fragment or differs from target"); if (seen.iat != now) return case.fail("DPoP iat differs from virtual clock"); const same_nonce = if (seen.nonce) |got| if (nonce_expected) |want| std.mem.eql(u8, got, want) else false else nonce_expected == null; if (!same_nonce) return case.fail("DPoP proof carries a stale or missing nonce"); if (rule == .resource) { if (seen.ath == null) return case.fail("resource request proof lacks ath"); if (!std.mem.eql(u8, seen.authorization orelse "", "DPoP at-1")) return case.fail("resource request lacks DPoP authorization"); } else if (seen.ath != null or seen.authorization != null) return case.fail("token request proof carries an access token"); } const has_result = actual == .status and (rule == .resource or actual.status == 200); if (has_result) { const same = if (actual_nonce) |got| if (returned) |want| std.mem.eql(u8, got, want) else false else returned == null; if (!same) return case.fail("returned DPoP nonce is not the latest the server sent"); current_nonce = returned; } switch (expected) { .status => case.event("DPoP request completed"), .missing_nonce => case.event("nonce challenge without a nonce refused"), .exhausted => case.event("second nonce challenge exhausted the retry"), .transport => case.event("DPoP request failed in transport"), } if (expected_nonces.items.len > 1) case.event("DPoP request retried with a fresh nonce"); } } if (debug.deinit() == .leak) return case.fail("OAuth client leaked memory"); tally.finish(network.requests); } pub fn main() !void { defer tally.print(); try hegel.run(.{ .key = "oauth" }, {}, property); }