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

zat.dev/zds

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

0
0
98 lines · 4.1 KB Raw History
//! Verification for permissioned-space client attestations.

const std = @import("std");
const clock = @import("../core/clock.zig");
const outbound = @import("outbound.zig");
const zat = @import("zat");

const max_json_bytes = 256 * 1024;

pub const Claims = struct {
    client_id: []const u8,
    jti: []const u8,
    exp: i64,
};

pub fn verify(
    allocator: std.mem.Allocator,
    io: std.Io,
    token: []const u8,
    expected_audience: []const u8,
) !Claims {
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const attestation = try parse(arena.allocator(), token, expected_audience, now());
    const issuer = attestation.client_id;
    if (!std.mem.startsWith(u8, issuer, "https://")) return error.InvalidClientId;

    const metadata = try fetchJson(allocator, io, issuer);
    defer metadata.deinit();
    if (!std.mem.eql(u8, zat.json.getString(metadata.value, "client_id") orelse issuer, issuer)) return error.InvalidClientMetadata;
    var fetched_jwks: ?std.json.Parsed(std.json.Value) = null;
    defer if (fetched_jwks) |parsed| parsed.deinit();
    const jwks = if (metadata.value == .object and metadata.value.object.get("jwks") != null)
        metadata.value.object.get("jwks").?
    else blk: {
        const uri = zat.json.getString(metadata.value, "jwks_uri") orelse return error.InvalidClientMetadata;
        fetched_jwks = try fetchJson(allocator, io, uri);
        break :blk fetched_jwks.?.value;
    };
    try attestation.verifySignature(jwks);
    return .{
        .client_id = try allocator.dupe(u8, issuer),
        .jti = try allocator.dupe(u8, attestation.jti),
        .exp = attestation.exp.?,
    };
}

fn parse(arena: std.mem.Allocator, token: []const u8, expected_audience: []const u8, current_time: i64) zat.oauth.ClientAssertionError!zat.oauth.ClientAssertion {
    return zat.oauth.parseClientAssertion(arena, token, .{
        .audience = expected_audience,
        .now = current_time,
        .typ = "atproto-client-attestation+jwt",
        .require_kid = true,
        .max_lifetime = 300,
    });
}

fn fetchJson(allocator: std.mem.Allocator, io: std.Io, url: []const u8) !std.json.Parsed(std.json.Value) {
    var transport = zat.HttpTransport.init(io, allocator);
    defer transport.deinit();
    const result = try outbound.fetch(allocator, io, &transport, .{
        .url = url,
        .method = .GET,
        .accept = "application/json",
        .max_response_size = max_json_bytes,
    });
    const status = @backingInt(result.status);
    if (status < 200 or status >= 300) return error.HttpStatus;
    return std.json.parseFromSlice(std.json.Value, allocator, result.body, .{});
}

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

test "client attestation freshness is short lived" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x46));
    const audience = "did:web:space.example#atproto_space_host";
    const header = "{\"typ\":\"atproto-client-attestation+jwt\",\"alg\":\"ES256\",\"kid\":\"k1\"}";
    const cases = [_]struct { header: []const u8, iat: i64, exp: i64, ok: bool }{
        .{ .header = header, .iat = 940, .exp = 1060, .ok = true },
        .{ .header = header, .iat = 600, .exp = 1100, .ok = false },
        .{ .header = header, .iat = 1061, .exp = 1100, .ok = false },
        .{ .header = header, .iat = 900, .exp = 999, .ok = false },
        .{ .header = "{\"typ\":\"JWT\",\"alg\":\"ES256\",\"kid\":\"k1\"}", .iat = 940, .exp = 1060, .ok = false },
        .{ .header = "{\"typ\":\"atproto-client-attestation+jwt\",\"alg\":\"ES256\"}", .iat = 940, .exp = 1060, .ok = false },
    };
    for (cases) |case| {
        const payload = try std.fmt.allocPrint(a, "{{\"iss\":\"https://app.example\",\"sub\":\"https://app.example\",\"aud\":\"{s}\",\"jti\":\"j\",\"iat\":{d},\"exp\":{d}}}", .{ audience, case.iat, case.exp });
        const token = try zat.oauth.createJwt(a, case.header, payload, &keypair);
        if (parse(a, token, audience, 1000)) |_| {
            try std.testing.expect(case.ok);
        } else |_| try std.testing.expect(!case.ok);
    }
}