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

zat.dev/zds

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

0
0
759 lines · 37.7 KB Raw History
const std = @import("std");
const zat = @import("zat");
const percent = zat.percent;
const permissions = zat.oauth.permissions;

pub const RepoAction = enum { create, update, delete };
pub const SpaceAction = enum { read_self, read, create, update, delete, manage_create, manage_update, manage_delete };
pub const AccountAction = enum { read, manage };
pub const AccountAttr = enum { email, repo, status, wildcard };
pub const IdentityAttr = enum { handle, wildcard };

pub fn oauthNeedsGranularCheck(maybe_scope: ?[]const u8) bool {
    const scope_text = maybe_scope orelse return false;
    return !std.mem.eql(u8, scope_text, "com.atproto.access") and
        !std.mem.eql(u8, scope_text, "atproto");
}

pub fn repoAllows(maybe_scope: ?[]const u8, action: RepoAction, collection: []const u8) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        const repo = RepoScope.parse(scope) orelse continue;
        if (repo.allows(action, collection)) return true;
    }
    return false;
}

pub fn blobAllows(maybe_scope: ?[]const u8, mime_type: []const u8) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        const blob = BlobScope.parse(scope) orelse continue;
        if (blob.allows(mime_type)) return true;
    }
    return false;
}

pub fn rpcAllows(maybe_scope: ?[]const u8, aud: []const u8, lxm: []const u8) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        if (!std.mem.startsWith(u8, scope, "rpc:") and !std.mem.startsWith(u8, scope, "rpc?")) continue;
        if (rpcScopeMatches(scope, aud, lxm)) return true;
    }
    return false;
}

pub fn spaceAllows(
    maybe_scope: ?[]const u8,
    action: SpaceAction,
    space_type: []const u8,
    did: []const u8,
    skey: []const u8,
    collection: ?[]const u8,
) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scope_iter = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scope_iter.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        if (!isSpaceScope(scope)) continue;
        if (spaceScopeMatches(scope, action, space_type, did, skey, collection)) return true;
    }
    return false;
}

pub fn accountAllows(maybe_scope: ?[]const u8, attr: AccountAttr, action: AccountAction) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        if (!std.mem.startsWith(u8, scope, "account")) continue;
        if (accountScopeMatches(scope, attr, action)) return true;
    }
    return false;
}

pub fn identityAllows(maybe_scope: ?[]const u8, attr: IdentityAttr) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        if (std.mem.eql(u8, scope, "transition:generic")) return true;
        if (!std.mem.startsWith(u8, scope, "identity")) continue;
        if (identityScopeMatches(scope, attr)) return true;
    }
    return false;
}

pub fn hasFullAccess(maybe_scope: ?[]const u8) bool {
    if (!oauthNeedsGranularCheck(maybe_scope)) return true;
    var scopes = std.mem.splitScalar(u8, maybe_scope.?, ' ');
    while (scopes.next()) |scope| {
        if (std.mem.eql(u8, scope, "atproto") or std.mem.eql(u8, scope, "transition:generic")) return true;
    }
    return false;
}

fn accountScopeMatches(scope: []const u8, attr: AccountAttr, action: AccountAction) bool {
    const query_start = std.mem.indexOfScalar(u8, scope, '?');
    const base = if (query_start) |idx| scope[0..idx] else scope;
    if (!accountAttrMatches(base, attr)) return false;
    if (query_start == null) return true;

    var saw_action = false;
    var params = std.mem.splitScalar(u8, scope[query_start.? + 1 ..], '&');
    while (params.next()) |param| {
        if (!std.mem.startsWith(u8, param, "action=")) continue;
        saw_action = true;
        if (std.mem.eql(u8, param["action=".len..], accountActionName(action))) return true;
    }
    return !saw_action;
}

fn accountAttrMatches(base: []const u8, attr: AccountAttr) bool {
    if (std.mem.eql(u8, base, "account") or std.mem.eql(u8, base, "account:") or std.mem.eql(u8, base, "account:*")) return true;
    if (!std.mem.startsWith(u8, base, "account:")) return false;
    const allowed = base["account:".len..];
    if (attr == .wildcard) return std.mem.eql(u8, allowed, "*");
    return std.mem.eql(u8, allowed, accountAttrName(attr));
}

fn accountActionName(action: AccountAction) []const u8 {
    return switch (action) {
        .read => "read",
        .manage => "manage",
    };
}

fn accountAttrName(attr: AccountAttr) []const u8 {
    return switch (attr) {
        .email => "email",
        .repo => "repo",
        .status => "status",
        .wildcard => "*",
    };
}

fn identityScopeMatches(scope: []const u8, attr: IdentityAttr) bool {
    const query_start = std.mem.indexOfScalar(u8, scope, '?');
    const base = if (query_start) |idx| scope[0..idx] else scope;
    if (std.mem.eql(u8, base, "identity") or std.mem.eql(u8, base, "identity:") or std.mem.eql(u8, base, "identity:*")) return true;
    if (!std.mem.startsWith(u8, base, "identity:")) return false;
    const allowed = base["identity:".len..];
    return switch (attr) {
        .handle => std.mem.eql(u8, allowed, "handle"),
        .wildcard => false,
    };
}

/// Splits `<resource>:<positional>?<query>` or `<resource>?<query>`; null for
/// any other shape, including a bare `<resource>`.
fn splitScope(scope: []const u8, resource: []const u8) ?struct { positional: ?[]const u8, query: []const u8 } {
    if (!std.mem.startsWith(u8, scope, resource)) return null;
    const rest = scope[resource.len..];
    if (rest.len == 0) return null;
    const query_start = std.mem.indexOfScalar(u8, rest, '?');
    return switch (rest[0]) {
        ':' => .{ .positional = rest[1 .. query_start orelse rest.len], .query = if (query_start) |idx| rest[idx + 1 ..] else "" },
        '?' => .{ .positional = null, .query = rest[1..] },
        else => null,
    };
}

/// A `repo` permission in the reference's grammar (@atproto/oauth-scopes
/// RepoPermission): one or more collections, each `*` or an exact NSID, given
/// positionally or as `collection` parameters but not both; optional `action`
/// parameters, each create, update or delete; no other parameters. A scope
/// outside it grants nothing, and sign-in refuses it.
pub const RepoScope = struct {
    positional: ?[]const u8,
    query: []const u8,
    any_action: bool,

    pub fn parse(scope: []const u8) ?RepoScope {
        const parts = splitScope(scope, "repo") orelse return null;
        if (parts.positional) |collection| if (!validNsidOrWildcard(collection)) return null;
        var collections: usize = 0;
        var actions: usize = 0;
        var params = std.mem.tokenizeScalar(u8, parts.query, '&');
        while (params.next()) |param| {
            if (std.mem.startsWith(u8, param, "collection=")) {
                if (!validNsidOrWildcard(param["collection=".len..])) return null;
                collections += 1;
            } else if (std.mem.startsWith(u8, param, "action=")) {
                if (repoActionFromName(param["action=".len..]) == null) return null;
                actions += 1;
            } else return null;
        }
        if ((parts.positional == null) == (collections == 0)) return null;
        return .{ .positional = parts.positional, .query = parts.query, .any_action = actions == 0 };
    }

    pub fn allows(self: RepoScope, action: RepoAction, collection: []const u8) bool {
        return self.allowsAction(action) and self.allowsCollection(collection);
    }

    fn allowsAction(self: RepoScope, action: RepoAction) bool {
        if (self.any_action) return true;
        var params = std.mem.tokenizeScalar(u8, self.query, '&');
        while (params.next()) |param| {
            if (!std.mem.startsWith(u8, param, "action=")) continue;
            if (repoActionFromName(param["action=".len..]) == action) return true;
        }
        return false;
    }

    fn allowsCollection(self: RepoScope, collection: []const u8) bool {
        if (self.positional) |allowed| return isWildcard(allowed) or percent.decodedEql(allowed, collection);
        var params = std.mem.tokenizeScalar(u8, self.query, '&');
        while (params.next()) |param| {
            if (!std.mem.startsWith(u8, param, "collection=")) continue;
            const allowed = param["collection=".len..];
            if (isWildcard(allowed) or percent.decodedEql(allowed, collection)) return true;
        }
        return false;
    }
};

fn repoActionFromName(name: []const u8) ?RepoAction {
    inline for (.{ RepoAction.create, RepoAction.update, RepoAction.delete }) |action| {
        if (percent.decodedEql(name, repoActionName(action))) return action;
    }
    return null;
}

fn repoActionName(action: RepoAction) []const u8 {
    return switch (action) {
        .create => "create",
        .update => "update",
        .delete => "delete",
    };
}

/// A `blob` permission in the reference's grammar (@atproto/oauth-scopes
/// BlobPermission): one or more accepted MIME types, `*/*`, `type/*` or an
/// exact `type/subtype`, given positionally or as `accept` parameters but not
/// both; no other parameters. A scope outside it grants nothing, and sign-in
/// refuses it.
pub const BlobScope = struct {
    positional: ?[]const u8,
    query: []const u8,

    pub fn parse(scope: []const u8) ?BlobScope {
        const parts = splitScope(scope, "blob") orelse return null;
        if (parts.positional) |accept| if (!validAccept(accept)) return null;
        var accepts: usize = 0;
        var params = std.mem.tokenizeScalar(u8, parts.query, '&');
        while (params.next()) |param| {
            if (!std.mem.startsWith(u8, param, "accept=")) return null;
            if (!validAccept(param["accept=".len..])) return null;
            accepts += 1;
        }
        if ((parts.positional == null) == (accepts == 0)) return null;
        return .{ .positional = parts.positional, .query = parts.query };
    }

    pub fn allows(self: BlobScope, mime_type: []const u8) bool {
        if (self.positional) |accept| return acceptMatches(accept, mime_type);
        var params = std.mem.tokenizeScalar(u8, self.query, '&');
        while (params.next()) |param| {
            if (acceptMatches(param["accept=".len..], mime_type)) return true;
        }
        return false;
    }
};

fn acceptMatches(encoded: []const u8, mime_type: []const u8) bool {
    var buf: [256]u8 = undefined;
    var fba: std.heap.FixedBufferAllocator = .init(&buf);
    const accept = percent.decodeAlloc(fba.allocator(), encoded) catch return false;
    return blobMimeMatches(accept, mime_type);
}

/// `*/*`, `type/*` or `type/subtype`: one slash with text on both sides, no
/// spaces, and `*` only as a whole subtype (@atproto/oauth-scopes isAccept)
fn validAccept(encoded: []const u8) bool {
    var buf: [256]u8 = undefined;
    var fba: std.heap.FixedBufferAllocator = .init(&buf);
    const accept = percent.decodeAlloc(fba.allocator(), encoded) catch return false;
    if (std.mem.eql(u8, accept, "*/*")) return true;
    const slash = std.mem.indexOfScalar(u8, accept, '/') orelse return false;
    if (slash == 0 or slash == accept.len - 1) return false;
    if (std.mem.indexOfScalarPos(u8, accept, slash + 1, '/') != null) return false;
    if (std.mem.indexOfScalar(u8, accept, ' ') != null) return false;
    const star = std.mem.indexOfScalar(u8, accept, '*') orelse return true;
    return star == accept.len - 1 and slash == accept.len - 2;
}

fn blobMimeMatches(pattern: []const u8, mime_type: []const u8) bool {
    if (pattern.len == 0) return false;
    if (std.mem.eql(u8, pattern, "*/*")) return true;
    if (std.mem.eql(u8, pattern, mime_type)) return true;
    if (std.mem.endsWith(u8, pattern, "/*")) {
        const prefix = pattern[0 .. pattern.len - 2];
        return std.mem.startsWith(u8, mime_type, prefix) and mime_type.len > prefix.len and mime_type[prefix.len] == '/';
    }
    return false;
}

/// An `rpc` permission in the reference's grammar: methods are `*` or exact NSIDs, given positionally or as
/// `lxm` parameters but not both; exactly one `aud`; no other parameters; and `*` for both is refused.
/// A scope outside it grants nothing, and sign-in refuses it.
pub const RpcScope = struct {
    positional: ?[]const u8,
    query: []const u8,
    aud: []const u8,

    pub fn parse(scope: []const u8) ?RpcScope {
        if (!std.mem.startsWith(u8, scope, "rpc")) return null;
        const rest = scope["rpc".len..];
        const query_start = std.mem.indexOfScalar(u8, rest, '?') orelse return null;
        const positional: ?[]const u8 = switch (rest[0]) {
            ':' => rest[1..query_start],
            '?' => null,
            else => return null,
        };
        const query = rest[query_start + 1 ..];
        if (positional) |lxm| if (!validLxm(lxm)) return null;

        var aud: ?[]const u8 = null;
        var any_wildcard = if (positional) |lxm| isWildcard(lxm) else false;
        var lxm_params: usize = 0;
        // Empty segments are skipped, as URLSearchParams does.
        var params = std.mem.tokenizeScalar(u8, query, '&');
        while (params.next()) |param| {
            if (std.mem.startsWith(u8, param, "lxm=")) {
                const lxm = param["lxm=".len..];
                if (!validLxm(lxm)) return null;
                any_wildcard = any_wildcard or isWildcard(lxm);
                lxm_params += 1;
            } else if (std.mem.startsWith(u8, param, "aud=")) {
                if (aud != null) return null;
                aud = param["aud=".len..];
            } else return null;
        }
        if ((positional == null) == (lxm_params == 0)) return null;
        const granted_aud = aud orelse return null;
        if (granted_aud.len == 0) return null;
        if (any_wildcard and isWildcard(granted_aud)) return null;
        return .{ .positional = positional, .query = query, .aud = granted_aud };
    }

    fn allowsMethod(self: RpcScope, lxm: []const u8) bool {
        if (self.positional) |allowed| return isWildcard(allowed) or percent.decodedEql(allowed, lxm);
        var params = std.mem.tokenizeScalar(u8, self.query, '&');
        while (params.next()) |param| {
            if (!std.mem.startsWith(u8, param, "lxm=")) continue;
            const allowed = param["lxm=".len..];
            if (isWildcard(allowed) or percent.decodedEql(allowed, lxm)) return true;
        }
        return false;
    }

    fn allowsAudience(self: RpcScope, aud: []const u8) bool {
        // Granted audiences are stored as scope text, percent-encoded (`did%3Aweb%3Aapi.bsky.chat%23bsky_chat`),
        // as permission-set expansion writes them and the permission spec asks clients to send them.
        return isWildcard(self.aud) or percent.decodedEql(self.aud, aud);
    }
};

// Values are compared decoded, as the reference URL-decodes them: `%2A` is `*`.
fn isWildcard(value: []const u8) bool {
    return percent.decodedEql(value, "*");
}

fn validLxm(lxm: []const u8) bool {
    return validNsidOrWildcard(lxm);
}

fn validNsidOrWildcard(value: []const u8) bool {
    if (isWildcard(value)) return true;
    var buf: [512]u8 = undefined;
    var fba: std.heap.FixedBufferAllocator = .init(&buf);
    const decoded = percent.decodeAlloc(fba.allocator(), value) catch return false;
    return zat.Nsid.parse(decoded) != null;
}

pub fn validTypedDataScope(allocator: std.mem.Allocator, scope: []const u8) error{OutOfMemory}!bool {
    const parsed = permissions.parse(allocator, scope) catch |err| switch (err) {
        error.InvalidScope, error.UnsupportedScope => return false,
        error.OutOfMemory => return error.OutOfMemory,
    };
    defer parsed.deinit();
    return parsed.value() == .permission;
}

fn rpcScopeMatches(scope: []const u8, aud: []const u8, lxm: []const u8) bool {
    const legacy = RpcScope.parse(scope) orelse return false;
    if (!legacy.allowsMethod(lxm) or !legacy.allowsAudience(aud)) return false;

    var buffer: [4096]u8 = undefined;
    var scratch: std.heap.FixedBufferAllocator = .init(&buffer);
    const attempt: permissions.Error!*const permissions.Scope = permissions.parse(scratch.allocator(), scope) catch |err| switch (err) {
        error.OutOfMemory => permissions.parse(std.heap.page_allocator, scope),
        else => err,
    };
    const parsed = attempt catch |err| switch (err) {
        error.InvalidScope, error.UnsupportedScope => return true,
        error.OutOfMemory => return false,
    };
    defer parsed.deinit();
    return switch (parsed.value()) {
        .permission => |permission| permission.matches(.{ .rpc = .{ .audience = aud, .method = lxm } }),
        else => false,
    };
}

fn spaceScopeMatches(
    scope: []const u8,
    action: SpaceAction,
    space_type: []const u8,
    authority: []const u8,
    skey: []const u8,
    collection: ?[]const u8,
) bool {
    const query_start = std.mem.indexOfScalar(u8, scope, '?');
    const type_pattern = spaceScopeType(scope) orelse return false;
    if (!std.mem.eql(u8, type_pattern, "*") and !std.mem.eql(u8, type_pattern, space_type)) return false;
    var saw_authority = false;
    var saw_action = false;
    var action_matches = false;
    var saw_manage = false;
    var manage_matches = false;
    var saw_collection = false;
    var collection_matches = false;
    var params = std.mem.splitScalar(u8, scope[(query_start orelse return false) + 1 ..], '&');
    while (params.next()) |param| {
        if (std.mem.startsWith(u8, param, "action=")) {
            saw_action = true;
            const allowed = param["action=".len..];
            action_matches = action_matches or switch (action) {
                .read_self => std.mem.eql(u8, allowed, "read_self") or std.mem.eql(u8, allowed, "read"),
                .read, .create, .update, .delete => std.mem.eql(u8, allowed, spaceActionName(action)),
                else => false,
            };
        } else if (std.mem.startsWith(u8, param, "manage=")) {
            saw_manage = true;
            manage_matches = manage_matches or std.mem.eql(u8, param["manage=".len..], spaceManageName(action));
        } else if (std.mem.startsWith(u8, param, "authority=")) {
            saw_authority = true;
            const allowed = param["authority=".len..];
            if (std.mem.eql(u8, allowed, "self")) return false;
            if (!std.mem.eql(u8, allowed, "*") and !std.mem.eql(u8, allowed, authority)) return false;
        } else if (std.mem.startsWith(u8, param, "skey=")) {
            const allowed = param["skey=".len..];
            if (!std.mem.eql(u8, allowed, "*") and !std.mem.eql(u8, allowed, skey)) return false;
        } else if (std.mem.startsWith(u8, param, "collection=")) {
            if (action == .read or action == .read_self or switch (action) {
                .manage_create, .manage_update, .manage_delete => true,
                else => false,
            }) continue;
            saw_collection = true;
            const requested = collection orelse return false;
            const allowed = param["collection=".len..];
            collection_matches = collection_matches or collectionPatternMatches(allowed, requested);
        }
    }
    if (!saw_authority) return false;
    return switch (action) {
        .manage_create, .manage_update, .manage_delete => saw_manage and manage_matches,
        .read => if (saw_action) action_matches else true,
        .read_self => if (saw_action) action_matches else true,
        .create, .update, .delete => (if (saw_action) action_matches else true) and saw_collection and collection_matches,
    };
}

/// A `space` scope, naming its type positionally (`space:<type>`) or with a
/// `spaceType` parameter (`space?spaceType=<type>`).
pub fn isSpaceScope(scope: []const u8) bool {
    return std.mem.startsWith(u8, scope, "space:") or std.mem.startsWith(u8, scope, "space?");
}

/// The space type a space scope names, in either form; null when it names
/// none, or names it both ways.
pub fn spaceScopeType(scope: []const u8) ?[]const u8 {
    const query_start = std.mem.indexOfScalar(u8, scope, '?');
    const base = if (query_start) |idx| scope[0..idx] else scope;
    if (std.mem.startsWith(u8, base, "space:")) {
        if (namedSpaceType(scope, query_start) != null) return null;
        return base["space:".len..];
    }
    if (std.mem.eql(u8, base, "space")) return namedSpaceType(scope, query_start);
    return null;
}

fn namedSpaceType(scope: []const u8, query_start: ?usize) ?[]const u8 {
    var params = std.mem.splitScalar(u8, scope[(query_start orelse return null) + 1 ..], '&');
    while (params.next()) |param| {
        if (std.mem.startsWith(u8, param, "spaceType=")) return param["spaceType=".len..];
    }
    return null;
}

fn collectionPatternMatches(pattern: []const u8, value: []const u8) bool {
    if (std.mem.eql(u8, pattern, "*") or std.mem.eql(u8, pattern, value)) return true;
    if (std.mem.endsWith(u8, pattern, ".*")) {
        const prefix = pattern[0 .. pattern.len - 2];
        return std.mem.startsWith(u8, value, prefix) and value.len > prefix.len and value[prefix.len] == '.';
    }
    return false;
}

fn spaceActionName(action: SpaceAction) []const u8 {
    return switch (action) {
        .read_self => "read_self",
        .read => "read",
        .create => "create",
        .update => "update",
        .delete => "delete",
        .manage_create, .manage_update, .manage_delete => "",
    };
}

fn spaceManageName(action: SpaceAction) []const u8 {
    return switch (action) {
        .manage_create => "create",
        .manage_update => "update",
        .manage_delete => "delete",
        else => "",
    };
}

test "repo scopes constrain action and collection" {
    try std.testing.expect(repoAllows("repo:*?action=create", .create, "app.bsky.feed.post"));
    try std.testing.expect(!repoAllows("repo:*?action=create", .delete, "app.bsky.feed.post"));
    try std.testing.expect(repoAllows("repo:app.bsky.feed.like", .update, "app.bsky.feed.like"));
    try std.testing.expect(!repoAllows("repo:app.bsky.feed.like", .update, "app.bsky.feed.post"));
    try std.testing.expect(repoAllows("repo:app.bsky.feed.post?action=create&action=delete", .delete, "app.bsky.feed.post"));
    try std.testing.expect(!repoAllows("repo:app.bsky.feed.post?action=create&action=delete", .update, "app.bsky.feed.post"));
}

test "repo scopes name collections with collection parameters" {
    const scope = "repo?collection=place.stream.live&collection=app.bsky.feed.post&action=create";
    try std.testing.expect(repoAllows(scope, .create, "place.stream.live"));
    try std.testing.expect(repoAllows(scope, .create, "app.bsky.feed.post"));
    try std.testing.expect(!repoAllows(scope, .create, "app.bsky.graph.follow"));
    try std.testing.expect(!repoAllows(scope, .delete, "place.stream.live"));
    try std.testing.expect(repoAllows("repo?collection=*", .delete, "app.bsky.graph.follow"));
    try std.testing.expect(repoAllows("repo?collection=%2A", .delete, "app.bsky.graph.follow"));
}

test "repo scopes outside the reference grammar grant nothing" {
    const collection = "app.bsky.feed.post";
    for ([_][]const u8{
        "repo",
        "repo:",
        "repo:?action=create",
        "repo?action=create",
        "repo:app.bsky.feed.*",
        "repo:app.bsky.*",
        "repo:invalid",
        "repo:*?action=*",
        "repo:*?action=publish",
        "repo:*?collection=app.bsky.feed.post",
        "repo:*?other=1",
        "repo?collection=app.bsky.feed.*",
        "repository:*",
    }) |scope| {
        try std.testing.expect(RepoScope.parse(scope) == null);
        try std.testing.expect(!repoAllows(scope, .create, collection));
    }
}

test "blob scopes constrain mime types" {
    try std.testing.expect(blobAllows("blob:image/*", "image/jpeg"));
    try std.testing.expect(!blobAllows("blob:image/*", "video/mp4"));
    try std.testing.expect(blobAllows("blob:*/*", "video/mp4"));
    try std.testing.expect(blobAllows("blob:image/png", "image/png"));
    try std.testing.expect(!blobAllows("blob:image/png", "image/jpeg"));
    try std.testing.expect(blobAllows("blob?accept=image/*&accept=video/*", "video/mp4"));
    try std.testing.expect(!blobAllows("blob?accept=image/*&accept=video/*", "audio/mpeg"));
    try std.testing.expect(blobAllows("blob:image%2F*", "image/jpeg"));
}

test "blob scopes outside the reference grammar grant nothing" {
    for ([_][]const u8{
        "blob",
        "blob:",
        "blob?",
        "blob:invalid",
        "blob:*/png",
        "blob:*/**",
        "blob:image/*/x",
        "blob:/png",
        "blob:image/",
        "blob?accept=invalid-mime",
        "blob:image/*?accept=video/*",
        "blob:*/*?other=1",
        "blobs:*/*",
    }) |scope| {
        try std.testing.expect(BlobScope.parse(scope) == null);
        try std.testing.expect(!blobAllows(scope, "image/png"));
    }
}

test "rpc scopes constrain method and audience" {
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getTimeline?aud=did:web:api.bsky.app#bsky_appview", "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getTimeline"));
    try std.testing.expect(rpcAllows("rpc:*?aud=did:web:api.bsky.app#bsky_appview", "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getFeed"));
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getFeed?aud=*", "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getFeed"));
    try std.testing.expect(!rpcAllows("rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app#bsky_appview", "did:web:video.bsky.app#video", "app.bsky.feed.getFeed"));
    try std.testing.expect(!rpcAllows("repo:*", "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getFeed"));
}

test "rpc scopes name methods with lxm parameters" {
    const scope = "rpc?lxm=*&aud=did:web:api.bsky.app%23bsky_appview";
    try std.testing.expect(rpcAllows(scope, "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getTimeline"));
    try std.testing.expect(!rpcAllows(scope, "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    const listed = "rpc?lxm=app.bsky.feed.getFeed&lxm=app.bsky.graph.getFollows&aud=*";
    try std.testing.expect(rpcAllows(listed, "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getFeed"));
    try std.testing.expect(rpcAllows(listed, "did:web:api.bsky.app#bsky_appview", "app.bsky.graph.getFollows"));
    try std.testing.expect(!rpcAllows(listed, "did:web:api.bsky.app#bsky_appview", "app.bsky.feed.getTimeline"));
}

test "rpc scopes compare decoded values and skip empty parameters" {
    const aud = "did:web:api.bsky.app#bsky_appview";
    try std.testing.expect(rpcAllows("rpc?lxm=%2A&aud=did:web:api.bsky.app%23bsky_appview", aud, "app.bsky.feed.getFeed"));
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getFeed?aud=*&", aud, "app.bsky.feed.getFeed"));
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getFeed?&aud=*", aud, "app.bsky.feed.getFeed"));
    // An include: set with an explicit `aud: "*"` is stored percent-encoded.
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getFeed?aud=%2A", aud, "app.bsky.feed.getFeed"));
}

test "rpc scopes outside the reference grammar grant nothing" {
    const aud = "did:web:api.bsky.app#bsky_appview";
    const lxm = "app.bsky.feed.getFeed";
    for ([_][]const u8{
        "rpc:app.bsky.feed.getFeed", // no aud
        "rpc?lxm=app.bsky.feed.getFeed", // no aud
        "rpc?aud=*", // no method
        "rpc:app.bsky.feed.getFeed?aud=", // empty aud
        "rpc:*?aud=*", // both wildcards
        "rpc?lxm=*&aud=*",
        "rpc?lxm=app.bsky.feed.getFeed&lxm=*&aud=*",
        "rpc:app.bsky.feed.*?aud=*", // methods are * or an exact NSID
        "rpc?lxm=app.bsky.feed.*&aud=*",
        "rpc:app.bsky.feed.getFeed?lxm=app.bsky.feed.getFeed&aud=*", // positional and lxm together
        "rpc:app.bsky.feed.getFeed?aud=did:web:other&aud=*", // aud given twice
        "rpc:app.bsky.feed.getFeed?aud=*&action=read", // unknown parameter
        "rpc:*?aud=%2A", // an encoded wildcard is still a wildcard
        "rpc?lxm=%2A&aud=*",
        "rpcx:app.bsky.feed.getFeed?aud=*",
    }) |scope| {
        if (rpcAllows(scope, aud, lxm)) {
            std.debug.print("granted by {s}\n", .{scope});
            return error.TestUnexpectedResult;
        }
        try std.testing.expect(RpcScope.parse(scope) == null);
    }
}

test "rpc scopes match a percent-encoded audience" {
    // As an expanded `include:` permission set stores them.
    try std.testing.expect(rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%23bsky_chat", "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    try std.testing.expect(rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did:web:api.bsky.chat%23bsky_chat", "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    try std.testing.expect(!rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%23bsky_chat", "did:web:api.bsky.app#bsky_appview", "chat.bsky.convo.listConvos"));
    try std.testing.expect(!rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%23bsky", "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    try std.testing.expect(!rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%2", "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    try std.testing.expect(!rpcAllows("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%2523bsky_chat", "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
}

test "percent decoding an include audience" {
    const allocator = std.testing.allocator;
    const decoded = try percent.decodeAlloc(allocator, "did:web:api.bsky.chat%23bsky_chat");
    defer allocator.free(decoded);
    try std.testing.expectEqualStrings("did:web:api.bsky.chat#bsky_chat", decoded);
    try std.testing.expectError(error.InvalidPercentEncoding, percent.decodeAlloc(allocator, "did:web:x%2"));
}

test "rpc audience escapes require exactly two hex digits" {
    try std.testing.expect(!rpcAllows("rpc:test.example.call?aud=%+A", "\n", "test.example.call"));
    try std.testing.expect(!rpcAllows("rpc:test.example.call?aud=%-0", "\x00", "test.example.call"));
    try std.testing.expect(rpcAllows("rpc:test.example.call?aud=did:web:a+b", "did:web:a+b", "test.example.call"));
    try std.testing.expect(!rpcAllows("rpc:test.example.call?aud=did:web:a+b", "did:web:a b", "test.example.call"));
}

test "space scopes constrain type identity key action and collection" {
    try std.testing.expect(spaceAllows("space:fm.plyr.privateMedia?authority=did:plc:alice&skey=self&collection=fm.plyr.track&action=create", .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.track"));
    try std.testing.expect(!spaceAllows("space:fm.plyr.privateMedia?authority=did:plc:alice&skey=self&action=read", .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.track"));
    try std.testing.expect(spaceAllows("space:*?authority=*&skey=*&action=read", .read, "fm.plyr.privateMedia", "did:plc:bob", "records", null));
    try std.testing.expect(!spaceAllows("space:fm.plyr.*?authority=*&skey=*&action=read", .read, "fm.plyr.privateMedia", "did:plc:bob", "records", null));
    try std.testing.expect(spaceAllows("space:fm.plyr.privateMedia?authority=did:plc:alice&collection=fm.plyr.track&action=read_self", .read_self, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.track"));
    try std.testing.expect(spaceAllows("space:fm.plyr.privateMedia?authority=did:plc:alice&collection=fm.plyr.track&action=read", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(spaceAllows("space:fm.plyr.privateMedia?authority=did:plc:alice&manage=update", .manage_update, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("space:fm.plyr.privateMedia?authority=self&manage=update", .manage_update, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("repo:*", .read, "fm.plyr.privateMedia", "did:plc:bob", "records", null));
}

test "space scopes name their type positionally or with spaceType" {
    try std.testing.expect(spaceAllows("space?spaceType=fm.plyr.privateMedia&authority=did:plc:alice&collection=fm.plyr.track&action=create", .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.track"));
    try std.testing.expect(!spaceAllows("space?spaceType=fm.plyr.privateMedia&authority=did:plc:alice&action=read", .read, "fm.plyr.other", "did:plc:alice", "self", null));
    try std.testing.expect(spaceAllows("space?spaceType=*&authority=*", .read, "fm.plyr.privateMedia", "did:plc:bob", "records", null));
    try std.testing.expect(!spaceAllows("space?authority=did:plc:alice&action=read", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("space:fm.plyr.privateMedia?spaceType=fm.plyr.privateMedia", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("spacex?spaceType=fm.plyr.privateMedia", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
}

test "a space grant without an authority matches nothing" {
    try std.testing.expect(!spaceAllows("space:fm.plyr.privateMedia", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("space?spaceType=fm.plyr.privateMedia&action=read", .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
}

test "space read scopes allow repo-level self reads" {
    const scope = "space:fm.plyr.privateMedia?authority=did:plc:alice&skey=self&collection=fm.plyr.track&action=read&action=create&manage=update";
    try std.testing.expect(spaceAllows(scope, .read_self, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(spaceAllows(scope, .read_self, "fm.plyr.privateMedia", "did:plc:alice", "self", "app.other.thing"));
    try std.testing.expect(spaceAllows(scope, .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows(scope, .read_self, "fm.plyr.privateMedia", "did:plc:bob", "self", null));
    try std.testing.expect(!spaceAllows(scope, .read_self, "fm.plyr.privateMedia", "did:plc:alice", "other", null));
    try std.testing.expect(!spaceAllows(scope, .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "app.other.thing"));
    try std.testing.expect(spaceAllows("space:app.bulleted.space?authority=did:plc:alice&collection=app.bulleted.bullet&action=read_self", .read_self, "app.bulleted.space", "did:plc:alice", "self", null));
    try std.testing.expect(!spaceAllows("space:app.bulleted.space?authority=did:plc:alice&collection=app.bulleted.bullet&action=read_self", .read, "app.bulleted.space", "did:plc:alice", "self", null));
}

test "account scopes constrain attribute and action" {
    try std.testing.expect(accountAllows("account:email?action=manage", .email, .manage));
    try std.testing.expect(!accountAllows("account:email?action=read", .email, .manage));
    try std.testing.expect(!accountAllows("account:repo?action=manage", .email, .manage));
    try std.testing.expect(accountAllows("account:*", .repo, .manage));
}

test "identity scopes constrain attribute" {
    try std.testing.expect(identityAllows("identity:handle", .handle));
    try std.testing.expect(!identityAllows("identity:handle", .wildcard));
    try std.testing.expect(identityAllows("identity:*", .wildcard));
}

test "a permission-set expansion with collections grants space manage actions" {
    const scope = "atproto space:tech.waow.lore.space?authority=*&skey=*&collection=tech.waow.lore.entry&collection=tech.waow.lore.registry&action=read&action=create&action=update&action=delete&manage=create&manage=update&manage=delete";
    const did = "did:plc:siv7zbedip4vcet4v67piibr";
    try std.testing.expect(spaceAllows(scope, .manage_update, "tech.waow.lore.space", did, "1d5d7c37", null));
    try std.testing.expect(spaceAllows(scope, .manage_create, "tech.waow.lore.space", did, "1d5d7c37", null));
    try std.testing.expect(spaceAllows(scope, .create, "tech.waow.lore.space", did, "1d5d7c37", "tech.waow.lore.entry"));
    try std.testing.expect(!spaceAllows(scope, .create, "tech.waow.lore.space", did, "1d5d7c37", "tech.waow.other"));
    try std.testing.expect(!spaceAllows(scope, .manage_update, "tech.waow.memory.space", did, "1d5d7c37", null));
}

test "typed RPC checks accept bare request DIDs only for wildcard audience grants" {
    const lxm = "app.bsky.feed.getFeed";
    const did = "did:web:api.bsky.app";
    const wildcard = "rpc:app.bsky.feed.getFeed?aud=*";
    const specific = "rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app%23bsky_appview";
    try std.testing.expect(try validTypedDataScope(std.testing.allocator, wildcard));
    try std.testing.expect(try validTypedDataScope(std.testing.allocator, specific));
    try std.testing.expect(!try validTypedDataScope(std.testing.allocator, "rpc:app.bsky.feed.getFeed?aud=" ++ did));
    try std.testing.expect(rpcAllows(wildcard, did, lxm));
    try std.testing.expect(!rpcAllows(wildcard, "not-a-did", lxm));
    try std.testing.expect(rpcAllows(specific, did ++ "#bsky_appview", lxm));
    try std.testing.expect(!rpcAllows(specific, did ++ "#other", lxm));
    try std.testing.expect(!rpcAllows(specific, did, lxm));
    try std.testing.expect(rpcAllows("rpc:app.bsky.feed.getFeed?aud=" ++ did, did, lxm));
}