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

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
321 lines · 17.3 KB Raw History
//! Server-side DPoP proof verification (RFC 9449). Replay tracking of `jti`
//! and issuing nonces stay with the server; this checks one proof against one
//! request.

const std = @import("std");
const Allocator = std.mem.Allocator;
const jwt = @import("../crypto/jwt.zig");
const jwk = @import("../crypto/jwk.zig");
const primitives = @import("primitives.zig");

pub const Error = error{
    InvalidDpopProof,
    /// the proof has no nonce, or one the server no longer accepts; answer
    /// with `use_dpop_nonce` and a fresh `DPoP-Nonce`
    UseDpopNonce,
    /// the proof is signed by a key other than the one the token is bound to
    DpopKeyMismatch,
    OutOfMemory,
};

pub const VerifyOptions = struct {
    /// the request's method
    htm: []const u8,
    /// the request's URL as the server sees it; compared after `normalizeHtu`
    htu: []const u8,
    /// unix seconds
    now: i64,
    /// how far `iat` may be behind `now`, in seconds
    max_age: i64 = 300,
    /// how far `iat` may be ahead of `now`, in seconds
    max_future_skew: i64 = 300,
    /// the nonces the server currently accepts; null when it requires none
    nonces: ?[]const []const u8 = null,
    /// the access token the proof must bind through `ath`; without one, a
    /// proof carrying `ath` is rejected
    access_token: ?[]const u8 = null,
    /// the thumbprint a DPoP-bound token names in `cnf.jkt`
    jkt: ?[]const u8 = null,
    algorithms: []const jwt.Algorithm = &.{ .ES256, .ES256K },
};

pub const Proof = struct {
    /// RFC 7638 thumbprint of the proof's `jwk` as sent, for binding a new token
    jkt: jwk.Thumbprint,
    /// for the caller's replay store
    jti: []const u8,
    iat: i64,
    nonce: ?[]const u8,
    key: jwk.PublicKey,
};

/// verify a `DPoP` header value: typ `dpop+jwt`, a public `jwk` in the header
/// whose signature over the proof verifies (JOSE, so high-S is accepted),
/// `htm` and `htu` naming this request, `iat` inside the window, a non-empty
/// `jti`, and the nonce, `ath` and key binding the options ask for.
/// Allocations belong to `arena`; `jti` and `nonce` point into it.
pub fn verifyProof(arena: Allocator, proof: []const u8, options: VerifyOptions) Error!Proof {
    const parts = jwt.decodeLeaky(arena, proof) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidJwt => return error.InvalidDpopProof,
    };
    if (!std.mem.eql(u8, parts.headerString("typ") orelse return error.InvalidDpopProof, "dpop+jwt")) return error.InvalidDpopProof;
    const alg = parts.algorithm() orelse return error.InvalidDpopProof;
    if (std.mem.indexOfScalar(jwt.Algorithm, options.algorithms, alg) == null) return error.InvalidDpopProof;
    const header_jwk = parts.header.object.get("jwk") orelse return error.InvalidDpopProof;
    const key = jwk.parsePublicKey(header_jwk) catch return error.InvalidDpopProof;
    key.verifyJose(alg, parts.signing_input, parts.signature) catch return error.InvalidDpopProof;

    const jti = parts.claimString("jti") orelse return error.InvalidDpopProof;
    if (jti.len == 0) return error.InvalidDpopProof;
    if (!std.mem.eql(u8, parts.claimString("htm") orelse return error.InvalidDpopProof, options.htm)) return error.InvalidDpopProof;
    const claimed_htu = normalizeHtu(arena, parts.claimString("htu") orelse return error.InvalidDpopProof) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidHtu => return error.InvalidDpopProof,
    };
    const expected_htu = normalizeHtu(arena, options.htu) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidHtu => return error.InvalidDpopProof,
    };
    if (!std.mem.eql(u8, claimed_htu, expected_htu)) return error.InvalidDpopProof;
    const iat = parts.claimNumericDate("iat") orelse return error.InvalidDpopProof;
    if (iat < options.now - options.max_age or iat > options.now + options.max_future_skew) return error.InvalidDpopProof;

    const ath = parts.claimString("ath");
    if (options.access_token) |token| {
        const expected = try primitives.accessTokenHash(arena, token);
        if (!std.mem.eql(u8, ath orelse return error.InvalidDpopProof, expected)) return error.InvalidDpopProof;
    } else if (ath != null) return error.InvalidDpopProof;

    const nonce = parts.claimString("nonce");
    if (options.nonces) |accepted| {
        const given = nonce orelse return error.UseDpopNonce;
        for (accepted) |candidate| {
            if (std.mem.eql(u8, given, candidate)) break;
        } else return error.UseDpopNonce;
    }

    const jkt = jwk.thumbprint(header_jwk) catch return error.InvalidDpopProof;
    if (options.jkt) |bound| {
        if (!std.mem.eql(u8, &jkt, bound)) return error.DpopKeyMismatch;
    }
    return .{ .jkt = jkt, .jti = jti, .iat = iat, .nonce = nonce, .key = key };
}

/// the form RFC 9449 §4.3 compares `htu` in: no query or fragment, scheme and
/// host lowercased, a default port dropped, and an empty path written `/`.
/// Only `http` and `https` URLs without userinfo are accepted.
pub fn normalizeHtu(allocator: Allocator, htu: []const u8) error{ InvalidHtu, OutOfMemory }![]u8 {
    const scheme_end = std.mem.indexOf(u8, htu, "://") orelse return error.InvalidHtu;
    const scheme = htu[0..scheme_end];
    const default_port = if (std.ascii.eqlIgnoreCase(scheme, "https"))
        "443"
    else if (std.ascii.eqlIgnoreCase(scheme, "http"))
        "80"
    else
        return error.InvalidHtu;
    const rest = htu[scheme_end + 3 ..];
    const authority_end = std.mem.indexOfAny(u8, rest, "/?#") orelse rest.len;
    const authority = rest[0..authority_end];
    if (authority.len == 0 or std.mem.indexOfScalar(u8, authority, '@') != null) return error.InvalidHtu;

    const host_end = if (authority[0] == '[')
        (std.mem.indexOfScalar(u8, authority, ']') orelse return error.InvalidHtu) + 1
    else
        std.mem.indexOfScalar(u8, authority, ':') orelse authority.len;
    const host = authority[0..host_end];
    if (host.len == 0) return error.InvalidHtu;
    var port: []const u8 = "";
    if (host_end < authority.len) {
        if (authority[host_end] != ':') return error.InvalidHtu;
        port = authority[host_end + 1 ..];
        for (port) |c| if (!std.ascii.isDigit(c)) return error.InvalidHtu;
        if (std.mem.eql(u8, port, default_port)) port = "";
    }

    const after = rest[authority_end..];
    const path = after[0 .. std.mem.indexOfAny(u8, after, "?#") orelse after.len];

    const out = try std.fmt.allocPrint(allocator, "{s}://{s}{s}{s}{s}", .{ scheme, host, if (port.len > 0) ":" else "", port, if (path.len == 0) "/" else path });
    const origin = out[0 .. scheme.len + 3 + host.len];
    _ = std.ascii.lowerString(origin, origin);
    return out;
}

const testing = std.testing;
const Keypair = @import("../crypto/keypair.zig").Keypair;

const now: i64 = 1_800_000_000;
const url = "https://pds.example/xrpc/com.atproto.repo.createRecord";

fn signProof(a: Allocator, keypair: *const Keypair, header_extra: []const u8, payload: []const u8) ![]u8 {
    const header = try std.fmt.allocPrint(a, "{{\"typ\":\"dpop+jwt\",\"alg\":\"{s}\",\"jwk\":{s}{s}}}", .{ @tagName(keypair.algorithm()), try keypair.jwk(a), header_extra });
    return primitives.createJwt(a, header, payload, keypair);
}

fn payloadWith(a: Allocator, extra: []const u8) ![]u8 {
    return std.fmt.allocPrint(a, "{{\"jti\":\"j1\",\"htm\":\"POST\",\"htu\":\"{s}\",\"iat\":{d}{s}}}", .{ url, now, extra });
}

test "a DPoP proof from createDpopProof verifies and binds its key" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const io = testing.io;
    for ([_]@import("../crypto/multicodec.zig").KeyType{ .p256, .secp256k1 }) |key_type| {
        const keypair = try Keypair.fromSecretKey(key_type, @splat(0x21));
        const ath = try primitives.accessTokenHash(a, "access-token");
        const proof = try primitives.createDpopProof(a, io, &keypair, "GET", "https://PDS.example:443/xrpc/com.atproto.repo.getRecord?repo=x#f", "n2", ath);
        const clock: i64 = @intCast(@divFloor(std.Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s));
        const jkt = try keypair.jwkThumbprint(a);
        const verified = try verifyProof(a, proof, .{
            .htm = "GET",
            .htu = "https://pds.example/xrpc/com.atproto.repo.getRecord",
            .now = clock,
            .nonces = &.{ "n1", "n2", "n3" },
            .access_token = "access-token",
            .jkt = jkt,
        });
        try testing.expectEqualStrings(jkt, &verified.jkt);
        try testing.expectEqualStrings("n2", verified.nonce.?);
        try testing.expect(verified.jti.len > 0);
        try testing.expectError(error.UseDpopNonce, verifyProof(a, proof, .{ .htm = "GET", .htu = "https://pds.example/xrpc/com.atproto.repo.getRecord", .now = clock, .nonces = &.{"n4"}, .access_token = "access-token" }));
        try testing.expectError(error.DpopKeyMismatch, verifyProof(a, proof, .{ .htm = "GET", .htu = "https://pds.example/xrpc/com.atproto.repo.getRecord", .now = clock, .access_token = "access-token", .jkt = "someone-else" }));
    }
}

test "DPoP proofs that do not match the request are rejected" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const keypair = try Keypair.fromSecretKey(.p256, @splat(0x31));
    const base: VerifyOptions = .{ .htm = "POST", .htu = url, .now = now };

    _ = try verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), base);

    // method and URL
    var options = base;
    options.htm = "GET";
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));
    options = base;
    options.htu = "https://pds.example/xrpc/com.atproto.repo.deleteRecord";
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));
    options.htu = "https://other.example/xrpc/com.atproto.repo.createRecord";
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));

    // iat window
    options = base;
    options.now = now + 301;
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));
    options.now = now + 300;
    _ = try verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options);
    options.now = now - 6;
    options.max_future_skew = 5;
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));

    // ath: wrong token, missing, and present without a token
    options = base;
    options.access_token = "token-b";
    const ath_a = try std.fmt.allocPrint(a, ",\"ath\":\"{s}\"", .{try primitives.accessTokenHash(a, "token-a")});
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, ath_a)), options));
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));
    options.access_token = "token-a";
    _ = try verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, ath_a)), options);
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, ath_a)), base));

    // a missing nonce when one is required
    options = base;
    options.nonces = &.{"n1"};
    try testing.expectError(error.UseDpopNonce, verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, "")), options));
    _ = try verifyProof(a, try signProof(a, &keypair, "", try payloadWith(a, ",\"nonce\":\"n1\"")), options);

    // claims that must be present
    for ([_][]const u8{
        "{\"htm\":\"POST\",\"htu\":\"" ++ url ++ "\",\"iat\":1800000000}",
        "{\"jti\":\"\",\"htm\":\"POST\",\"htu\":\"" ++ url ++ "\",\"iat\":1800000000}",
        "{\"jti\":\"j\",\"htu\":\"" ++ url ++ "\",\"iat\":1800000000}",
        "{\"jti\":\"j\",\"htm\":\"POST\",\"iat\":1800000000}",
        "{\"jti\":\"j\",\"htm\":\"POST\",\"htu\":\"" ++ url ++ "\"}",
        "{\"jti\":\"j\",\"htm\":\"POST\",\"htu\":\"" ++ url ++ "\",\"iat\":\"1800000000\"}",
    }) |payload| {
        try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &keypair, "", payload), base));
    }
}

test "DPoP proofs with the wrong type, key or signature are rejected" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const keypair = try Keypair.fromSecretKey(.p256, @splat(0x31));
    const other = try Keypair.fromSecretKey(.p256, @splat(0x32));
    const options: VerifyOptions = .{ .htm = "POST", .htu = url, .now = now };
    const payload = try payloadWith(a, "");

    // typ
    const jwt_typ = try std.fmt.allocPrint(a, "{{\"typ\":\"JWT\",\"alg\":\"ES256\",\"jwk\":{s}}}", .{try keypair.jwk(a)});
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try primitives.createJwt(a, jwt_typ, payload, &keypair), options));
    // no jwk, and a jwk for another key than the signer's
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try primitives.createJwt(a, "{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\"}", payload, &keypair), options));
    const wrong_key = try std.fmt.allocPrint(a, "{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{s}}}", .{try other.jwk(a)});
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try primitives.createJwt(a, wrong_key, payload, &keypair), options));
    // an off-curve jwk
    const off_curve = "{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M\",\"y\":\"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eA\"}}";
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try primitives.createJwt(a, off_curve, payload, &keypair), options));
    // an algorithm the server does not allow
    const k256 = try Keypair.fromSecretKey(.secp256k1, @splat(0x33));
    var es256_only = options;
    es256_only.algorithms = &.{.ES256};
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, try signProof(a, &k256, "", payload), es256_only));
    _ = try verifyProof(a, try signProof(a, &k256, "", payload), options);
    // a tampered payload
    const proof = try signProof(a, &keypair, "", payload);
    const first_dot = std.mem.indexOfScalar(u8, proof, '.').?;
    const tampered = try std.mem.concat(a, u8, &.{ proof[0 .. first_dot + 1], try jwt.base64UrlEncode(a, try payloadWith(a, ",\"x\":1")), proof[std.mem.lastIndexOfScalar(u8, proof, '.').?..] });
    try testing.expectError(error.InvalidDpopProof, verifyProof(a, tampered, options));
}

test "a high-S DPoP proof is accepted" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const keypair = try Keypair.fromSecretKey(.p256, @splat(0x31));
    const proof = try signProof(a, &keypair, "", try payloadWith(a, ""));
    const sig_start = std.mem.lastIndexOfScalar(u8, proof, '.').? + 1;
    var signature = try jwt.base64UrlDecode(a, proof[sig_start..]);
    signature[32..64].* = try std.crypto.ecc.P256.scalar.neg(signature[32..64].*, .big);
    const high_s = try std.mem.concat(a, u8, &.{ proof[0..sig_start], try jwt.base64UrlEncode(a, signature) });
    _ = try verifyProof(a, high_s, .{ .htm = "POST", .htu = url, .now = now });
}

test "htu normalization" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const cases = [_][2][]const u8{
        .{ "https://pds.example/xrpc/x?a=1#b", "https://pds.example/xrpc/x" },
        .{ "HTTPS://PDS.Example:443/xrpc/X", "https://pds.example/xrpc/X" },
        .{ "http://localhost:80", "http://localhost/" },
        .{ "http://localhost:2583/oauth/token", "http://localhost:2583/oauth/token" },
        .{ "https://pds.example:8443?q", "https://pds.example:8443/" },
        .{ "https://[::1]:443/a", "https://[::1]/a" },
    };
    for (cases) |case| try testing.expectEqualStrings(case[1], try normalizeHtu(a, case[0]));
    for ([_][]const u8{ "pds.example/xrpc", "ftp://pds.example/", "https:///x", "https://user@pds.example/", "https://pds.example:44a/", "https://[::1/" }) |htu| {
        try testing.expectError(error.InvalidHtu, normalizeHtu(a, htu));
    }
}

test "the jkt is the thumbprint of the jwk as sent, and iat may be fractional" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    // the 0x21 P-256 key with its x padded; Node computes this jkt for it
    const keypair = try Keypair.fromSecretKey(.p256, @splat(0x21));
    const header =
        \\{"typ":"dpop+jwt","alg":"ES256","jwk":{"kty":"EC","crv":"P-256","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M=","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE"}}
    ;
    const payload = "{\"jti\":\"j1\",\"htm\":\"POST\",\"htu\":\"" ++ url ++ "\",\"iat\":1800000000.75}";
    const verified = try verifyProof(a, try primitives.createJwt(a, header, payload, &keypair), .{ .htm = "POST", .htu = url, .now = now });
    try testing.expectEqualStrings("PtOaRXPjIqyzEzKLfVN9E6SUMLNz9POreIT4cCTLdCs", &verified.jkt);
    try testing.expectEqual(now, verified.iat);
}