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

zat.dev/zat

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

0
0
331 lines · 16.8 KB Raw History
const std = @import("std");
const hegel = @import("hegel");
const scopes = @import("zat").oauth.permissions;

const collections = [_][]const u8{ "app.example.post", "app.example.like", "app.example.profile" };
const actions = [_]scopes.RepoAction{ .create, .update, .delete };
const methods = [_][]const u8{ "app.example.getPost", "app.example.newPost", "app.example.deletePost" };
const audiences = [_][]const u8{
    "did:web:api.example.com#svc_appview",
    "did:web:api.example.com#svc_chat",
    "did:web:localhost%3A8443#svc_chat",
};
const mime_types = [_][]const u8{ "image/png", "image/svg+xml", "video/mp4", "text/html", "imageevil/png" };

fn selected(mask: u8, i: usize) bool {
    return mask & (@as(u8, 1) << @intCast(i)) != 0;
}

fn format(scope: *const scopes.Scope, a: std.mem.Allocator) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(a);
    errdefer out.deinit();
    try scope.write(&out.writer);
    return out.toOwnedSlice();
}

fn assertCanonical(a: std.mem.Allocator, scope: *const scopes.Scope, case: *hegel.TestCase) !*const scopes.Scope {
    const wire = try format(scope, a);
    case.note("canonical scope {s}", .{wire});
    const reparsed = try scopes.parse(a, wire);
    if (!std.mem.eql(u8, wire, try format(reparsed, a))) return case.fail("canonical scope encoding changed after parsing");
    return reparsed;
}

fn repoRelation(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const masks = [2]u8{ try case.int(u8, 1, 8), try case.int(u8, 1, 8) };
    const action_masks = [2]u8{ try case.int(u8, 1, 7), try case.int(u8, 1, 7) };
    case.note("repo selectors {any}, actions {any}", .{ masks, action_masks });
    var permissions: [2]*const scopes.Permission = undefined;
    for (masks, action_masks, &permissions) |mask, action_mask, *permission| {
        var names: std.ArrayList([]const u8) = .empty;
        for (collections, 0..) |_, i| {
            const index = collections.len - 1 - i;
            if (selected(mask, index)) try names.append(a, collections[index]);
        }
        var repo_actions: scopes.RepoActions = .empty;
        for (actions, 0..) |action, i| {
            if (selected(action_mask, i)) repo_actions.insert(action);
        }
        const scope = try scopes.init(a, .{ .repo = .{
            .collections = if (mask == 8) .all else .{ .named = names.items },
            .actions = repo_actions,
        } });
        permission.* = (try assertCanonical(a, scope, case)).value().permission;
    }
    for (collections, 0..) |collection, i| {
        for (actions, 0..) |action, j| {
            const requirement: scopes.Requirement = .{ .repo = .{ .collection = collection, .action = action } };
            const expected_first = (masks[0] == 8 or selected(masks[0], i)) and selected(action_masks[0], j);
            const expected_second = (masks[1] == 8 or selected(masks[1], i)) and selected(action_masks[1], j);
            if (permissions[0].matches(requirement) != expected_first or
                permissions[1].matches(requirement) != expected_second) return case.fail("repo grant diverged from collection/action relation");
        }
    }
    case.event("repo relation checked");
}

fn rpcRelation(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const audience = try case.int(usize, 0, audiences.len);
    const mask = try case.int(u8, 1, @as(u8, if (audience == audiences.len) 7 else 8));
    const audiences_wire = [_][]const u8{
        "did:web:api.example.com%23svc_appview",
        "did%3Aweb%3Aapi.example.com%23svc_chat",
        "did:web:localhost%253A8443%23svc_chat",
        "%2A",
    };
    var wire: std.Io.Writer.Allocating = .init(a);
    try wire.writer.print("rpc?aud={s}", .{audiences_wire[audience]});
    if (mask == 8) {
        try wire.writer.writeAll("&lxm=%2A");
    } else {
        for (methods, 0..) |method, index| {
            if (selected(mask, index)) try wire.writer.print("&lxm={s}", .{method});
        }
    }
    case.note("rpc scope {s}", .{wire.written()});
    const scope = try scopes.parse(a, wire.written());
    const reparsed = try assertCanonical(a, scope, case);
    const bare_dids = [_][]const u8{ "did:web:api.example.com", "did:plc:ewvi7nxzyoun6zhxrhs64oiz", "did:web:localhost%3A8443" };
    const invalid = [_][]const u8{ "*", "did:key:123", "did:plc:short", "did:web:api.example.com#", "did:web:api.example.com#svc#other" };
    const targets = audiences ++ bare_dids ++ invalid;
    if (audience == audiences.len) case.event("wildcard checked against bare and malformed audiences");
    if (audience < audiences.len) case.event("specific service checked against sibling and bare audiences");
    for (methods, 0..) |method, i| {
        for (targets, 0..) |target, j| {
            const valid_target = j < audiences.len + bare_dids.len;
            const expected = (mask == 8 or selected(mask, i)) and valid_target and
                (audience == audiences.len or audience == j);
            const requirement: scopes.Requirement = .{ .rpc = .{ .method = method, .audience = target } };
            if (scope.value().permission.matches(requirement) != expected or
                reparsed.value().permission.matches(requirement) != expected)
            {
                case.note("RPC method={s} audience={s} expected={}", .{ method, target, expected });
                return case.fail("RPC audience/method relation changed");
            }
        }
    }
    if (audience == 2) case.event("nested DID escape checked");
    case.event("rpc relation checked");
}

fn blobRelation(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const mask = try case.int(u8, 1, 63);
    const patterns = [_][]const u8{ "IMAGE/*", "image/png", "image/svg+xml", "video/mp4", "text/html", "*/*" };
    var wire: std.Io.Writer.Allocating = .init(a);
    try wire.writer.writeAll("blob");
    var separator: u8 = '?';
    for (patterns, 0..) |pattern, i| {
        if (!selected(mask, i)) continue;
        try wire.writer.print("{c}accept={s}", .{ separator, pattern });
        separator = '&';
    }
    const scope = try scopes.parse(a, wire.written());
    const reparsed = try assertCanonical(a, scope, case);
    for (mime_types, 0..) |mime, i| {
        const expected = selected(mask, 5) or (i < 2 and selected(mask, 0)) or (i < 4 and selected(mask, i + 1));
        const requirement: scopes.Requirement = .{ .blob = mime };
        if (scope.value().permission.matches(requirement) != expected or
            reparsed.value().permission.matches(requirement) != expected) return case.fail("blob accept changed the media relation");
    }
    if (selected(mask, 0) and selected(mask, 1)) case.event("redundant allow checked");
    case.event("blob relation checked");
}

fn accountIdentity(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const attr = try case.int(usize, 0, 1);
    const action = try case.int(usize, 0, 2);
    const auth = [_][]const u8{ "email", "repo" };
    const attrs = [_]scopes.AccountAttribute{ .email, .repo };
    const suffixes = [_][]const u8{ "", "&action=read", "&action=manage" };
    const account = try scopes.parse(a, try std.fmt.allocPrint(a, "account?attr={s}{s}", .{ auth[attr], suffixes[action] }));
    const permission = (try assertCanonical(a, account, case)).value().permission;
    for (attrs, 0..) |attribute, i| {
        if (permission.matches(.{ .account = .{ .attribute = attribute, .action = .read } }) != (attr == i and i == 0) or
            permission.matches(.{ .account = .{ .attribute = attribute, .action = .manage } }) != (attr == i and action == 2)) return case.fail("account action or attribute widened");
    }
    const all = try case.boolean();
    const identity = try scopes.parse(a, if (all) "identity:*?" else "identity?attr=handle");
    const ident = (try assertCanonical(a, identity, case)).value().permission;
    if (!ident.matches(.{ .identity = .handle }) or ident.matches(.{ .identity = .all }) != all) return case.fail("identity selector widened");
    if (action == 0) case.event("account default checked");
}

const Rejection = enum {
    unknown_attenuator,
    duplicate_singleton,
    positional_and_named,
    escaped_delimiter,
    malformed_escape,
    double_escape,
    double_rpc_wildcard,
    bare_scope_audience,
    invalid_wildcard_companion,
};

const Mutation = struct { valid: []const u8, malformed: []const u8 };

fn malformedMutation(a: std.mem.Allocator, case: *hegel.TestCase, kind: Rejection) !Mutation {
    const id = try case.int(u16, 0, 65535);
    const collection = try std.fmt.allocPrint(a, "app.example.record{d}", .{id});
    const alternate = try case.boolean();
    const escaped_aud = "did:web:api.example.com%23svc";
    return switch (kind) {
        .unknown_attenuator => blk: {
            const forms = [_][]const u8{
                "repo:app.example.post?action=create",
                "blob?accept=image/png",
                "account:email?action=read",
                "identity?attr=handle",
                "rpc:app.example.getPost?aud=*",
                "include:app.example.auth?aud=" ++ escaped_aud,
            };
            const valid = forms[try case.int(usize, 0, forms.len - 1)];
            const field = if (alternate) "%66uture" else "future";
            break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}{d}=narrower", .{ valid, field, id }) };
        },
        .duplicate_singleton => blk: {
            const fields = [_]struct { prefix: []const u8, key: []const u8, first: []const u8, second: []const u8 }{
                .{ .prefix = "rpc:app.example.getPost", .key = "aud", .first = escaped_aud, .second = "*" },
                .{ .prefix = "include:app.example.auth", .key = "aud", .first = escaped_aud, .second = "did:web:other.example.com%23svc" },
                .{ .prefix = "account:email", .key = "action", .first = "read", .second = "manage" },
                .{ .prefix = "identity", .key = "attr", .first = "handle", .second = "*" },
            };
            const field = fields[try case.int(usize, 0, fields.len - 1)];
            const fallback = if (try case.boolean()) field.first else field.second;
            const first = if (alternate) fallback else field.first;
            const second = if (alternate) field.first else fallback;
            const alias = try std.fmt.allocPrint(a, "%{X:0>2}{s}", .{ field.key[0], field.key[1..] });
            const key = if (try case.boolean()) alias else field.key;
            const valid = try std.fmt.allocPrint(a, "{s}?{s}={s}", .{ field.prefix, field.key, first });
            break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}={s}", .{ valid, key, second }) };
        },
        .positional_and_named => blk: {
            const valid = try std.fmt.allocPrint(a, "repo:{s}?action=create", .{collection});
            const key = if (alternate) "%63ollection" else "collection";
            const selector = if (try case.boolean()) collection else "*";
            break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}={s}", .{ valid, key, selector }) };
        },
        .escaped_delimiter, .malformed_escape, .double_escape => blk: {
            const prefix = try std.fmt.allocPrint(a, "repo?collection={s}&action=", .{collection});
            const suffix = switch (kind) {
                .escaped_delimiter => if (alternate) "create%26action%3Ddelete" else "create%26action=update",
                .malformed_escape => bad: {
                    const escapes = [_][]const u8{ "%", "%6", "%+A", "%-0", "%G1", "%1G" };
                    break :bad escapes[try case.int(usize, 0, escapes.len - 1)];
                },
                .double_escape => if (alternate) "%2563reate" else "cre%2561te",
                else => unreachable,
            };
            break :blk .{
                .valid = try std.fmt.allocPrint(a, "{s}%63reate", .{prefix}),
                .malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, suffix }),
            };
        },
        .double_rpc_wildcard => blk: {
            const selector = if (alternate) "rpc:*?aud=" else "rpc?lxm=%2a&aud=";
            const wildcard = if (try case.boolean()) "*" else "%2A";
            break :blk .{
                .valid = try std.fmt.allocPrint(a, "{s}{s}{d}", .{ selector, escaped_aud, id }),
                .malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ selector, wildcard }),
            };
        },
        .bare_scope_audience => blk: {
            const prefix = if (alternate) "rpc:app.example.getPost?aud=" else "include:app.example.auth?aud=";
            const did = try std.fmt.allocPrint(a, "did:web:api{d}.example.com", .{id});
            break :blk .{
                .valid = try std.fmt.allocPrint(a, "{s}{s}%23svc", .{ prefix, did }),
                .malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, did }),
            };
        },
        .invalid_wildcard_companion => blk: {
            const wildcard = if (alternate) "*" else "%2a";
            const key = if (try case.boolean()) "%63ollection" else "collection";
            const prefix = try std.fmt.allocPrint(a, "repo?collection={s}&{s}=", .{ wildcard, key });
            const bad = if (try case.boolean()) "app.example.partial%2A" else "invalid";
            break :blk .{
                .valid = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, collection }),
                .malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, bad }),
            };
        },
    };
}

fn invalidScopes(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const kinds = std.enums.values(Rejection);
    const kind = kinds[try case.int(usize, 0, kinds.len - 1)];
    const mutation = try malformedMutation(allocator, case, kind);
    case.note("{s}: valid={s}, malformed={s}", .{ @tagName(kind), mutation.valid, mutation.malformed });
    const valid = try scopes.parse(allocator, mutation.valid);
    defer valid.deinit();

    switch (kind) {
        inline else => |family| case.event(@tagName(family)),
    }
    if (scopes.parse(allocator, mutation.malformed)) |scope| {
        defer scope.deinit();
        return case.fail("a malformed mutation of a valid scope was accepted");
    } else |err| switch (err) {
        error.InvalidScope => {},
        else => return err,
    }
}

fn wireAliases(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const id = try case.int(u16, 0, 65535);
    const mime = try std.fmt.allocPrint(a, "image/x{d}+json", .{id});
    const mixed = try std.fmt.allocPrint(a, "IMAGE/X{d}+JSON", .{id});
    const raw = try std.fmt.allocPrint(a, "blob?accept={s}", .{mixed});
    const escaped = try std.fmt.allocPrint(a, "blob:image/x{d}%2bjson", .{id});
    const duplicate = try std.fmt.allocPrint(a, "blob?accept={s}&accept={s}", .{ mixed, mime });
    const expected = try std.fmt.allocPrint(a, "blob:image/x{d}%2Bjson", .{id});
    for ([_][]const u8{ raw, escaped, duplicate }) |wire| {
        const scope = try scopes.parse(a, wire);
        if (!std.mem.eql(u8, expected, try format(scope, a))) return case.fail("wire aliases yielded different canonical bytes");
        if (!scope.value().permission.matches(.{ .blob = mime })) return case.fail("wire alias lost the literal plus");
    }
    case.event("equivalent wire spellings checked");
}

fn arbitraryBytes(_: void, case: *hegel.TestCase) !void {
    var buffer: [768]u8 = undefined;
    const bytes = try case.bytes(&buffer, 0, buffer.len);
    case.event("arbitrary bytes checked");
    const a = std.heap.page_allocator;
    if (scopes.parse(a, bytes)) |scope| {
        defer scope.deinit();
        var arena: std.heap.ArenaAllocator = .init(a);
        defer arena.deinit();
        _ = try assertCanonical(arena.allocator(), scope, case);
    } else |err| switch (err) {
        error.InvalidScope, error.UnsupportedScope => {},
        error.OutOfMemory => return err,
    }
}

pub fn main() !void {
    try hegel.run(.{ .key = "permission-repo" }, {}, repoRelation);
    try hegel.run(.{ .key = "permission-rpc" }, {}, rpcRelation);
    try hegel.run(.{ .key = "permission-blob" }, {}, blobRelation);
    try hegel.run(.{ .key = "permission-account-identity" }, {}, accountIdentity);
    try hegel.run(.{ .key = "permission-rejection" }, {}, invalidScopes);
    try hegel.run(.{ .key = "permission-wire-aliases" }, {}, wireAliases);
    try hegel.run(.{ .key = "permission-arbitrary-bytes" }, {}, arbitraryBytes);
}