~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
329 lines · 12.5 KB Raw History
const std = @import("std");
const clock = @import("../core/clock.zig");
const config = @import("../core/config.zig");
const http_api = @import("../http/api.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

const ProofMaxAgeSecs: i64 = 300;
const NonceRotationSecs: i64 = 60;

pub const Error = error{
    MissingProof,
    InvalidProof,
    UseDpopNonce,
    Replay,
    KeyBindingMismatch,
} || std.mem.Allocator.Error;

pub const Proof = struct {
    jkt: []const u8,
    jti: []const u8,
};

pub fn nextNonce(allocator: std.mem.Allocator) ![]u8 {
    return nonceForCounter(allocator, nonceCounter(now()) + 1);
}

pub fn attachNonce(allocator: std.mem.Allocator) !void {
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    try http_api.addResponseHeader("dpop-nonce", nonce);
}

/// Sets the challenge headers; the caller answers with `bearerErrorResponse(error.UseDpopNonce)`.
pub fn challengeResource(allocator: std.mem.Allocator) !void {
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    try http_api.addResponseHeader("dpop-nonce", nonce);
    try http_api.addResponseHeader("www-authenticate", "DPoP error=\"use_dpop_nonce\", error_description=\"Resource server requires nonce in DPoP proof\"");
}

pub fn challengeAuthorizationServer(request: *http_api.Request, allocator: std.mem.Allocator) !void {
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    try http_api.addResponseHeader("dpop-nonce", nonce);
    const body = try allocator.dupe(u8, "{\"error\":\"use_dpop_nonce\",\"error_description\":\"Authorization server requires nonce in DPoP proof\"}");
    try http_api.json(request, .bad_request, body);
}

pub fn verifyRequest(
    allocator: std.mem.Allocator,
    request: *const http_api.Request,
    access_token: ?[]const u8,
    expected_jkt: ?[]const u8,
) Error!Proof {
    return verifyRequestWithPolicy(allocator, request, access_token, expected_jkt, true, ProofMaxAgeSecs, ProofMaxAgeSecs, false);
}

fn verifyRequestWithPolicy(
    allocator: std.mem.Allocator,
    request: *const http_api.Request,
    access_token: ?[]const u8,
    expected_jkt: ?[]const u8,
    require_nonce: bool,
    max_age_secs: i64,
    future_skew_secs: i64,
    require_es256: bool,
) Error!Proof {
    const dpop_header = http_api.headerValue(request, "dpop") orelse return error.MissingProof;
    const htu = try htuForRequest(allocator, request);
    defer allocator.free(htu);
    return verifyProof(allocator, dpop_header, methodName(request.method), htu, access_token, expected_jkt, require_nonce, max_age_secs, future_skew_secs, require_es256);
}

fn verifyProof(
    allocator: std.mem.Allocator,
    proof: []const u8,
    method: []const u8,
    expected_htu: []const u8,
    access_token: ?[]const u8,
    expected_jkt: ?[]const u8,
    require_nonce: bool,
    max_age_secs: i64,
    future_skew_secs: i64,
    require_es256: bool,
) Error!Proof {
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const ts = now();
    var nonce_bufs: [3][64]u8 = undefined;
    var nonces: [3][]const u8 = undefined;
    for (&nonces, &nonce_bufs, 0..) |*nonce, *buf, i| {
        var stream = std.Io.Writer.fixed(buf);
        writeNonceForCounter(&stream, nonceCounter(ts) - 1 + @as(i64, @intCast(i))) catch return error.InvalidProof;
        nonce.* = stream.buffered();
    }
    const verified = zat.oauth.verifyDpopProof(arena.allocator(), proof, .{
        .htm = method,
        .htu = expected_htu,
        .now = ts,
        .max_age = max_age_secs,
        .max_future_skew = future_skew_secs,
        .nonces = if (require_nonce) &nonces else null,
        .access_token = access_token,
        .jkt = expected_jkt,
        .algorithms = if (require_es256) &.{.ES256} else &.{ .ES256, .ES256K },
    }) catch |err| return switch (err) {
        error.OutOfMemory => error.OutOfMemory,
        error.InvalidDpopProof => error.InvalidProof,
        error.UseDpopNonce => error.UseDpopNonce,
        error.DpopKeyMismatch => error.KeyBindingMismatch,
    };
    const expires_at = @max(verified.iat + max_age_secs, ts + max_age_secs);
    if (!(store.recordDpopJti(verified.jti, expires_at) catch return error.InvalidProof)) return error.Replay;

    const jkt = try allocator.dupe(u8, &verified.jkt);
    errdefer allocator.free(jkt);
    return .{
        .jkt = jkt,
        .jti = try allocator.dupe(u8, verified.jti),
    };
}

fn htuForRequest(allocator: std.mem.Allocator, request: *const http_api.Request) ![]u8 {
    const path = stripQueryAndFragment(request.url.raw);
    return std.fmt.allocPrint(allocator, "{s}{s}", .{ config.publicUrl(), path });
}

fn nonceForCounter(allocator: std.mem.Allocator, counter: i64) ![]u8 {
    var buf: [64]u8 = undefined;
    var stream = std.Io.Writer.fixed(&buf);
    try writeNonceForCounter(&stream, counter);
    return allocator.dupe(u8, stream.buffered());
}

fn writeNonceForCounter(writer: *std.Io.Writer, counter: i64) !void {
    var counter_bytes: [8]u8 = undefined;
    std.mem.writeInt(i64, &counter_bytes, counter, .big);
    var mac: [std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8 = undefined;
    std.crypto.auth.hmac.sha2.HmacSha256.create(&mac, &counter_bytes, config.dpopSecret());
    const encoded = try zat.jwt.base64UrlEncode(std.heap.page_allocator, &mac);
    defer std.heap.page_allocator.free(encoded);
    try writer.writeAll(encoded);
}

fn nonceCounter(ts: i64) i64 {
    return @divFloor(ts, NonceRotationSecs);
}

fn stripQueryAndFragment(value: []const u8) []const u8 {
    const end = std.mem.indexOfAny(u8, value, "?#") orelse value.len;
    return value[0..end];
}

fn methodName(method: anytype) []const u8 {
    return switch (method) {
        .GET => "GET",
        .HEAD => "HEAD",
        .POST => "POST",
        .PUT => "PUT",
        .PATCH => "PATCH",
        .DELETE => "DELETE",
        .OPTIONS => "OPTIONS",
        else => "GET",
    };
}

fn now() i64 {
    return clock.nowSeconds();
}

test "validates DPoP proof and rejects replay" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();

    const keypair = try zat.Keypair.fromSecretKey(.p256, .{
        0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
        0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
        0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
        0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
    });
    const access_token = "access-token";
    const ath = try zat.oauth.accessTokenHash(allocator, access_token);
    defer allocator.free(ath);
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    const proof = try zat.oauth.createDpopProof(
        allocator,
        std.Options.debug_io,
        &keypair,
        "GET",
        "https://pds.example/xrpc/com.atproto.repo.getRecord?repo=x",
        nonce,
        ath,
    );
    defer allocator.free(proof);
    const expected_jkt = try keypair.jwkThumbprint(allocator);
    defer allocator.free(expected_jkt);

    const verified = try verifyProof(allocator, proof, "GET", "https://pds.example/xrpc/com.atproto.repo.getRecord", access_token, expected_jkt, true, ProofMaxAgeSecs, ProofMaxAgeSecs, false);
    defer allocator.free(verified.jkt);
    defer allocator.free(verified.jti);
    try std.testing.expectEqualStrings(expected_jkt, verified.jkt);
    try std.testing.expectError(error.Replay, verifyProof(allocator, proof, "GET", "https://pds.example/xrpc/com.atproto.repo.getRecord", access_token, expected_jkt, true, ProofMaxAgeSecs, ProofMaxAgeSecs, false));
}

test "rejects DPoP proof with wrong token binding" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();

    const keypair = try zat.Keypair.fromSecretKey(.p256, .{
        0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
        0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
        0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
        0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60,
    });
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    const ath = try zat.oauth.accessTokenHash(allocator, "access-token-a");
    defer allocator.free(ath);
    const proof = try zat.oauth.createDpopProof(
        allocator,
        std.Options.debug_io,
        &keypair,
        "POST",
        "https://pds.example/xrpc/com.atproto.repo.createRecord",
        nonce,
        ath,
    );
    defer allocator.free(proof);
    const expected_jkt = try keypair.jwkThumbprint(allocator);
    defer allocator.free(expected_jkt);

    try std.testing.expectError(error.InvalidProof, verifyProof(allocator, proof, "POST", "https://pds.example/xrpc/com.atproto.repo.createRecord", "access-token-b", expected_jkt, true, ProofMaxAgeSecs, ProofMaxAgeSecs, false));
}

test "rejects DPoP proof with mismatched JKT" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();

    const keypair = try zat.Keypair.fromSecretKey(.p256, .{
        0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
        0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
        0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
        0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80,
    });
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    const proof = try zat.oauth.createDpopProof(
        allocator,
        std.Options.debug_io,
        &keypair,
        "POST",
        "https://pds.example/oauth/token",
        nonce,
        null,
    );
    defer allocator.free(proof);

    try std.testing.expectError(error.KeyBindingMismatch, verifyProof(allocator, proof, "POST", "https://pds.example/oauth/token", null, "not-the-key", true, ProofMaxAgeSecs, ProofMaxAgeSecs, false));
}

test "space DPoP proof does not require an OAuth nonce" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x31));
    const proof = try zat.oauth.createDpopProof(
        allocator,
        std.Options.debug_io,
        &keypair,
        "POST",
        "https://space.example/xrpc/com.atproto.space.authorizeSpaceSync",
        "",
        null,
    );
    defer allocator.free(proof);
    const expected_jkt = try keypair.jwkThumbprint(allocator);
    defer allocator.free(expected_jkt);
    const verified = try verifyProof(
        allocator,
        proof,
        "POST",
        "https://space.example/xrpc/com.atproto.space.authorizeSpaceSync",
        null,
        null,
        false,
        60,
        5,
        true,
    );
    defer allocator.free(verified.jkt);
    defer allocator.free(verified.jti);
    try std.testing.expectEqualStrings(expected_jkt, verified.jkt);
}

test "rejects a DPoP proof whose jwk is not a point on the curve" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // the signer's x with a y of the same parity that is off the curve
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x21));
    const header = "{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M\",\"y\":\"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eM\"}}";
    const url = "https://pds.example/oauth/token";
    const payload = try std.fmt.allocPrint(a, "{{\"jti\":\"off-curve\",\"htm\":\"POST\",\"htu\":\"{s}\",\"iat\":{d}}}", .{ url, now() });
    const proof = try zat.oauth.createJwt(a, header, payload, &keypair);
    try std.testing.expectError(error.InvalidProof, verifyProof(allocator, proof, "POST", url, null, null, false, ProofMaxAgeSecs, ProofMaxAgeSecs, false));
}

test "DPoP htu compares in RFC 9449 normal form" {
    const allocator = std.testing.allocator;
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x51));
    const nonce = try nextNonce(allocator);
    defer allocator.free(nonce);
    const proof = try zat.oauth.createDpopProof(allocator, std.Options.debug_io, &keypair, "POST", "https://PDS.Example:443/oauth/token?x=1", nonce, null);
    defer allocator.free(proof);
    const verified = try verifyProof(allocator, proof, "POST", "https://pds.example/oauth/token", null, null, true, ProofMaxAgeSecs, ProofMaxAgeSecs, false);
    allocator.free(verified.jkt);
    allocator.free(verified.jti);
}