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

zat.dev/zat

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

0
0
726 lines · 31.8 KB Raw History
const std = @import("std");
const Did = @import("../syntax/did.zig").Did;
const Handle = @import("../syntax/handle.zig").Handle;
const Nsid = @import("../syntax/nsid.zig").Nsid;
const percent = @import("../syntax/percent.zig");

pub const Error = error{ InvalidScope, UnsupportedScope, OutOfMemory };
pub const RepoAction = enum { create, update, delete };
pub const RepoActions = std.EnumSet(RepoAction);
pub const AccountAttribute = enum { email, repo };
pub const AccountAction = enum { read, manage };
pub const IdentityAttribute = enum { handle, all };
pub const Transition = enum { generic, email, chat_bsky };
pub const Names = union(enum) { all, named: []const []const u8 };

pub const Include = struct {
    nsid: []const u8,
    audience: ?[]const u8 = null,
};

/// A concrete action to evaluate against one permission. Identifier strings are decoded.
pub const Requirement = union(enum) {
    repo: struct { collection: []const u8, action: RepoAction },
    blob: []const u8,
    /// The audience is a bare atproto DID or an absolute DID service reference.
    rpc: struct { method: []const u8, audience: []const u8 },
    account: struct { attribute: AccountAttribute, action: AccountAction },
    identity: IdentityAttribute,
};

/// Semantic inputs to init. Its slices can be discarded after initialization.
pub const Input = union(enum) {
    atproto,
    transition: Transition,
    repo: struct { collections: Names, actions: RepoActions = .full },
    blob: []const []const u8,
    rpc: union(enum) {
        any_audience: []const []const u8,
        service: struct { methods: Names, audience: []const u8 },
    },
    account: struct { attribute: AccountAttribute, action: AccountAction = .read },
    identity: IdentityAttribute,
    include: Include,
};

/// An owned, validated scope token. Call deinit once. Values borrowed from it
/// stay valid until deinit, including Permission handles.
pub const Scope = opaque {
    pub fn value(self: *const Scope) Value {
        const data = &storage(self).data;
        return switch (data.*) {
            .atproto => .atproto,
            .transition => |kind| .{ .transition = kind },
            .permission => .{ .permission = @ptrCast(&data.permission) },
            .include => |include| .{ .include = include },
        };
    }

    pub fn write(self: *const Scope, out: *std.Io.Writer) std.Io.Writer.Error!void {
        switch (self.value()) {
            .atproto => try out.writeAll("atproto"),
            .transition => |kind| try out.writeAll(switch (kind) {
                .generic => "transition:generic",
                .email => "transition:email",
                .chat_bsky => "transition:chat.bsky",
            }),
            .include => |include| {
                try out.writeAll("include:");
                try writeComponent(out, include.nsid);
                if (include.audience) |audience| try writeParam(out, "?aud=", audience);
            },
            .permission => |permission| try permission.write(out),
        }
    }

    pub fn deinit(self: *const Scope) void {
        var arena = storage(self).arena;
        arena.deinit();
    }

    fn storage(self: *const Scope) *const Storage {
        return @ptrCast(@alignCast(self));
    }
};

pub const Value = union(enum) {
    atproto,
    transition: Transition,
    permission: *const Permission,
    include: Include,
};

pub const Permission = opaque {
    /// Checks one granular clause, with no allocation or I/O.
    pub fn matches(self: *const Permission, requirement: Requirement) bool {
        return switch (requirement) {
            .repo => |request| switch (self.data().*) {
                .repo => |grant| grant.actions.contains(request.action) and matchesName(grant.collections, request.collection),
                else => false,
            },
            .blob => |mime| switch (self.data().*) {
                .blob => |accept| matchesMime(accept, mime),
                else => false,
            },
            .rpc => |request| switch (self.data().*) {
                .rpc => |grant| switch (grant) {
                    .any_audience => |methods| containsSorted(methods, request.method) and validAudience(request.audience, .did_or_service),
                    .service => |service| eql(service.audience, request.audience) and matchesName(service.methods, request.method),
                },
                else => false,
            },
            .account => |request| switch (self.data().*) {
                .account => |grant| grant.attribute == request.attribute and switch (request.action) {
                    .read => request.attribute == .email,
                    .manage => grant.action == .manage,
                },
                else => false,
            },
            .identity => |attribute| switch (self.data().*) {
                .identity => |grant| grant == attribute or grant == .all,
                else => false,
            },
        };
    }

    fn data(self: *const Permission) *const Grant {
        return @ptrCast(@alignCast(self));
    }

    fn write(self: *const Permission, out: *std.Io.Writer) std.Io.Writer.Error!void {
        switch (self.data().*) {
            .repo => |grant| {
                try writeNames(out, "repo", "collection", grant.collections);
                if (grant.actions.count() == RepoActions.len) return;
                var prefix: []const u8 = switch (grant.collections) {
                    .all => "?",
                    .named => |names| if (names.len == 1) "?" else "&",
                };
                var actions = grant.actions.iterator();
                while (actions.next()) |action| {
                    try out.writeAll(prefix);
                    try writeParam(out, "action=", @tagName(action));
                    prefix = "&";
                }
            },
            .blob => |accept| try writeNames(out, "blob", "accept", .{ .named = accept }),
            .rpc => |grant| {
                const methods: Names = switch (grant) {
                    .any_audience => |names| .{ .named = names },
                    .service => |service| service.methods,
                };
                try writeNames(out, "rpc", "lxm", methods);
                const prefix: []const u8 = switch (methods) {
                    .all => "?aud=",
                    .named => |names| if (names.len == 1) "?aud=" else "&aud=",
                };
                try writeParam(out, prefix, switch (grant) {
                    .any_audience => "*",
                    .service => |service| service.audience,
                });
            },
            .account => |grant| {
                try writeParam(out, "account:", @tagName(grant.attribute));
                if (grant.action == .manage) try out.writeAll("?action=manage");
            },
            .identity => |attribute| try out.writeAll(switch (attribute) {
                .handle => "identity:handle",
                .all => "identity:*",
            }),
        }
    }
};

const Grant = union(enum) {
    repo: struct { collections: Names, actions: RepoActions },
    blob: []const []const u8,
    rpc: @FieldType(Input, "rpc"),
    account: @FieldType(Input, "account"),
    identity: IdentityAttribute,
};

const Data = union(enum) {
    atproto,
    transition: Transition,
    permission: Grant,
    include: Include,
};

const Storage = struct { arena: std.heap.ArenaAllocator, data: Data };

pub fn init(allocator: std.mem.Allocator, input: Input) Error!*const Scope {
    var arena: std.heap.ArenaAllocator = .init(allocator);
    errdefer arena.deinit();
    return finish(&arena, input);
}

/// Parses one scope token after decoding the enclosing OAuth transport.
pub fn parse(allocator: std.mem.Allocator, wire: []const u8) Error!*const Scope {
    if (wire.len == 0) return error.InvalidScope;
    for (wire) |byte| {
        if (byte < 0x21 or byte > 0x7e or byte == '"' or byte == '\\') return error.InvalidScope;
    }
    var arena: std.heap.ArenaAllocator = .init(allocator);
    errdefer arena.deinit();
    return finish(&arena, try parseToken(arena.allocator(), wire));
}

fn finish(arena: *std.heap.ArenaAllocator, input: Input) Error!*const Scope {
    const allocator = arena.allocator();
    const owner = try allocator.create(Storage);
    const data: Data = switch (input) {
        .atproto => .atproto,
        .transition => |kind| .{ .transition = kind },
        .include => |include| blk: {
            if (Nsid.parse(include.nsid) == null) return error.InvalidScope;
            break :blk .{ .include = .{
                .nsid = try allocator.dupe(u8, include.nsid),
                .audience = if (include.audience) |audience| try ownedService(allocator, audience) else null,
            } };
        },
        .repo => |repo| blk: {
            if (repo.actions.count() == 0) return error.InvalidScope;
            break :blk .{ .permission = .{ .repo = .{
                .collections = try ownedNames(allocator, repo.collections),
                .actions = repo.actions,
            } } };
        },
        .blob => |accept| .{ .permission = .{ .blob = try ownedMime(allocator, accept) } },
        .rpc => |rpc| .{ .permission = .{ .rpc = switch (rpc) {
            .any_audience => |methods| .{ .any_audience = try ownedNsids(allocator, methods) },
            .service => |service| .{ .service = .{
                .methods = try ownedNames(allocator, service.methods),
                .audience = try ownedService(allocator, service.audience),
            } },
        } } },
        .account => |account| .{ .permission = .{ .account = account } },
        .identity => |attribute| .{ .permission = .{ .identity = attribute } },
    };
    owner.* = .{ .arena = arena.*, .data = data };
    return @ptrCast(owner);
}

fn eql(a: []const u8, b: []const u8) bool {
    return std.mem.eql(u8, a, b);
}

fn ownedNames(allocator: std.mem.Allocator, names: Names) Error!Names {
    return switch (names) {
        .all => .all,
        .named => |values| .{ .named = try ownedNsids(allocator, values) },
    };
}

fn ownedNsids(allocator: std.mem.Allocator, values: []const []const u8) Error![]const []const u8 {
    if (values.len == 0) return error.InvalidScope;
    const result = try allocator.alloc([]const u8, values.len);
    for (values, result) |value, *name| {
        if (Nsid.parse(value) == null) return error.InvalidScope;
        name.* = try allocator.dupe(u8, value);
    }
    return sortUnique(result);
}

fn sortUnique(values: [][]const u8) [][]const u8 {
    std.mem.sortUnstable([]const u8, values, {}, struct {
        fn lessThan(_: void, a: []const u8, b: []const u8) bool {
            return std.mem.order(u8, a, b) == .lt;
        }
    }.lessThan);
    var unique: usize = 0;
    for (values) |value| {
        if (unique != 0 and eql(value, values[unique - 1])) continue;
        values[unique] = value;
        unique += 1;
    }
    return values[0..unique];
}

fn containsSorted(values: []const []const u8, key: []const u8) bool {
    return std.sort.binarySearch([]const u8, values, key, struct {
        fn order(needle: []const u8, value: []const u8) std.math.Order {
            return std.mem.order(u8, needle, value);
        }
    }.order) != null;
}

fn matchesName(names: Names, name: []const u8) bool {
    return switch (names) {
        .all => Nsid.parse(name) != null,
        .named => |values| containsSorted(values, name),
    };
}

fn ownedService(allocator: std.mem.Allocator, audience: []const u8) Error![]const u8 {
    if (!validAudience(audience, .service)) return error.InvalidScope;
    return allocator.dupe(u8, audience);
}

fn validAudience(value: []const u8, kind: enum { service, did_or_service }) bool {
    const hash = std.mem.indexOfScalar(u8, value, '#');
    const did = Did.parse(value[0 .. hash orelse value.len]) orelse return false;
    if (!validServiceDid(did)) return false;
    const fragment = value[(hash orelse return kind == .did_or_service) + 1 ..];
    if (fragment.len == 0) return false;
    var i: usize = 0;
    while (i < fragment.len) : (i += 1) {
        const byte = fragment[i];
        if (byte == '%') {
            if (fragment.len - i < 3) return false;
            _ = std.fmt.charToDigit(fragment[i + 1], 16) catch return false;
            _ = std.fmt.charToDigit(fragment[i + 2], 16) catch return false;
            i += 2;
        } else if (!unreserved(byte) and std.mem.indexOfScalar(u8, "!$&'()*+,;=:@/?", byte) == null) {
            return false;
        }
    }
    return true;
}

fn validServiceDid(did: Did) bool {
    const id = did.identifier();
    switch (did.method()) {
        .plc => {
            if (id.len != 24) return false;
            for (id) |byte| {
                if (!(byte >= 'a' and byte <= 'z') and !(byte >= '2' and byte <= '7')) return false;
            }
            return true;
        },
        .web => {
            if (eql(id, "localhost")) return true;
            const local_prefix = "localhost%3A";
            if (id.len > local_prefix.len and std.ascii.eqlIgnoreCase(id[0..local_prefix.len], local_prefix)) {
                const port = id[local_prefix.len..];
                for (port) |byte| {
                    if (!std.ascii.isDigit(byte)) return false;
                }
                return (std.fmt.parseInt(u16, port, 10) catch return false) != 0;
            }
            const host = Handle.parse(id) orelse return false;
            return !host.hasDisallowedTld();
        },
        .other => return false,
    }
}

const max_media_name = 127;

fn validMediaName(name: []const u8) bool {
    if (name.len == 0 or name.len > max_media_name or !std.ascii.isAlphanumeric(name[0])) return false;
    for (name[1..]) |byte| {
        if (!std.ascii.isAlphanumeric(byte) and std.mem.indexOfScalar(u8, "!#$&-^_.+", byte) == null) return false;
    }
    return true;
}

fn validMime(value: []const u8, allow_wildcards: bool) bool {
    if (allow_wildcards and eql(value, "*/*")) return true;
    const slash = std.mem.indexOfScalar(u8, value, '/') orelse return false;
    const subtype = value[slash + 1 ..];
    return validMediaName(value[0..slash]) and
        (validMediaName(subtype) or (allow_wildcards and eql(subtype, "*")));
}

fn wildcardMime(buffer: *[max_media_name + 2]u8, mime: []const u8) []const u8 {
    const prefix_len = std.mem.indexOfScalar(u8, mime, '/').? + 1;
    @memcpy(buffer[0..prefix_len], mime[0..prefix_len]);
    buffer[prefix_len] = '*';
    return buffer[0 .. prefix_len + 1];
}

fn ownedMime(allocator: std.mem.Allocator, values: []const []const u8) Error![]const []const u8 {
    if (values.len == 0) return error.InvalidScope;
    var all = false;
    for (values) |value| {
        if (!validMime(value, true)) return error.InvalidScope;
        all = all or eql(value, "*/*");
    }
    if (all) return &.{"*/*"};

    const list = try allocator.alloc([]const u8, values.len);
    for (values, list) |value, *entry| {
        const lower = try allocator.alloc(u8, value.len);
        for (value, lower) |byte, *dest| dest.* = std.ascii.toLower(byte);
        entry.* = lower;
    }
    const sorted = sortUnique(list);
    var kept: usize = 0;
    var start: usize = 0;
    while (start < sorted.len) {
        const prefix = sorted[start][0 .. std.mem.indexOfScalar(u8, sorted[start], '/').? + 1];
        var wildcard: ?[]const u8 = null;
        var end = start;
        while (end < sorted.len and std.mem.startsWith(u8, sorted[end], prefix)) : (end += 1) {
            if (sorted[end].len == prefix.len + 1 and sorted[end][prefix.len] == '*') wildcard = sorted[end];
        }
        if (wildcard) |value| {
            list[kept] = value;
            kept += 1;
        } else {
            const group = sorted[start..end];
            std.mem.copyForwards([]const u8, list[kept..][0..group.len], group);
            kept += group.len;
        }
        start = end;
    }
    return list[0..kept];
}

fn matchesMime(accept: []const []const u8, mime: []const u8) bool {
    if (!validMime(mime, false)) return false;
    if (eql(accept[0], "*/*")) return true;
    var lower_buffer: [max_media_name * 2 + 1]u8 = undefined;
    const lower = lower_buffer[0..mime.len];
    for (mime, lower) |byte, *dest| dest.* = std.ascii.toLower(byte);
    var wildcard: [max_media_name + 2]u8 = undefined;
    return containsSorted(accept, lower) or containsSorted(accept, wildcardMime(&wildcard, lower));
}

fn unreserved(byte: u8) bool {
    return std.ascii.isAlphanumeric(byte) or std.mem.indexOfScalar(u8, "-._~", byte) != null;
}

fn writeComponent(out: *std.Io.Writer, value: []const u8) std.Io.Writer.Error!void {
    const hex = "0123456789ABCDEF";
    var start: usize = 0;
    for (value, 0..) |byte, i| {
        if (unreserved(byte) or byte == ':' or byte == '/' or byte == '*') continue;
        try out.writeAll(value[start..i]);
        try out.writeAll(&.{ '%', hex[byte >> 4], hex[byte & 15] });
        start = i + 1;
    }
    try out.writeAll(value[start..]);
}

fn writeParam(out: *std.Io.Writer, prefix: []const u8, value: []const u8) std.Io.Writer.Error!void {
    try out.writeAll(prefix);
    try writeComponent(out, value);
}

fn writeNames(out: *std.Io.Writer, resource: []const u8, parameter: []const u8, names: Names) std.Io.Writer.Error!void {
    try out.writeAll(resource);
    switch (names) {
        .all => try out.writeAll(":*"),
        .named => |values| {
            if (values.len == 1) return writeParam(out, ":", values[0]);
            for (values, 0..) |value, i| {
                try out.writeByte(if (i == 0) '?' else '&');
                try out.writeAll(parameter);
                try writeParam(out, "=", value);
            }
        },
    }
}

const Resource = enum {
    repo,
    blob,
    rpc,
    account,
    identity,
    include,
};

fn parseToken(allocator: std.mem.Allocator, wire: []const u8) Error!Input {
    if (eql(wire, "atproto")) return .atproto;
    if (eql(wire, "transition:generic")) return .{ .transition = .generic };
    if (eql(wire, "transition:email")) return .{ .transition = .email };
    if (eql(wire, "transition:chat.bsky")) return .{ .transition = .chat_bsky };

    const query_start = std.mem.indexOfScalar(u8, wire, '?') orelse wire.len;
    const base = wire[0..query_start];
    const colon = std.mem.indexOfScalar(u8, base, ':') orelse base.len;
    const kind = base[0..colon];
    if (kind.len == 0) return error.InvalidScope;
    for (kind) |byte| {
        if (!std.ascii.isAlphanumeric(byte) and byte != '-' and byte != '_' and byte != '.') return error.InvalidScope;
    }
    const resource = std.meta.stringToEnum(Resource, kind);
    const selector = if (resource) |known| switch (known) {
        .repo => "collection",
        .blob => "accept",
        .rpc => "lxm",
        .account, .identity => "attr",
        .include => "nsid",
    } else "";
    const positional = colon != base.len;
    var names: std.ArrayList([]const u8) = .empty;
    if (positional) try names.append(allocator, try decode(allocator, base[colon + 1 ..]));

    var audience: ?[]const u8 = null;
    var account_action: ?AccountAction = null;
    var actions: RepoActions = .empty;
    var params = std.mem.tokenizeScalar(u8, if (query_start == wire.len) "" else wire[query_start + 1 ..], '&');
    while (params.next()) |param| {
        const equals = std.mem.indexOfScalar(u8, param, '=') orelse return error.InvalidScope;
        const key = try decode(allocator, param[0..equals]);
        const value = try decode(allocator, param[equals + 1 ..]);
        const known = resource orelse continue;
        if (eql(key, selector)) {
            if (positional) return error.InvalidScope;
            try names.append(allocator, value);
        } else if (eql(key, "aud") and (known == .rpc or known == .include)) {
            if (audience != null) return error.InvalidScope;
            audience = value;
        } else if (eql(key, "action") and known == .repo) {
            actions.insert(std.meta.stringToEnum(RepoAction, value) orelse return error.InvalidScope);
        } else if (eql(key, "action") and known == .account) {
            if (account_action != null) return error.InvalidScope;
            account_action = std.meta.stringToEnum(AccountAction, value) orelse return error.InvalidScope;
        } else {
            return error.InvalidScope;
        }
    }

    const known = resource orelse {
        if (eql(kind, "atproto") or eql(kind, "transition")) return error.InvalidScope;
        return error.UnsupportedScope;
    };
    const values = names.items;
    if (values.len == 0) return error.InvalidScope;
    return switch (known) {
        .repo => .{ .repo = .{
            .collections = try parsedNames(values),
            .actions = if (actions.count() == 0) .full else actions,
        } },
        .blob => .{ .blob = values },
        .rpc => blk: {
            const aud = audience orelse return error.InvalidScope;
            const methods = try parsedNames(values);
            if (eql(aud, "*")) {
                if (methods == .all) return error.InvalidScope;
                break :blk .{ .rpc = .{ .any_audience = methods.named } };
            }
            break :blk .{ .rpc = .{ .service = .{ .methods = methods, .audience = aud } } };
        },
        .account => .{ .account = .{
            .attribute = std.meta.stringToEnum(AccountAttribute, try only(values)) orelse return error.InvalidScope,
            .action = account_action orelse .read,
        } },
        .identity => .{ .identity = blk: {
            const attribute = try only(values);
            if (eql(attribute, "*")) break :blk .all;
            if (eql(attribute, "handle")) break :blk .handle;
            return error.InvalidScope;
        } },
        .include => .{ .include = .{ .nsid = try only(values), .audience = audience } },
    };
}

fn parsedNames(values: []const []const u8) Error!Names {
    for (values) |value| {
        if (eql(value, "*")) {
            for (values) |candidate| {
                if (!eql(candidate, "*") and Nsid.parse(candidate) == null) return error.InvalidScope;
            }
            return .all;
        }
    }
    return .{ .named = values };
}

fn only(values: []const []const u8) Error![]const u8 {
    if (values.len != 1) return error.InvalidScope;
    return values[0];
}

fn decode(allocator: std.mem.Allocator, bytes: []const u8) Error![]const u8 {
    if (bytes.len == 0) return error.InvalidScope;
    if (std.mem.indexOfScalar(u8, bytes, '%') == null) return bytes;
    const decoded = percent.decodeAlloc(allocator, bytes) catch |err| switch (err) {
        error.InvalidPercentEncoding => return error.InvalidScope,
        error.OutOfMemory => return error.OutOfMemory,
    };
    for (decoded) |byte| {
        if (byte < 0x21 or byte > 0x7e) return error.InvalidScope;
    }
    return decoded;
}

fn expectCanonical(wire: []const u8, expected: []const u8) !void {
    const allocator = std.testing.allocator;
    const scope = try parse(allocator, wire);
    defer scope.deinit();
    var output: std.Io.Writer.Allocating = .init(allocator);
    defer output.deinit();
    try scope.write(&output.writer);
    try std.testing.expectEqualStrings(expected, output.written());
}

test "permission scope wire values canonicalize" {
    for ([_][2][]const u8{
        .{ "atproto", "atproto" },
        .{ "transition:chat.bsky", "transition:chat.bsky" },
        .{ "identity:*?", "identity:*" },
        .{ "identity?attr=handle", "identity:handle" },
        .{ "account?attr=email&action=read", "account:email" },
        .{ "account?attr=email&action=manage", "account:email?action=manage" },
        .{ "repo?collection=app.example.post&action=%63reate", "repo:app.example.post?action=create" },
        .{ "repo?collection=app.example.post&collection=app.example.like&action=update&action=create", "repo?collection=app.example.like&collection=app.example.post&action=create&action=update" },
        .{ "blob?accept=IMAGE/png&accept=image/!invalid", "" },
        .{ "blob?accept=image/png&accept=image/*&accept=audio/*&accept=video/mp4", "blob?accept=audio/*&accept=image/*&accept=video/mp4" },
        .{ "blob?accept=image/svg+xml", "blob:image/svg%2Bxml" },
        .{ "rpc?lxm=*&aud=did%3Aweb%3Aapi.example.com%23svc_appview", "rpc:*?aud=did:web:api.example.com%23svc_appview" },
        .{ "rpc:app.example.getThing?aud=did:web:localhost%253A8443%23svc_appview", "rpc:app.example.getThing?aud=did:web:localhost%253A8443%23svc_appview" },
        .{ "include:app.example.authFull?aud=did:web:api.example.com%23svc_chat", "include:app.example.authFull?aud=did:web:api.example.com%23svc_chat" },
    }) |pair| {
        if (pair[1].len == 0) {
            try std.testing.expectError(error.InvalidScope, parse(std.testing.allocator, pair[0]));
        } else {
            try expectCanonical(pair[0], pair[1]);
        }
    }
}

test "permission scope malformed values cannot become wildcard or default grants" {
    for ([_][]const u8{
        "",                    "repo",                                     "repo:",                                                "repo:app.example.*",                                      "repo:*?collection=app.example.post",
        "repo:*?restrict=new", "repo:*?action=",                           "repo:*?action=%2563reate",                             "blob",                                                    "blob:",
        "blob:*/png",          "blob:im*ge/*",                             "blob:image/%00",                                       "blob?accept=*/*&accept=image/%00",                        "blob:image/png;text=plain",
        "rpc:*?aud=%2A",       "rpc?lxm=*&lxm=app.example.getThing&aud=*", "rpc:app.example.getThing?aud=did:web:api.example.com", "rpc:app.example.getThing?aud=did:web:api.example.com%23", "rpc:app.example.getThing?aud=did:web:api.example.com%23svc&aud=*",
        "account:*",           "account:",                                 "account:status",                                       "account:email?action=read&action=manage",                 "identity:*?unknown=value",
        "identity:",           "include:app.example.auth?aud=*",           "include:app.example.auth?aud=%+A",                     "include:app.example.auth?aud=%",                          "atproto?",
        "transition:unknown",  "repo:app.example.post blob:image/png",
    }) |wire| {
        try std.testing.expectError(error.InvalidScope, parse(std.testing.allocator, wire));
    }
    try std.testing.expectError(error.UnsupportedScope, parse(std.testing.allocator, "space:app.example.space?authority=self"));
    try std.testing.expectError(error.InvalidScope, parse(std.testing.allocator, "space:app.example.space?authority=%GG"));
}

test "permission scope matches concrete repo, blob, RPC, account and identity requirements" {
    const allocator = std.testing.allocator;
    const repo = try parse(allocator, "repo:app.example.post?action=create");
    defer repo.deinit();
    try std.testing.expect(repo.value().permission.matches(.{ .repo = .{ .collection = "app.example.post", .action = .create } }));
    try std.testing.expect(!repo.value().permission.matches(.{ .repo = .{ .collection = "app.example.post", .action = .delete } }));
    try std.testing.expect(!repo.value().permission.matches(.{ .repo = .{ .collection = "app.example.like", .action = .create } }));

    const blob = try parse(allocator, "blob:image/*");
    defer blob.deinit();
    try std.testing.expect(blob.value().permission.matches(.{ .blob = "IMAGE/SVG+XML" }));
    try std.testing.expect(!blob.value().permission.matches(.{ .blob = "image/*" }));
    try std.testing.expect(!blob.value().permission.matches(.{ .blob = "images/png" }));

    const rpc = try parse(allocator, "rpc:*?aud=did:web:api.example.com%23svc_appview");
    defer rpc.deinit();
    try std.testing.expect(rpc.value().permission.matches(.{ .rpc = .{ .method = "app.example.getThing", .audience = "did:web:api.example.com#svc_appview" } }));
    try std.testing.expect(!rpc.value().permission.matches(.{ .rpc = .{ .method = "app.example.getThing", .audience = "did:web:api.example.com#svc_chat" } }));
    try std.testing.expect(!rpc.value().permission.matches(.{ .rpc = .{ .method = "*", .audience = "did:web:api.example.com#svc_appview" } }));

    const email = try parse(allocator, "account:email");
    defer email.deinit();
    try std.testing.expect(email.value().permission.matches(.{ .account = .{ .attribute = .email, .action = .read } }));
    try std.testing.expect(!email.value().permission.matches(.{ .account = .{ .attribute = .email, .action = .manage } }));
    const management = try parse(allocator, "account:email?action=manage");
    defer management.deinit();
    try std.testing.expect(management.value().permission.matches(.{ .account = .{ .attribute = .email, .action = .read } }));
    try std.testing.expect(management.value().permission.matches(.{ .account = .{ .attribute = .email, .action = .manage } }));
    try std.testing.expect(!management.value().permission.matches(.{ .account = .{ .attribute = .repo, .action = .manage } }));

    const identity = try parse(allocator, "identity:*");
    defer identity.deinit();
    try std.testing.expect(identity.value().permission.matches(.{ .identity = .handle }));
    try std.testing.expect(!identity.value().permission.matches(.{ .blob = "image/png" }));
}

test "permission scope keeps wildcard requests distinct from specific service grants" {
    const allocator = std.testing.allocator;
    var lines = std.mem.tokenizeScalar(u8, @embedFile("rpc_match_vectors.tsv"), '\n');
    while (lines.next()) |line| {
        var fields = std.mem.splitScalar(u8, line, '\t');
        const scope = try parse(allocator, fields.next().?);
        defer scope.deinit();
        const method = fields.next().?;
        const audience = fields.next().?;
        const expected = eql(fields.next().?, "allow");
        const actual = scope.value().permission.matches(.{ .rpc = .{ .method = method, .audience = audience } });
        errdefer std.debug.print("RPC vector failed: {s}\n", .{line});
        try std.testing.expectEqual(expected, actual);
    }

    try std.testing.expectError(error.InvalidScope, parse(allocator, "rpc:app.example.getThing?aud=did:web:api.example.com"));
    try std.testing.expectError(error.InvalidScope, parse(allocator, "include:app.example.auth?aud=did:web:api.example.com"));
    try std.testing.expectError(error.InvalidScope, init(allocator, .{ .rpc = .{ .service = .{
        .methods = .all,
        .audience = "did:web:api.example.com",
    } } }));
}

fn exerciseOwnership(allocator: std.mem.Allocator) !void {
    var bytes = "rpc?lxm=app.example.foo&lxm=app.example.bar&aud=did:web:api.example.com%23svc".*;
    const scope = try parse(allocator, &bytes);
    defer scope.deinit();
    @memset(&bytes, 0);
    var output_buffer: [128]u8 = undefined;
    var output: std.Io.Writer = .fixed(&output_buffer);
    try scope.write(&output);
    try std.testing.expectEqualStrings("rpc?lxm=app.example.bar&lxm=app.example.foo&aud=did:web:api.example.com%23svc", output.buffered());

    const from_fields = try init(allocator, .{ .repo = .{ .collections = .{ .named = &.{"app.example.post"} } } });
    defer from_fields.deinit();
    var fixed: [3]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&fixed);
    try std.testing.expectError(error.WriteFailed, from_fields.write(&writer));
}

test "permission scope owns bytes and cleans up on allocation failure" {
    try std.testing.checkAllAllocationFailures(std.testing.allocator, exerciseOwnership, .{});
    try std.testing.expectError(error.InvalidScope, init(std.testing.allocator, .{ .repo = .{ .collections = .{ .named = &.{} } } }));
    try std.testing.expectError(error.InvalidScope, init(std.testing.allocator, .{ .rpc = .{ .any_audience = &.{"*"} } }));
}

test "permission scope agrees with the reviewed reference wire corpus" {
    var lines = std.mem.tokenizeScalar(u8, @embedFile("permission_vectors.tsv"), '\n');
    while (lines.next()) |line| {
        var fields = std.mem.splitScalar(u8, line, '\t');
        const wire = fields.next().?;
        const expected = fields.next().?;
        if (eql(expected, "-")) {
            try std.testing.expectError(error.InvalidScope, parse(std.testing.allocator, wire));
        } else {
            try expectCanonical(wire, expected);
        }
    }
}