const std = @import("std");
const request_context = @import("../internal/request_context.zig");
const clock = @import("../core/clock.zig");
const config = @import("../core/config.zig");
const auth = @import("../auth/tokens.zig");
const dpop = @import("../internal/dpop.zig");
const log = @import("../core/log.zig");
const store = @import("../storage/store.zig");
const httpz = @import("httpz");
const http = std.http;
pub const Request = httpz.Request;
pub const Response = httpz.Response;
/// The exact bodies of a page's inline `");
try std.testing.expectEqual(2, code.scripts.len);
try std.testing.expectEqual(1, code.styles.len);
const csp = htmlSecurityHeaders(code)[0].value;
try std.testing.expect(std.mem.indexOf(u8, csp, "script-src 'sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=';") != null);
try std.testing.expect(std.mem.indexOf(u8, csp, "unsafe") == null);
try std.testing.expect(std.mem.indexOf(u8, htmlSecurityHeaders(.{})[0].value, "script-src 'none'; style-src 'none';") != null);
const dynamic = try htmlSecurityHeadersWithStyle(std.testing.allocator, .{ .styles = code.styles }, "");
defer std.testing.allocator.free(dynamic[0].value);
try std.testing.expect(std.mem.indexOf(u8, dynamic[0].value, "style-src 'sha256-" ++ comptime hashOf("p{}") ++ "' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='; img-src") != null);
}
test "decodes query params" {
var buf: [64]u8 = undefined;
try std.testing.expectEqualStrings("did:plc:service", queryParam("/xrpc/foo?aud=did%3Aplc%3Aservice", "aud", &buf).?);
}
test "a DPoP-bound token sent without a nonce gets the reference's use_dpop_nonce challenge" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try store.init(std.Options.debug_io, ":memory:");
defer store.close();
const account = try store.createAccount(a, "nonce.test", "nonce@test.com", "password", "did:plc:noncechallenge", true);
const token = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, "https://client.example/client-metadata.json", "atproto transition:generic", token, "refresh", now() + 600, now() + 6000, "test-jkt", "password");
var ht = httpz.testing.init(.{});
defer ht.deinit();
bindResponse(ht.res);
defer unbindResponse();
ht.header("authorization", try std.fmt.allocPrint(a, "DPoP {s}", .{token}));
// No DPoP proof at all, as atproto-oauth's DpopRetry sends first: a nonce challenge, not InvalidToken,
// and uploadBlob must not mistake it for a service-auth token.
try std.testing.expectError(error.UseDpopNonce, requireBearerAccess(ht.req, a));
try std.testing.expectError(error.HandledResponse, bearerErrorResponse(ht.req, error.UseDpopNonce));
try ht.expectStatus(401);
try ht.expectHeader("www-authenticate", "DPoP error=\"use_dpop_nonce\", error_description=\"Resource server requires nonce in DPoP proof\"");
try std.testing.expect(std.mem.startsWith(u8, ht.res.body, "{\"error\":\"use_dpop_nonce\","));
}
const OAuthFailureCase = struct {
authorization: []const u8,
dpop_proof: ?[]const u8 = null,
body_error: []const u8,
challenge: ?[]const u8,
};
fn expectBearerFailure(a: std.mem.Allocator, case: OAuthFailureCase) !void {
var ht = httpz.testing.init(.{});
defer ht.deinit();
bindResponse(ht.res);
defer unbindResponse();
ht.header("authorization", case.authorization);
if (case.dpop_proof) |proof| ht.header("dpop", proof);
const err = if (requireBearerAccess(ht.req, a)) |_| return error.TestUnexpectedResult else |err| err;
try std.testing.expectError(error.HandledResponse, bearerErrorResponse(ht.req, err));
try ht.expectStatus(401);
try ht.expectHeader("www-authenticate", case.challenge);
const prefix = try std.fmt.allocPrint(a, "{{\"error\":\"{s}\",", .{case.body_error});
if (!std.mem.startsWith(u8, ht.res.body, prefix)) {
std.debug.print("{s}: body {s}\n", .{ case.authorization[0..@min(case.authorization.len, 24)], ht.res.body });
return error.TestUnexpectedResult;
}
}
test "every DPoP-scheme token failure answers with the reference's OAuth error code" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try store.init(std.Options.debug_io, ":memory:");
defer store.close();
const account = try store.createAccount(a, "oauthfail.test", "oauthfail@test.com", "password", "did:plc:oauthfailures", true);
const client = "https://client.example/client-metadata.json";
const bound = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, client, "atproto", bound, "refresh-bound", now() + 600, now() + 6000, "test-jkt", "password");
const revoked = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, client, "atproto", revoked, "refresh-revoked", now() + 600, now() + 6000, "test-jkt", "password");
try store.revokeOAuthToken(revoked);
const other_key = try auth.createDpopSessionJwt(a, "access", account, "other-jkt");
try store.putOAuthToken(account.did, client, "atproto", other_key, "refresh-other", now() + 600, now() + 6000, "test-jkt", "password");
const unbound = try auth.createSessionJwt(a, "access", account);
try store.putOAuthToken(account.did, client, "atproto", unbound, "refresh-unbound", now() + 600, now() + 6000, null, "password");
const no_row = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
const invalid_token = "DPoP error=\"invalid_token\", error_description=\"Invalid token\"";
for ([_]OAuthFailureCase{
.{ .authorization = "DPoP not-a-jwt", .body_error = "invalid_token", .challenge = "DPoP error=\"invalid_token\", error_description=\"Token is invalid\"" },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{revoked}), .body_error = "invalid_token", .challenge = "DPoP error=\"invalid_token\", error_description=\"Token has been revoked\"" },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{other_key}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{unbound}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{no_row}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{bound}), .dpop_proof = "not.a.proof", .body_error = "invalid_dpop_proof", .challenge = "DPoP error=\"invalid_dpop_proof\", error_description=\"Invalid DPoP proof\"" },
// The Bearer scheme also carries password sessions and service auth, which keep their XRPC names.
.{ .authorization = "Bearer not-a-jwt", .body_error = "InvalidToken", .challenge = "Bearer error=\"invalid_token\", error_description=\"Token is invalid\"" },
}) |case| try expectBearerFailure(a, case);
}
test "formats OAuth invalid token challenges" {
var buf: [160]u8 = undefined;
try std.testing.expectEqualStrings(
"Bearer error=\"invalid_token\", error_description=\"Token has expired\"",
try formatInvalidTokenChallenge(&buf, .bearer, "Token has expired"),
);
try std.testing.expectEqualStrings(
"DPoP error=\"invalid_token\", error_description=\"Token has been revoked\"",
try formatInvalidTokenChallenge(&buf, .dpop, "Token has been revoked"),
);
}
test "collects every value of a repeated query parameter" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const values = try queryParamValues(arena.allocator(), "/x?did=a&cids=b%3Ac&other=1&cids=d", "cids");
try std.testing.expectEqual(@as(usize, 2), values.len);
try std.testing.expectEqualStrings("b:c", values[0]);
try std.testing.expectEqualStrings("d", values[1]);
try std.testing.expectEqual(@as(usize, 0), (try queryParamValues(arena.allocator(), "/x", "cids")).len);
}
test "apps are named by the host of their client_id" {
try std.testing.expectEqualStrings("bsky.app", appLabel("https://bsky.app/oauth-client-metadata.json"));
try std.testing.expectEqualStrings("stream.place", appLabel("https://stream.place/oauth/downstream/client-metadata.json"));
try std.testing.expectEqualStrings("an app on a device", appLabel("http://localhost?redirect_uri=x"));
try std.testing.expectEqualStrings("did:web:example.com", appLabel("did:web:example.com"));
}
test "legacy sessions are named by Origin host, then User-Agent product" {
try std.testing.expectEqualStrings("bsky.app", clientHost("https://bsky.app").?);
try std.testing.expectEqualStrings("deck.blue", clientHost("https://deck.blue/").?);
try std.testing.expectEqualStrings("an app on a device", clientHost("http://localhost:19006").?);
try std.testing.expect(clientHost("null") == null);
try std.testing.expectEqualStrings("Bluesky", productToken("Bluesky/1.98.0 CFNetwork/1568 Darwin/24.0.0").?);
try std.testing.expectEqualStrings("okhttp", productToken("okhttp/4.12.0").?);
try std.testing.expect(productToken("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)") == null);
try std.testing.expect(productToken("