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

zat.dev/zat

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

0
0
935 lines · 38.9 KB Raw History
//! JWT parsing and verification for AT Protocol
//!
//! parses and verifies JWTs used in AT Protocol service auth.
//! supports ES256 (P-256) and ES256K (secp256k1) signing.
//!
//! see: https://atproto.com/specs/xrpc#service-auth

const std = @import("std");
const crypto = std.crypto;
const Io = std.Io;
const json = @import("../xrpc/json.zig");
const multibase = @import("multibase.zig");
const multicodec = @import("multicodec.zig");

fn timestamp(io: Io) i64 {
    return @intCast(@divFloor(Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s));
}

/// JWT signing algorithm
pub const Algorithm = enum {
    ES256, // P-256 / secp256r1
    ES256K, // secp256k1

    pub fn fromString(s: []const u8) ?Algorithm {
        if (std.mem.eql(u8, s, "ES256")) return .ES256;
        if (std.mem.eql(u8, s, "ES256K")) return .ES256K;
        return null;
    }
};

/// parsed JWT header
pub const Header = struct {
    alg: Algorithm,
    typ: []const u8,
};

/// parsed JWT payload (AT Protocol service auth claims)
pub const Payload = struct {
    /// issuer DID (account making the request)
    iss: []const u8,
    /// audience DID (service receiving the request)
    aud: []const u8,
    /// expiration timestamp (unix seconds)
    exp: i64,
    /// issued-at timestamp (unix seconds)
    iat: ?i64 = null,
    /// unique nonce for replay prevention
    jti: ?[]const u8 = null,
    /// lexicon method (optional, may become required)
    lxm: ?[]const u8 = null,
};

pub const DecodeError = error{ InvalidJwt, OutOfMemory };

/// a compact JWS split into its parts, for verifiers that check their own
/// header and claims. `header` and `payload` are always JSON objects.
pub const Decoded = struct {
    header: std.json.Value,
    payload: std.json.Value,
    /// `header.payload` exactly as it appears in the token.
    signing_input: []const u8,
    signature: []const u8,

    /// the header's `alg` as a supported ECDSA algorithm.
    pub fn algorithm(self: Decoded) ?Algorithm {
        return Algorithm.fromString(self.headerString("alg") orelse return null);
    }

    pub fn headerString(self: Decoded, name: []const u8) ?[]const u8 {
        return memberString(self.header, name);
    }

    pub fn claimString(self: Decoded, name: []const u8) ?[]const u8 {
        return memberString(self.payload, name);
    }

    /// a JSON number claim as whole seconds, the way a JavaScript verifier
    /// compares it: fractions are floored and out-of-range values saturate.
    pub fn claimNumericDate(self: Decoded, name: []const u8) ?i64 {
        return switch (self.payload.object.get(name) orelse return null) {
            .integer => |n| n,
            .float => |n| saturatingSeconds(n),
            .number_string => |s| saturatingSeconds(std.fmt.parseFloat(f64, s) catch return null),
            else => null,
        };
    }
};

fn memberString(object: std.json.Value, name: []const u8) ?[]const u8 {
    return switch (object.object.get(name) orelse return null) {
        .string => |s| s,
        else => null,
    };
}

fn saturatingSeconds(n: f64) ?i64 {
    if (std.math.isNan(n)) return null;
    if (n >= 0x1p63) return std.math.maxInt(i64);
    if (n < -0x1p63) return std.math.minInt(i64);
    return @intFromFloat(@floor(n));
}

/// split a compact JWS into its three parts and decode the header and payload
/// as JSON objects, accepting what the reference SDKs accept: parts are decoded
/// like Node's `Buffer.from(part, "base64url")` (see `base64UrlDecodeLenient`),
/// bytes that are not UTF-8 become U+FFFD and lone surrogate escapes become
/// `�` as JavaScript strings would carry them, and a repeated member takes
/// its last value, as `JSON.parse` does. Nothing is verified. Every allocation
/// belongs to `allocator`, which is meant to be an arena; `signing_input`
/// borrows `token`.
pub fn decodeLeaky(allocator: std.mem.Allocator, token: []const u8) DecodeError!Decoded {
    var parts = std.mem.splitScalar(u8, token, '.');
    const header_b64 = parts.next().?;
    const payload_b64 = parts.next() orelse return error.InvalidJwt;
    const signature_b64 = parts.next() orelse return error.InvalidJwt;
    if (parts.next() != null) return error.InvalidJwt;
    return .{
        .header = try decodeObject(allocator, header_b64),
        .payload = try decodeObject(allocator, payload_b64),
        .signing_input = token[0 .. header_b64.len + 1 + payload_b64.len],
        .signature = try base64UrlDecodeLenient(allocator, signature_b64),
    };
}

/// `decodeLeaky` into an arena the result owns, together with a copy of the
/// token; `deinit` frees everything.
pub fn decode(allocator: std.mem.Allocator, token: []const u8) DecodeError!std.json.Parsed(Decoded) {
    const arena = try allocator.create(std.heap.ArenaAllocator);
    errdefer allocator.destroy(arena);
    arena.* = .init(allocator);
    errdefer arena.deinit();
    const owned = try arena.allocator().dupe(u8, token);
    return .{ .arena = arena, .value = try decodeLeaky(arena.allocator(), owned) };
}

/// base64url decoding as Node's `Buffer.from(text, "base64url")` does it, which
/// is how @atproto/xrpc-server and jose decode JWT parts: both the url and the
/// standard alphabet, data ends at the first `=`, any other character is
/// skipped, and leftover bits are dropped.
pub fn base64UrlDecodeLenient(allocator: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]u8 {
    var count = LenientBase64{ .text = text };
    var len: usize = 0;
    while (count.next()) |_| len += 1;
    const out = try allocator.alloc(u8, len);
    var bytes = LenientBase64{ .text = text };
    for (out) |*b| b.* = bytes.next().?;
    return out;
}

pub const LenientBase64 = struct {
    text: []const u8,
    index: usize = 0,
    bits: u32 = 0,
    bit_count: u5 = 0,

    pub fn next(self: *LenientBase64) ?u8 {
        while (self.bit_count < 8) {
            if (self.index >= self.text.len) return null;
            const c = self.text[self.index];
            self.index += 1;
            const value: u32 = switch (c) {
                'A'...'Z' => c - 'A',
                'a'...'z' => c - 'a' + 26,
                '0'...'9' => c - '0' + 52,
                '-', '+' => 62,
                '_', '/' => 63,
                '=' => {
                    self.index = self.text.len;
                    return null;
                },
                else => continue,
            };
            self.bits = (self.bits << 6 | value) & 0xfff;
            self.bit_count += 6;
        }
        self.bit_count -= 8;
        return @truncate(self.bits >> self.bit_count);
    }
};

fn decodeObject(allocator: std.mem.Allocator, b64: []const u8) DecodeError!std.json.Value {
    const text = try javascriptText(allocator, try base64UrlDecodeLenient(allocator, b64));
    const value = std.json.parseFromSliceLeaky(std.json.Value, allocator, text, .{ .duplicate_field_behavior = .use_last }) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => return error.InvalidJwt,
    };
    return if (value == .object) value else error.InvalidJwt;
}

/// the JSON text a JavaScript verifier parses: invalid UTF-8 replaced per byte
/// by U+FFFD, and `\u` escapes of unpaired surrogates, which a JavaScript
/// string holds but UTF-8 cannot, rewritten to `�`.
fn javascriptText(allocator: std.mem.Allocator, bytes: []u8) error{OutOfMemory}![]u8 {
    var text = bytes;
    if (!std.unicode.utf8ValidateSlice(bytes)) {
        var out: std.ArrayList(u8) = .empty;
        var i: usize = 0;
        while (i < bytes.len) {
            const len = std.unicode.utf8ByteSequenceLength(bytes[i]) catch 0;
            const valid = len != 0 and i + len <= bytes.len and
                if (std.unicode.utf8Decode(bytes[i .. i + len])) |_| true else |_| false;
            if (!valid) {
                try out.appendSlice(allocator, "\u{fffd}");
                i += 1;
            } else {
                try out.appendSlice(allocator, bytes[i .. i + len]);
                i += len;
            }
        }
        text = out.items;
    }

    var in_string = false;
    var i: usize = 0;
    while (i < text.len) : (i += 1) {
        switch (text[i]) {
            '"' => in_string = !in_string,
            '\\' => if (in_string) {
                const unit = escapedUnit(text, i) orelse {
                    i += 1;
                    continue;
                };
                if (unit >= 0xd800 and unit <= 0xdbff) {
                    if (escapedUnit(text, i + 6)) |low| if (low >= 0xdc00 and low <= 0xdfff) {
                        i += 11;
                        continue;
                    };
                    @memcpy(text[i..][0..6], "\\ufffd");
                } else if (unit >= 0xdc00 and unit <= 0xdfff) {
                    @memcpy(text[i..][0..6], "\\ufffd");
                }
                i += 5;
            },
            else => {},
        }
    }
    return text;
}

fn escapedUnit(text: []const u8, at: usize) ?u16 {
    if (at + 6 > text.len or text[at] != '\\' or text[at + 1] != 'u') return null;
    return std.fmt.parseInt(u16, text[at + 2 .. at + 6], 16) catch null;
}

/// parsed JWT with raw components
pub const Jwt = struct {
    allocator: std.mem.Allocator,

    /// decoded header
    header: Header,
    /// decoded payload
    payload: Payload,
    /// raw signature bytes (r || s, 64 bytes)
    signature: []u8,
    /// the signed portion (header.payload) for verification
    signed_input: []const u8,
    /// original token for reference
    raw_token: []const u8,

    /// parse a JWT token string
    pub fn parse(allocator: std.mem.Allocator, token: []const u8) !Jwt {
        // split on dots: header.payload.signature
        var parts: [3][]const u8 = undefined;
        var part_idx: usize = 0;
        var it = std.mem.splitScalar(u8, token, '.');

        while (it.next()) |part| {
            if (part_idx >= 3) return error.InvalidJwt;
            parts[part_idx] = part;
            part_idx += 1;
        }

        if (part_idx != 3) return error.InvalidJwt;

        const header_b64 = parts[0];
        const payload_b64 = parts[1];
        const sig_b64 = parts[2];

        // find signed input (everything before last dot)
        const last_dot = std.mem.lastIndexOfScalar(u8, token, '.') orelse return error.InvalidJwt;
        const signed_input = token[0..last_dot];

        // decode header
        const header_json = try base64UrlDecode(allocator, header_b64);
        defer allocator.free(header_json);

        const header = try parseHeader(allocator, header_json);

        // decode payload
        const payload_json = try base64UrlDecode(allocator, payload_b64);
        defer allocator.free(payload_json);

        const payload = try parsePayload(allocator, payload_json);
        errdefer freePayload(allocator, payload);

        // decode signature
        const signature = try base64UrlDecode(allocator, sig_b64);
        errdefer allocator.free(signature);

        // JWT signatures should be 64 bytes (r || s)
        if (signature.len != 64) return error.InvalidSignatureLength;

        return .{
            .allocator = allocator,
            .header = header,
            .payload = payload,
            .signature = signature,
            .signed_input = signed_input,
            .raw_token = token,
        };
    }

    /// verify the JWT signature against a public key
    /// public_key should be multibase-encoded (from DID document)
    ///
    /// JWTs are JOSE tokens (RFC 7515): the low-S requirement does not apply,
    /// and signers such as WebCrypto-based OAuth clients routinely emit high-S
    /// signatures. verification is therefore lenient on S. atproto's strict
    /// low-S requirement is enforced where it belongs — on content-addressed
    /// signatures (repo commits via verifyCommitCar, did:key via
    /// verifyDidKeySignature), which use verifyP256/verifySecp256k1 directly.
    pub fn verify(self: *const Jwt, public_key_multibase: []const u8) !void {
        // decode multibase key
        const key_bytes = try multibase.decode(self.allocator, public_key_multibase);
        defer self.allocator.free(key_bytes);

        // parse multicodec to get key type and raw bytes
        const parsed_key = try multicodec.parsePublicKey(key_bytes);

        // verify key type matches algorithm
        switch (self.header.alg) {
            .ES256K => if (parsed_key.key_type != .secp256k1) return error.AlgorithmKeyMismatch,
            .ES256 => if (parsed_key.key_type != .p256) return error.AlgorithmKeyMismatch,
        }

        try verifyJose(self.header.alg, self.signed_input, self.signature, parsed_key.raw);
    }

    /// check if the token is expired
    pub fn isExpired(self: *const Jwt, io: Io) bool {
        const now = timestamp(io);
        return now > self.payload.exp;
    }

    /// check if the token is expired with clock skew tolerance (in seconds)
    pub fn isExpiredWithSkew(self: *const Jwt, io: Io, skew_seconds: i64) bool {
        const now = timestamp(io);
        return now > (self.payload.exp + skew_seconds);
    }

    pub fn deinit(self: *Jwt) void {
        self.allocator.free(self.signature);
        freePayload(self.allocator, self.payload);
    }
};

// === internal helpers ===

pub fn base64UrlDecode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
    const decoder = &std.base64.url_safe_no_pad.Decoder;
    const size = try decoder.calcSizeForSlice(input);
    const output = try allocator.alloc(u8, size);
    errdefer allocator.free(output);
    try decoder.decode(output, input);
    return output;
}

pub fn base64UrlEncode(allocator: std.mem.Allocator, data: []const u8) ![]u8 {
    const encoder = &std.base64.url_safe_no_pad.Encoder;
    const len = encoder.calcSize(data.len);
    const buf = try allocator.alloc(u8, len);
    _ = encoder.encode(buf, data);
    return buf;
}

fn parseHeader(allocator: std.mem.Allocator, header_json: []const u8) !Header {
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, header_json, .{});
    defer parsed.deinit();

    const alg_str = json.getString(parsed.value, "alg") orelse return error.MissingAlgorithm;
    const alg = Algorithm.fromString(alg_str) orelse return error.UnsupportedAlgorithm;

    return .{
        .alg = alg,
        .typ = "JWT", // static string, no need to dupe
    };
}

fn parsePayload(allocator: std.mem.Allocator, payload_json: []const u8) !Payload {
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, payload_json, .{});
    defer parsed.deinit();

    const iss_raw = json.getString(parsed.value, "iss") orelse return error.MissingIssuer;
    const aud_raw = json.getString(parsed.value, "aud") orelse return error.MissingAudience;
    const exp = json.getInt(parsed.value, "exp") orelse return error.MissingExpiration;

    // dupe strings so they outlive parsed
    const iss = try allocator.dupe(u8, iss_raw);
    errdefer allocator.free(iss);

    const aud = try allocator.dupe(u8, aud_raw);
    errdefer allocator.free(aud);

    const jti: ?[]const u8 = if (json.getString(parsed.value, "jti")) |s|
        try allocator.dupe(u8, s)
    else
        null;
    errdefer if (jti) |s| allocator.free(s);

    const lxm: ?[]const u8 = if (json.getString(parsed.value, "lxm")) |s|
        try allocator.dupe(u8, s)
    else
        null;

    return .{
        .iss = iss,
        .aud = aud,
        .exp = exp,
        .iat = json.getInt(parsed.value, "iat"),
        .jti = jti,
        .lxm = lxm,
    };
}

fn freePayload(allocator: std.mem.Allocator, payload: Payload) void {
    allocator.free(payload.iss);
    allocator.free(payload.aud);
    if (payload.jti) |s| allocator.free(s);
    if (payload.lxm) |s| allocator.free(s);
}

/// compare two 32-byte big-endian values: true if a > b
fn bigEndianGt(a: [32]u8, b: [32]u8) bool {
    for (a, b) |ab, bb| {
        if (ab > bb) return true;
        if (ab < bb) return false;
    }
    return false;
}

/// reject high-S signatures (atproto requires low-S normalization).
/// s is high-S if s > curve_order / 2.
fn rejectHighS(comptime half_order: [32]u8, s_bytes: [32]u8) error{HighSSignature}!void {
    if (bigEndianGt(s_bytes, half_order)) return error.HighSSignature;
}

// secp256k1 order/2 (big-endian)
// order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
const secp256k1_half_order: [32]u8 = .{
    0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D,
    0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0,
};

// P-256 order/2 (big-endian)
// order = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
const p256_half_order: [32]u8 = .{
    0x7F, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00,
    0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xDE, 0x73, 0x7D, 0x56, 0xD3, 0x8B, 0xCF, 0x42,
    0x79, 0xDC, 0xE5, 0x61, 0x7E, 0x31, 0x92, 0xA8,
};

/// ECDSA signature (r || s, 64 bytes)
pub const Signature = struct {
    bytes: [64]u8,
};

/// sign a message with deterministic RFC 6979 ECDSA and low-S normalization
fn signEcdsa(comptime Scheme: type, comptime Curve: type, comptime half_order: [32]u8, message: []const u8, secret_key_bytes: []const u8) !Signature {
    if (secret_key_bytes.len != 32) return error.InvalidSecretKey;
    const sk = Scheme.SecretKey.fromBytes(secret_key_bytes[0..32].*) catch return error.InvalidSecretKey;
    const kp = Scheme.KeyPair.fromSecretKey(sk) catch return error.InvalidSecretKey;

    var sig = kp.sign(message, null) catch return error.SigningFailed;

    if (bigEndianGt(sig.s, half_order)) {
        sig.s = Curve.scalar.neg(sig.s, .big) catch return error.SigningFailed;
    }

    return .{ .bytes = sig.toBytes() };
}

/// verify an ECDSA signature, rejecting high-S
fn verifyEcdsa(comptime Scheme: type, comptime half_order: [32]u8, message: []const u8, sig_bytes: []const u8, public_key_raw: []const u8) !void {
    if (sig_bytes.len != 64) return error.InvalidSignature;

    // reject high-S before constructing Signature — fromBytes does scalar
    // arithmetic that can overflow on out-of-range values
    rejectHighS(half_order, sig_bytes[32..64].*) catch return error.SignatureVerificationFailed;

    const sig = Scheme.Signature.fromBytes(sig_bytes[0..64].*);

    if (public_key_raw.len != 33) return error.InvalidPublicKey;
    const public_key = Scheme.PublicKey.fromSec1(public_key_raw) catch return error.InvalidPublicKey;

    sig.verify(message, public_key) catch return error.SignatureVerificationFailed;
}

pub fn signSecp256k1(message: []const u8, secret_key_bytes: []const u8) !Signature {
    return signEcdsa(crypto.sign.ecdsa.EcdsaSecp256k1Sha256, crypto.ecc.Secp256k1, secp256k1_half_order, message, secret_key_bytes);
}

pub fn signP256(message: []const u8, secret_key_bytes: []const u8) !Signature {
    return signEcdsa(crypto.sign.ecdsa.EcdsaP256Sha256, crypto.ecc.P256, p256_half_order, message, secret_key_bytes);
}

pub fn verifySecp256k1(message: []const u8, sig_bytes: []const u8, public_key_raw: []const u8) !void {
    return verifyEcdsa(crypto.sign.ecdsa.EcdsaSecp256k1Sha256, secp256k1_half_order, message, sig_bytes, public_key_raw);
}

pub fn verifyP256(message: []const u8, sig_bytes: []const u8, public_key_raw: []const u8) !void {
    return verifyEcdsa(crypto.sign.ecdsa.EcdsaP256Sha256, p256_half_order, message, sig_bytes, public_key_raw);
}

/// verify a JOSE ECDSA signature (RFC 7515) WITHOUT the atproto low-S
/// requirement: both low-S and high-S signatures are accepted.
///
/// use this for general JOSE JWTs — OAuth client assertions, DPoP proofs —
/// where signing libraries are not required to normalize S, and high-S
/// signatures are valid. repo commit and service-auth signatures must use the
/// strict `Jwt.verify` / `verifyP256` / `verifySecp256k1` path, which rejects
/// high-S to hold atproto's low-S requirement. do not reach for `verifyJose`
/// where signature malleability matters (e.g. anything content-addressed).
pub fn verifyJose(alg: Algorithm, message: []const u8, sig_bytes: []const u8, public_key_raw: []const u8) !void {
    return switch (alg) {
        .ES256 => verifyEcdsaJose(crypto.sign.ecdsa.EcdsaP256Sha256, message, sig_bytes, public_key_raw),
        .ES256K => verifyEcdsaJose(crypto.sign.ecdsa.EcdsaSecp256k1Sha256, message, sig_bytes, public_key_raw),
    };
}

/// verify an ECDSA signature accepting both low-S and high-S (RFC 7515 / JOSE).
/// unlike `verifyEcdsa`, there is no `rejectHighS` step. `Signature.fromBytes`
/// only copies bytes; an out-of-range `s` (>= curve order) is rejected by
/// `verify` as `NonCanonical`, surfaced here as `SignatureVerificationFailed`.
fn verifyEcdsaJose(comptime Scheme: type, message: []const u8, sig_bytes: []const u8, public_key_raw: []const u8) !void {
    if (sig_bytes.len != 64) return error.InvalidSignature;
    if (public_key_raw.len != 33) return error.InvalidPublicKey;

    const sig = Scheme.Signature.fromBytes(sig_bytes[0..64].*);
    const public_key = Scheme.PublicKey.fromSec1(public_key_raw) catch return error.InvalidPublicKey;
    sig.verify(message, public_key) catch return error.SignatureVerificationFailed;
}

// === tests ===

test "parse jwt structure" {
    // a minimal valid JWT structure (signature won't verify, just testing parsing)
    // header: {"alg":"ES256K","typ":"JWT"}
    // payload: {"iss":"did:plc:test","aud":"did:plc:service","exp":9999999999}
    const token = "eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJkaWQ6cGxjOnRlc3QiLCJhdWQiOiJkaWQ6cGxjOnNlcnZpY2UiLCJleHAiOjk5OTk5OTk5OTl9.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    var jwt = try Jwt.parse(std.testing.allocator, token);
    defer jwt.deinit();

    try std.testing.expectEqual(Algorithm.ES256K, jwt.header.alg);
    try std.testing.expectEqualStrings("did:plc:test", jwt.payload.iss);
    try std.testing.expectEqualStrings("did:plc:service", jwt.payload.aud);
    try std.testing.expectEqual(@as(i64, 9999999999), jwt.payload.exp);
}

test "reject invalid jwt format" {
    // missing parts
    try std.testing.expectError(error.InvalidJwt, Jwt.parse(std.testing.allocator, "onlyonepart"));
    try std.testing.expectError(error.InvalidJwt, Jwt.parse(std.testing.allocator, "two.parts"));
    try std.testing.expectError(error.InvalidJwt, Jwt.parse(std.testing.allocator, "too.many.parts.here"));
}

test "Jwt.parse frees its claims when the signature part is rejected" {
    // {"alg":"ES256K"} . {"iss":"did:plc:test","aud":"did:plc:service","exp":9999999999,"jti":"j","lxm":"m"}
    const signed = "eyJhbGciOiJFUzI1NksifQ.eyJpc3MiOiJkaWQ6cGxjOnRlc3QiLCJhdWQiOiJkaWQ6cGxjOnNlcnZpY2UiLCJleHAiOjk5OTk5OTk5OTksImp0aSI6ImoiLCJseG0iOiJtIn0";
    try std.testing.expectError(error.InvalidCharacter, Jwt.parse(std.testing.allocator, signed ++ ".!!!!"));
    try std.testing.expectError(error.InvalidSignatureLength, Jwt.parse(std.testing.allocator, signed ++ ".AAEC"));
}

test "decode keeps every header and claim for custom verification" {
    const allocator = std.testing.allocator;
    const header_b64 = try base64UrlEncode(allocator, "{\"alg\":\"ES256\",\"typ\":\"dpop+jwt\",\"kid\":\"k1\",\"jwk\":{\"kty\":\"EC\"}}");
    defer allocator.free(header_b64);
    const payload_b64 = try base64UrlEncode(allocator, "{\"iss\":\"https://client.example\",\"iat\":1700000000,\"exp\":1700000060.9,\"cnf\":{\"jkt\":\"x\"}}");
    defer allocator.free(payload_b64);
    const token = try std.fmt.allocPrint(allocator, "{s}.{s}.AAEC", .{ header_b64, payload_b64 });
    defer allocator.free(token);

    const decoded = try decode(allocator, token);
    defer decoded.deinit();
    const parts = decoded.value;
    try std.testing.expectEqual(Algorithm.ES256, parts.algorithm().?);
    try std.testing.expectEqualStrings("dpop+jwt", parts.headerString("typ").?);
    try std.testing.expectEqualStrings("k1", parts.headerString("kid").?);
    try std.testing.expectEqualStrings("EC", json.getString(parts.header, "jwk.kty").?);
    try std.testing.expectEqualStrings("https://client.example", parts.claimString("iss").?);
    try std.testing.expectEqual(@as(?i64, 1700000000), parts.claimNumericDate("iat"));
    try std.testing.expectEqual(@as(?i64, 1700000060), parts.claimNumericDate("exp"));
    try std.testing.expect(parts.claimString("iat") == null);
    try std.testing.expect(parts.claimNumericDate("iss") == null);
    try std.testing.expectEqualStrings(token[0 .. header_b64.len + 1 + payload_b64.len], parts.signing_input);
    try std.testing.expectEqualSlices(u8, &.{ 0, 1, 2 }, parts.signature);
}

test "decodeLeaky borrows the token and allocates into an arena" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkaWQ6cGxjOmFiYyJ9.AAEC";
    const parts = try decodeLeaky(arena.allocator(), token);
    try std.testing.expect(parts.algorithm() == null);
    try std.testing.expectEqualStrings("HS256", parts.headerString("alg").?);
    try std.testing.expectEqualStrings("did:plc:abc", parts.claimString("sub").?);
    try std.testing.expectEqual(token.ptr, parts.signing_input.ptr);
}

test "base64UrlDecodeLenient matches Node's Buffer.from(text, \"base64url\")" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    // expected bytes from Node 22.23.4
    const cases = [_][2][]const u8{
        .{ "eyJhIjoxfQ", "{\"a\":1}" },
        .{ "eyJhIjoxfQ==", "{\"a\":1}" },
        .{ "eyJh IjoxfQ", "{\"a\":1}" },
        .{ "eyJh*IjoxfQ", "{\"a\":1}" },
        .{ "eyJh=IjoxfQ", "{\"a" },
        .{ "+/+/", "\xfb\xff\xbf" },
        .{ "-_-_", "\xfb\xff\xbf" },
        .{ "AAF", "\x00\x01" },
        .{ "AAE", "\x00\x01" },
        .{ "A", "" },
        .{ "", "" },
    };
    for (cases) |case| try std.testing.expectEqualSlices(u8, case[1], try base64UrlDecodeLenient(a, case[0]));
}

test "decode accepts what the reference's base64url and JSON.parse accept" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const header = "eyJhbGciOiJFUzI1NiJ9"; // {"alg":"ES256"}

    const padded = try decodeLeaky(a, header ++ "==.eyJzdWIiOiJ4In0=.AAEC==");
    try std.testing.expectEqualStrings("x", padded.claimString("sub").?);
    try std.testing.expectEqualSlices(u8, &.{ 0, 1, 2 }, padded.signature);

    // {"a":1,"a":2}: the last member wins, as with JSON.parse
    const duplicate = try decodeLeaky(a, header ++ ".eyJhIjoxLCJhIjoyfQ.AAEC");
    try std.testing.expectEqual(@as(?i64, 2), duplicate.claimNumericDate("a"));

    // an empty signature part decodes to no bytes; it can never verify
    try std.testing.expectEqual(@as(usize, 0), (try decodeLeaky(a, header ++ ".eyJzdWIiOiJ4In0.")).signature.len);

    // {"s":"<0xff>"} and {"s":"\ud800","p":"😀"}
    const invalid_utf8 = try decodeLeaky(a, try std.fmt.allocPrint(a, "{s}.{s}.AAEC", .{ header, try base64UrlEncode(a, "{\"s\":\"\xff\"}") }));
    try std.testing.expectEqualStrings("\u{fffd}", invalid_utf8.claimString("s").?);
    const surrogates = try decodeLeaky(a, try std.fmt.allocPrint(a, "{s}.{s}.AAEC", .{ header, try base64UrlEncode(a, "{\"s\":\"a\\ud800b\",\"p\":\"\\ud83d\\ude00\",\"e\":\"\\\\ud800\"}") }));
    try std.testing.expectEqualStrings("a\u{fffd}b", surrogates.claimString("s").?);
    try std.testing.expectEqualStrings("\u{1f600}", surrogates.claimString("p").?);
    try std.testing.expectEqualStrings("\\ud800", surrogates.claimString("e").?);
}

test "decode rejects what the reference cannot parse" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const header = "eyJhbGciOiJFUzI1NiJ9";
    const payload = "eyJzdWIiOiJ4In0";
    for ([_][]const u8{
        "",
        header,
        header ++ "." ++ payload,
        header ++ "." ++ payload ++ ".AAEC.AAEC",
        // an empty header or payload is not JSON
        "." ++ payload ++ ".AAEC",
        header ++ "..AAEC",
        // a JSON array, a string, and not JSON
        header ++ ".W10.AAEC",
        header ++ ".Ingi.AAEC",
        header ++ ".bm9wZQ.AAEC",
    }) |token| {
        try std.testing.expectError(error.InvalidJwt, decodeLeaky(a, token));
    }
}

test "numeric dates floor and saturate like JavaScript comparisons" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const payload = try base64UrlEncode(a, "{\"f\":-1.5,\"big\":1e400,\"small\":-1e30,\"huge\":123456789012345678901234567890}");
    const parts = try decodeLeaky(a, try std.fmt.allocPrint(a, "eyJhbGciOiJFUzI1NiJ9.{s}.AAEC", .{payload}));
    try std.testing.expectEqual(@as(?i64, -2), parts.claimNumericDate("f"));
    try std.testing.expectEqual(@as(?i64, std.math.maxInt(i64)), parts.claimNumericDate("big"));
    try std.testing.expectEqual(@as(?i64, std.math.minInt(i64)), parts.claimNumericDate("small"));
    try std.testing.expectEqual(@as(?i64, std.math.maxInt(i64)), parts.claimNumericDate("huge"));
}

test "decode frees everything on failure" {
    try std.testing.checkAllAllocationFailures(std.testing.allocator, struct {
        fn run(allocator: std.mem.Allocator) !void {
            const decoded = try decode(allocator, "eyJhbGciOiJFUzI1NiJ9.eyJzIjoiXHVkODAwXHUwMGZmIn0.AAEC");
            decoded.deinit();
        }
    }.run, .{});
}

test "verify ES256K signature - official fixture" {
    // test vector from bluesky-social/indigo atproto/auth/jwt_test.go
    // pubkey: did:key:zQ3shscXNYZQZSPwegiv7uQZZV5kzATLBRtgJhs7uRY7pfSk4
    // iss: did:example:iss, aud: did:example:aud, exp: 1713571012
    const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpc3MiOiJkaWQ6ZXhhbXBsZTppc3MiLCJhdWQiOiJkaWQ6ZXhhbXBsZTphdWQiLCJleHAiOjE3MTM1NzEwMTJ9.J_In_PQCMjygeeoIKyjybORD89ZnEy1bZTd--sdq_78qv3KCO9181ZAh-2Pl0qlXZjfUlxgIa6wiak2NtsT98g";

    // extract multibase key from did:key (strip "did:key:" prefix)
    const did_key = "did:key:zQ3shscXNYZQZSPwegiv7uQZZV5kzATLBRtgJhs7uRY7pfSk4";
    const multibase_key = did_key["did:key:".len..];

    var jwt = try Jwt.parse(std.testing.allocator, token);
    defer jwt.deinit();

    // verify claims
    try std.testing.expectEqual(Algorithm.ES256K, jwt.header.alg);
    try std.testing.expectEqualStrings("did:example:iss", jwt.payload.iss);
    try std.testing.expectEqualStrings("did:example:aud", jwt.payload.aud);

    // verify signature
    try jwt.verify(multibase_key);
}

test "verify ES256 signature - official fixture" {
    // test vector from bluesky-social/indigo atproto/auth/jwt_test.go
    // pubkey: did:key:zDnaeXRDKRCEUoYxi8ZJS2pDsgfxUh3pZiu3SES9nbY4DoART
    // iss: did:example:iss, aud: did:example:aud, exp: 1713571554
    const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJkaWQ6ZXhhbXBsZTppc3MiLCJhdWQiOiJkaWQ6ZXhhbXBsZTphdWQiLCJleHAiOjE3MTM1NzE1NTR9.FFRLm7SGbDUp6cL0WoCs0L5oqNkjCXB963TqbgI-KxIjbiqMQATVCalcMJx17JGTjMmfVHJP6Op_V4Z0TTjqog";

    // extract multibase key from did:key
    const did_key = "did:key:zDnaeXRDKRCEUoYxi8ZJS2pDsgfxUh3pZiu3SES9nbY4DoART";
    const multibase_key = did_key["did:key:".len..];

    var jwt = try Jwt.parse(std.testing.allocator, token);
    defer jwt.deinit();

    // verify claims
    try std.testing.expectEqual(Algorithm.ES256, jwt.header.alg);
    try std.testing.expectEqualStrings("did:example:iss", jwt.payload.iss);
    try std.testing.expectEqualStrings("did:example:aud", jwt.payload.aud);

    // verify signature
    try jwt.verify(multibase_key);
}

test "reject signature with wrong key" {
    // ES256K token
    const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpc3MiOiJkaWQ6ZXhhbXBsZTppc3MiLCJhdWQiOiJkaWQ6ZXhhbXBsZTphdWQiLCJleHAiOjE3MTM1NzEwMTJ9.J_In_PQCMjygeeoIKyjybORD89ZnEy1bZTd--sdq_78qv3KCO9181ZAh-2Pl0qlXZjfUlxgIa6wiak2NtsT98g";

    // different ES256K key (second fixture from indigo)
    const wrong_key = "zQ3shqKrpHzQ5HDfhgcYMWaFcpBK3SS39wZLdTjA5GeakX8G5";

    var jwt = try Jwt.parse(std.testing.allocator, token);
    defer jwt.deinit();

    // should fail verification with wrong key
    try std.testing.expectError(error.SignatureVerificationFailed, jwt.verify(wrong_key));
}

test "sign and verify round-trip - secp256k1" {
    // generate a deterministic keypair using a fixed seed
    const Scheme = crypto.sign.ecdsa.EcdsaSecp256k1Sha256;
    const sk_bytes = [_]u8{
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
        0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
    };

    const message = "hello atproto";
    const sig = try signSecp256k1(message, &sk_bytes);

    // verify low-S: s must be <= half_order
    const s = sig.bytes[32..64].*;
    try std.testing.expect(!bigEndianGt(s, secp256k1_half_order));

    // verify with the corresponding public key
    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk_bytes = kp.public_key.toCompressedSec1();

    try verifySecp256k1(message, &sig.bytes, &pk_bytes);
}

test "sign and verify round-trip - P-256" {
    const Scheme = crypto.sign.ecdsa.EcdsaP256Sha256;
    const sk_bytes = [_]u8{
        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 message = "hello atproto p256";
    const sig = try signP256(message, &sk_bytes);

    // verify low-S
    const s = sig.bytes[32..64].*;
    try std.testing.expect(!bigEndianGt(s, p256_half_order));

    // verify with the corresponding public key
    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk_bytes = kp.public_key.toCompressedSec1();

    try verifyP256(message, &sig.bytes, &pk_bytes);
}

test "sign produces deterministic signatures" {
    const sk_bytes = [_]u8{
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
        0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
    };
    const message = "deterministic test";

    const sig1 = try signSecp256k1(message, &sk_bytes);
    const sig2 = try signSecp256k1(message, &sk_bytes);
    try std.testing.expectEqualSlices(u8, &sig1.bytes, &sig2.bytes);
}

test "verifyJose accepts high-S P-256 while strict verifyP256 rejects it" {
    const Scheme = crypto.sign.ecdsa.EcdsaP256Sha256;
    const sk_bytes = [_]u8{
        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 message = "oauth client assertion";

    // signP256 normalizes to low-S; flip S to its complement to get a valid
    // high-S signature, exactly as a non-normalizing JOSE signer would emit.
    const low = try signP256(message, &sk_bytes);
    var high = low.bytes;
    high[32..64].* = try crypto.ecc.P256.scalar.neg(low.bytes[32..64].*, .big);
    try std.testing.expect(bigEndianGt(high[32..64].*, p256_half_order));

    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk = kp.public_key.toCompressedSec1();

    // the strict (repo / did:key) policy rejects high-S
    try std.testing.expectError(error.SignatureVerificationFailed, verifyP256(message, &high, &pk));
    // the JOSE policy accepts it — and still accepts the low-S form
    try verifyJose(.ES256, message, &high, &pk);
    try verifyJose(.ES256, message, &low.bytes, &pk);
}

test "verifyJose accepts high-S secp256k1 while strict verifySecp256k1 rejects it" {
    const Scheme = crypto.sign.ecdsa.EcdsaSecp256k1Sha256;
    const sk_bytes = [_]u8{
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
        0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
    };
    const message = "oauth client assertion";

    const low = try signSecp256k1(message, &sk_bytes);
    var high = low.bytes;
    high[32..64].* = try crypto.ecc.Secp256k1.scalar.neg(low.bytes[32..64].*, .big);
    try std.testing.expect(bigEndianGt(high[32..64].*, secp256k1_half_order));

    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk = kp.public_key.toCompressedSec1();

    try std.testing.expectError(error.SignatureVerificationFailed, verifySecp256k1(message, &high, &pk));
    try verifyJose(.ES256K, message, &high, &pk);
    try verifyJose(.ES256K, message, &low.bytes, &pk);
}

test "Jwt.verify accepts a high-S ES256 JWT (JOSE leniency)" {
    const allocator = std.testing.allocator;
    const Scheme = crypto.sign.ecdsa.EcdsaP256Sha256;
    const sk_bytes = [_]u8{
        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 header_b64 = try base64UrlEncode(allocator, "{\"alg\":\"ES256\",\"typ\":\"JWT\"}");
    defer allocator.free(header_b64);
    const payload_b64 = try base64UrlEncode(allocator, "{\"iss\":\"did:example:iss\",\"aud\":\"did:example:aud\",\"exp\":9999999999}");
    defer allocator.free(payload_b64);
    const signed_input = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ header_b64, payload_b64 });
    defer allocator.free(signed_input);

    const low = try signP256(signed_input, &sk_bytes);
    var high = low.bytes;
    high[32..64].* = try crypto.ecc.P256.scalar.neg(low.bytes[32..64].*, .big);
    const sig_b64 = try base64UrlEncode(allocator, &high);
    defer allocator.free(sig_b64);
    const token = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ signed_input, sig_b64 });
    defer allocator.free(token);

    // the public key as it would appear in a DID document (multibase multikey)
    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk = kp.public_key.toCompressedSec1();
    const mc = try multicodec.encodePublicKey(allocator, .p256, &pk);
    defer allocator.free(mc);
    const multibase_key = try multibase.encode(allocator, .base58btc, mc);
    defer allocator.free(multibase_key);

    var jwt = try Jwt.parse(allocator, token);
    defer jwt.deinit();
    try jwt.verify(multibase_key);
}

test "verifyJose rejects out-of-range S without panicking" {
    const Scheme = crypto.sign.ecdsa.EcdsaP256Sha256;
    const sk_bytes = [_]u8{
        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 message = "out of range";

    const low = try signP256(message, &sk_bytes);
    var bad = low.bytes;
    bad[32..64].* = @as([32]u8, @splat(0xFF)); // s >= curve order: non-canonical

    const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
    const kp = try Scheme.KeyPair.fromSecretKey(sk);
    const pk = kp.public_key.toCompressedSec1();

    try std.testing.expectError(error.SignatureVerificationFailed, verifyJose(.ES256, message, &bad, &pk));
}