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

zat.dev/zat

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

0
0
282 lines · 14.1 KB Raw History
//! Space tokens: a requester's PDS signs a delegation token naming the space
//! host as audience; the space authority exchanges it for a space credential
//! bound to the holder's P-256 key (`cnf.kid`). Mirrors `@atproto/space`
//! `credential.ts`. Client attestations are signed with a client's JWKS key,
//! so only their structure is checked here.

const std = @import("std");
const jwt = @import("../crypto/jwt.zig");
const multicodec = @import("../crypto/multicodec.zig");
const Keypair = @import("../crypto/keypair.zig").Keypair;
const Did = @import("../syntax/did.zig").Did;
const json = @import("../xrpc/json.zig");

pub const Error = error{ InvalidSpaceToken, ExpiredSpaceToken, OutOfMemory };

pub const clock_skew_s = 5;
pub const credential_max_age_s = 3600;

pub const Type = enum {
    delegation,
    credential,
    client_attestation,

    pub fn typ(self: Type) []const u8 {
        return switch (self) {
            .delegation => "atproto-space-delegation+jwt",
            .credential => "atproto-space-credential+jwt",
            .client_attestation => "atproto-client-attestation+jwt",
        };
    }

    fn kid(self: Type) ?[]const u8 {
        return switch (self) {
            .delegation, .credential => "#atproto",
            .client_attestation => null,
        };
    }

    pub fn lifetime(self: Type) i64 {
        return switch (self) {
            .delegation, .client_attestation => 60,
            .credential => 600,
        };
    }
};

/// The audience a delegation token and a client attestation name: the space
/// authority's PDS service entry, since the space host is its PDS.
pub fn spaceHostAud(allocator: std.mem.Allocator, space_did: []const u8) ![]u8 {
    return std.fmt.allocPrint(allocator, "{s}#atproto_pds", .{space_did});
}

/// The space DID a `spaceHostAud` audience names.
pub fn spaceDidFromAud(aud: []const u8) ?[]const u8 {
    const did = if (std.mem.endsWith(u8, aud, "#atproto_pds")) aud[0 .. aud.len - "#atproto_pds".len] else return null;
    return if (Did.parse(did) != null) did else null;
}

pub const Claims = struct {
    iss: []const u8,
    sub: []const u8,
    aud: ?[]const u8 = null,
    /// The holder key a credential is bound to.
    cnf_kid: ?[]const u8 = null,
    iat: i64,
    exp: i64,
    jti: []const u8,
};

pub const Token = struct {
    alg: jwt.Algorithm,
    kid: ?[]const u8,
    claims: Claims,
    signing_input: []const u8,
    signature: []const u8,
};

/// Sign a token of `token_type` with the issuer's key. `iat` is now, in unix
/// seconds; `exp` follows from the type's lifetime unless given.
pub fn create(allocator: std.mem.Allocator, io: std.Io, token_type: Type, keypair: *const Keypair, claims: struct {
    iss: []const u8,
    sub: []const u8,
    aud: ?[]const u8 = null,
    cnf_kid: ?[]const u8 = null,
    iat: i64,
    expires_in: ?i64 = null,
}) ![]u8 {
    const expires_in = claims.expires_in orelse token_type.lifetime();
    if (token_type == .credential and (claims.cnf_kid == null or expires_in <= 0 or expires_in > credential_max_age_s)) return error.InvalidSpaceToken;
    var jti_bytes: [16]u8 = undefined;
    io.random(&jti_bytes);
    const jti = std.fmt.bytesToHex(jti_bytes, .lower);

    var header: std.Io.Writer.Allocating = .init(allocator);
    defer header.deinit();
    try header.writer.print("{{\"alg\":\"{s}\",\"typ\":\"{s}\"", .{ @tagName(keypair.algorithm()), token_type.typ() });
    if (token_type.kid()) |kid| try header.writer.print(",\"kid\":\"{s}\"", .{kid});
    try header.writer.writeByte('}');

    var payload: std.Io.Writer.Allocating = .init(allocator);
    defer payload.deinit();
    const w = &payload.writer;
    try w.print("{{\"iss\":{f},\"sub\":{f}", .{ std.json.fmt(claims.iss, .{}), std.json.fmt(claims.sub, .{}) });
    if (claims.aud) |aud| try w.print(",\"aud\":{f}", .{std.json.fmt(aud, .{})});
    if (claims.cnf_kid) |kid| try w.print(",\"cnf\":{{\"kid\":{f}}}", .{std.json.fmt(kid, .{})});
    try w.print(",\"iat\":{d},\"exp\":{d},\"jti\":\"{s}\"}}", .{ claims.iat, claims.iat + expires_in, jti });

    const header_b64 = try jwt.base64UrlEncode(allocator, header.written());
    defer allocator.free(header_b64);
    const payload_b64 = try jwt.base64UrlEncode(allocator, payload.written());
    defer allocator.free(payload_b64);
    const signing_input = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ header_b64, payload_b64 });
    defer allocator.free(signing_input);
    const signature = try keypair.sign(signing_input);
    const signature_b64 = try jwt.base64UrlEncode(allocator, &signature.bytes);
    defer allocator.free(signature_b64);
    return std.fmt.allocPrint(allocator, "{s}.{s}", .{ signing_input, signature_b64 });
}

/// Structural checks only, no signature check: as far as a client attestation
/// goes, since its key comes from the client's JWKS. Allocations belong to
/// `arena`.
pub fn parse(arena: std.mem.Allocator, token_type: Type, token: []const u8) Error!Token {
    var parts = std.mem.splitScalar(u8, token, '.');
    const header_b64 = parts.next() orelse return error.InvalidSpaceToken;
    const payload_b64 = parts.next() orelse return error.InvalidSpaceToken;
    const signature_b64 = parts.next() orelse return error.InvalidSpaceToken;
    if (parts.next() != null) return error.InvalidSpaceToken;
    const header = try jsonPart(arena, header_b64);
    const payload = try jsonPart(arena, payload_b64);

    if (!std.mem.eql(u8, json.getString(header, "typ") orelse return error.InvalidSpaceToken, token_type.typ())) return error.InvalidSpaceToken;
    const alg = jwt.Algorithm.fromString(json.getString(header, "alg") orelse return error.InvalidSpaceToken) orelse return error.InvalidSpaceToken;
    const kid = json.getString(header, "kid");
    if (token_type.kid()) |required| {
        if (!std.mem.eql(u8, kid orelse return error.InvalidSpaceToken, required)) return error.InvalidSpaceToken;
    }
    const claims: Claims = .{
        .iss = nonEmpty(json.getString(payload, "iss")) orelse return error.InvalidSpaceToken,
        .sub = nonEmpty(json.getString(payload, "sub")) orelse return error.InvalidSpaceToken,
        .aud = nonEmpty(json.getString(payload, "aud")),
        .cnf_kid = json.getString(payload, "cnf.kid"),
        .iat = numericDate(payload, "iat") orelse 0,
        .exp = numericDate(payload, "exp") orelse return error.InvalidSpaceToken,
        .jti = nonEmpty(json.getString(payload, "jti")) orelse return error.InvalidSpaceToken,
    };
    switch (token_type) {
        .delegation => if (claims.aud == null) return error.InvalidSpaceToken,
        .client_attestation => if (claims.aud == null or !std.mem.eql(u8, claims.iss, claims.sub)) return error.InvalidSpaceToken,
        .credential => {
            if (Did.parse(claims.cnf_kid orelse return error.InvalidSpaceToken) == null) return error.InvalidSpaceToken;
            if (numericDate(payload, "iat") == null or claims.exp <= claims.iat or claims.exp - claims.iat > credential_max_age_s) return error.InvalidSpaceToken;
        },
    }
    return .{
        .alg = alg,
        .kid = kid,
        .claims = claims,
        .signing_input = token[0 .. header_b64.len + 1 + payload_b64.len],
        .signature = jwt.base64UrlDecode(arena, signature_b64) catch return error.InvalidSpaceToken,
    };
}

pub const VerifyOptions = struct {
    /// The issuer's `#atproto` signing key, as a did:key.
    signing_key: []const u8,
    /// Unix seconds.
    now: i64,
    aud: ?[]const u8 = null,
    sub: ?[]const u8 = null,
};

/// Parse, check timing and claims, and verify the issuer's low-S signature.
/// A caller that finds the signature invalid may retry once with a freshly
/// resolved key, in case the issuer rotated it.
pub fn verify(arena: std.mem.Allocator, token_type: Type, token: []const u8, options: VerifyOptions) Error!Token {
    const parsed = try parse(arena, token_type, token);
    const claims = parsed.claims;
    if (token_type == .credential and claims.iat > options.now + clock_skew_s) return error.InvalidSpaceToken;
    if (options.now - clock_skew_s >= claims.exp) return error.ExpiredSpaceToken;
    if (options.aud) |aud| {
        if (!std.mem.eql(u8, claims.aud orelse return error.InvalidSpaceToken, aud)) return error.InvalidSpaceToken;
    }
    if (options.sub) |sub| {
        if (!std.mem.eql(u8, claims.sub, sub)) return error.InvalidSpaceToken;
    }
    if (token_type == .credential) {
        const holder = multicodec.parseDidKey(arena, claims.cnf_kid.?) catch return error.InvalidSpaceToken;
        if (holder.key_type != .p256) return error.InvalidSpaceToken;
    }
    const key = multicodec.parseDidKey(arena, options.signing_key) catch return error.InvalidSpaceToken;
    switch (parsed.alg) {
        .ES256 => {
            if (key.key_type != .p256) return error.InvalidSpaceToken;
            jwt.verifyP256(parsed.signing_input, parsed.signature, key.raw) catch return error.InvalidSpaceToken;
        },
        .ES256K => {
            if (key.key_type != .secp256k1) return error.InvalidSpaceToken;
            jwt.verifySecp256k1(parsed.signing_input, parsed.signature, key.raw) catch return error.InvalidSpaceToken;
        },
    }
    return parsed;
}

fn jsonPart(arena: std.mem.Allocator, b64: []const u8) Error!std.json.Value {
    const bytes = jwt.base64UrlDecode(arena, b64) catch return error.InvalidSpaceToken;
    const value = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{}) catch return error.InvalidSpaceToken;
    return if (value == .object) value else error.InvalidSpaceToken;
}

fn nonEmpty(value: ?[]const u8) ?[]const u8 {
    const v = value orelse return null;
    return if (v.len == 0) null else v;
}

fn numericDate(payload: std.json.Value, name: []const u8) ?i64 {
    return switch (json.getPath(payload, name) orelse return null) {
        .integer => |n| n,
        .float => |n| if (std.math.isFinite(n) and @abs(n) < 1e15) @intFromFloat(@floor(n)) else null,
        else => null,
    };
}

const testing = std.testing;

test "delegation tokens and credentials round trip and bind their claims" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const io = testing.io;
    var authority = try Keypair.fromSecretKey(.secp256k1, @splat(0x21));
    var requester = try Keypair.fromSecretKey(.p256, @splat(0x22));
    var holder = try Keypair.fromSecretKey(.p256, @splat(0x23));
    const space = "at:space/did:plc:alice/fm.example.private/self";
    const aud = try spaceHostAud(a, "did:plc:alice");
    const now: i64 = 1_800_000_000;

    const delegation = try create(a, io, .delegation, &requester, .{ .iss = "did:plc:bob", .sub = space, .aud = aud, .iat = now });
    const verified = try verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now, .aud = aud, .sub = space });
    try testing.expectEqualStrings("did:plc:bob", verified.claims.iss);
    try testing.expectEqualStrings("did:plc:alice", spaceDidFromAud(verified.claims.aud.?).?);
    try testing.expectEqual(now + 60, verified.claims.exp);
    try testing.expectError(error.InvalidSpaceToken, verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now, .aud = "did:plc:carol#atproto_pds" }));
    try testing.expectError(error.ExpiredSpaceToken, verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now + 65 }));
    try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, delegation, .{ .signing_key = try requester.did(a), .now = now }));

    const credential = try create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try holder.did(a), .iat = now });
    const cred = try verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now + 599, .sub = space });
    try testing.expectEqualStrings(try holder.did(a), cred.claims.cnf_kid.?);
    try testing.expectEqualStrings("#atproto", cred.kid.?);
    try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, credential, .{ .signing_key = try requester.did(a), .now = now }));
    try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now - 6 }));
    try testing.expectError(error.ExpiredSpaceToken, verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now + 605 }));
}

test "credentials need a P-256 holder key and a bounded lifetime" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const io = testing.io;
    var authority = try Keypair.fromSecretKey(.p256, @splat(0x21));
    var k256 = try Keypair.fromSecretKey(.secp256k1, @splat(0x23));
    const space = "at:space/did:plc:alice/fm.example.private/self";
    try testing.expectError(error.InvalidSpaceToken, create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .iat = 0 }));
    try testing.expectError(error.InvalidSpaceToken, create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try k256.did(a), .iat = 0, .expires_in = 3601 }));
    const bound_to_k256 = try create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try k256.did(a), .iat = 0 });
    try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, bound_to_k256, .{ .signing_key = try authority.did(a), .now = 0 }));
}

test "client attestations name the client as issuer and subject" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    var client = try Keypair.fromSecretKey(.p256, @splat(0x31));
    const id = "https://client.example/client-metadata.json";
    const token = try create(a, testing.io, .client_attestation, &client, .{ .iss = id, .sub = id, .aud = "did:plc:alice#atproto_pds", .iat = 0 });
    const parsed = try parse(a, .client_attestation, token);
    try testing.expectEqualStrings(id, parsed.claims.sub);
    try testing.expect(parsed.kid == null);
    const mismatched = try create(a, testing.io, .client_attestation, &client, .{ .iss = id, .sub = "https://other.example", .aud = "did:plc:alice#atproto_pds", .iat = 0 });
    try testing.expectError(error.InvalidSpaceToken, parse(a, .client_attestation, mismatched));
}