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

zat.dev/zds

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

0
0
761 lines · 35.8 KB Raw History
const std = @import("std");
const service_auth = @import("../../internal/service_auth.zig");
const store = @import("../../storage/store.zig");
const clock = @import("../../core/clock.zig");
const scope_rules = @import("../../internal/scopes.zig");
const zat = @import("zat");

const max_lexicon_response_size = 1024 * 1024;
const document_cache = @import("../../internal/document_cache.zig");
const outbound = @import("../../internal/outbound.zig");
const lexicon_cache_ttl_seconds: i64 = 5 * 60;
var lexicon_cache = document_cache.DocumentCache(64).init(std.heap.page_allocator);

pub const testing = if (@import("builtin").is_test) struct {
    pub fn cacheDeclaration(nsid: []const u8, body: []const u8) !void {
        try lexicon_cache.put(nsid, body, clock.nowSeconds() + 600);
    }

    pub fn clearCache() void {
        lexicon_cache.deinit();
    }
} else struct {};

pub const PermissionSet = struct {
    title: []const u8,
    detail: []const u8,
    expanded_scope: []const u8,
};

pub fn expandScopes(allocator: std.mem.Allocator, scope_text: []const u8, user_did: []const u8) ![]const u8 {
    return resolveScopes(allocator, scope_text, user_did, true);
}

pub fn prepareScopes(allocator: std.mem.Allocator, scope_text: []const u8, user_did: []const u8) ![]const u8 {
    return resolveScopes(allocator, scope_text, user_did, false);
}

fn resolveScopes(allocator: std.mem.Allocator, scope_text: []const u8, user_did: []const u8, collections: bool) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    var first = true;
    var scopes = std.mem.splitScalar(u8, scope_text, ' ');
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        const expanded = if (std.mem.startsWith(u8, scope, "include:"))
            try expandIncludeScope(allocator, scope)
        else
            scope;

        var expanded_parts = std.mem.splitScalar(u8, expanded, ' ');
        while (expanded_parts.next()) |part| {
            if (part.len == 0) continue;
            if (!first) try out.writer.writeByte(' ');
            first = false;
            try writeResolvedScope(allocator, &out.writer, part, user_did, collections);
        }
    }
    return out.toOwnedSlice();
}

pub fn resolveSpaceWriteScopes(allocator: std.mem.Allocator, scope_text: []const u8, space_type: []const u8) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    errdefer out.deinit();
    var parts = std.mem.tokenizeScalar(u8, scope_text, ' ');
    while (parts.next()) |scope| {
        if (out.written().len != 0) try out.writer.writeByte(' ');
        const declared_type = scope_rules.spaceScopeType(scope);
        if (declared_type != null and std.mem.eql(u8, declared_type.?, space_type)) {
            try writeResolvedScope(allocator, &out.writer, scope, "", true);
        } else {
            try out.writer.writeAll(scope);
        }
    }
    return out.toOwnedSlice();
}

fn writeResolvedScope(allocator: std.mem.Allocator, writer: *std.Io.Writer, scope: []const u8, user_did: []const u8, collections: bool) !void {
    if (!scope_rules.isSpaceScope(scope)) return writer.writeAll(scope);
    const space_type = scope_rules.spaceScopeType(scope) orelse return error.InvalidSpaceScope;
    const query_start = std.mem.indexOfScalar(u8, scope, '?');
    var authority = user_did;
    var has_collection = false;
    if (query_start) |idx| {
        var params = std.mem.splitScalar(u8, scope[idx + 1 ..], '&');
        while (params.next()) |param| {
            if (std.mem.startsWith(u8, param, "collection=")) has_collection = true;
            if (!std.mem.startsWith(u8, param, "authority=")) continue;
            const value = param["authority=".len..];
            if (!std.mem.eql(u8, value, "self")) authority = value;
        }
    }
    try writer.print("space:{s}?authority={s}", .{ space_type, authority });
    if (collections and !has_collection and !std.mem.eql(u8, space_type, "*")) {
        const defaults = try resolveSpaceTypeCollections(allocator, space_type);
        for (defaults) |collection| try writer.print("&collection={s}", .{collection});
    }
    if (query_start) |idx| {
        var params = std.mem.splitScalar(u8, scope[idx + 1 ..], '&');
        while (params.next()) |param| {
            if (std.mem.startsWith(u8, param, "authority=") or std.mem.startsWith(u8, param, "spaceType=")) continue;
            try writer.writeByte('&');
            try writer.writeAll(param);
        }
    }
}

fn resolveSpaceTypeCollections(allocator: std.mem.Allocator, nsid: []const u8) ![]const []const u8 {
    const lexicon = try fetchPermissionSetLexicon(allocator, nsid);
    defer lexicon.deinit();
    const root = switch (lexicon.value) {
        .object => |object| object,
        else => return error.InvalidSpaceTypeDeclaration,
    };
    const value = switch (root.get("value") orelse return error.InvalidSpaceTypeDeclaration) {
        .object => |object| object,
        else => return error.InvalidSpaceTypeDeclaration,
    };
    const defs = switch (value.get("defs") orelse return error.InvalidSpaceTypeDeclaration) {
        .object => |object| object,
        else => return error.InvalidSpaceTypeDeclaration,
    };
    const main = switch (defs.get("main") orelse return error.InvalidSpaceTypeDeclaration) {
        .object => |object| object,
        else => return error.InvalidSpaceTypeDeclaration,
    };
    if (!std.mem.eql(u8, jsonString(main, "type") orelse return error.InvalidSpaceTypeDeclaration, "space")) return error.InvalidSpaceTypeDeclaration;
    const values = switch (main.get("collections") orelse return error.InvalidSpaceTypeDeclaration) {
        .array => |array| array,
        else => return error.InvalidSpaceTypeDeclaration,
    };
    var collections: std.ArrayList([]const u8) = .empty;
    for (values.items) |item| {
        if (item != .string or zat.Nsid.parse(item.string) == null) return error.InvalidSpaceTypeDeclaration;
        try collections.append(allocator, try allocator.dupe(u8, item.string));
    }
    return collections.toOwnedSlice(allocator);
}

pub fn resolvePermissionSet(allocator: std.mem.Allocator, include_scope: []const u8) !PermissionSet {
    const parsed = try parseIncludeScope(include_scope);
    const lexicon = try fetchPermissionSetLexicon(allocator, parsed.nsid);
    const main = try mainPermissionSet(lexicon);
    const aud = try includeAudience(allocator, parsed.aud);
    defer if (aud) |value| allocator.free(value); // the expansion writes its own encoded copy
    const expanded = try buildExpandedScope(allocator, parsed.nsid, aud, main);
    if (expanded.len == 0) return error.EmptyPermissionSet;

    return .{
        .title = try allocator.dupe(u8, jsonString(main, "title") orelse parsed.nsid),
        .detail = try allocator.dupe(u8, jsonString(main, "detail") orelse "permissions requested by this app."),
        .expanded_scope = expanded,
    };
}

pub fn containsSpaceScope(scope_text: []const u8) bool {
    var parts = std.mem.splitScalar(u8, scope_text, ' ');
    while (parts.next()) |part| {
        if (std.mem.startsWith(u8, part, "space:") or std.mem.startsWith(u8, part, "space?")) return true;
    }
    return false;
}

fn expandIncludeScope(allocator: std.mem.Allocator, include_scope: []const u8) ![]const u8 {
    const permission_set = try resolvePermissionSet(allocator, include_scope);
    return permission_set.expanded_scope;
}

/// An `include:` scope's `aud`, decoded. Clients percent-encode it (`did:web:api.bsky.chat%23bsky_chat`), and
/// `buildExpandedScope` encodes it again as it writes each scope, so it's decoded first or `%23` would become `%2523`.
fn includeAudience(allocator: std.mem.Allocator, aud: ?[]const u8) !?[]const u8 {
    const value = aud orelse return null;
    return try zat.percent.decodeAlloc(allocator, value);
}

const IncludeScope = struct {
    nsid: []const u8,
    aud: ?[]const u8,
};

fn parseIncludeScope(scope: []const u8) !IncludeScope {
    const rest = if (std.mem.startsWith(u8, scope, "include:")) scope["include:".len..] else return error.InvalidIncludeScope;
    const query_start = std.mem.indexOfScalar(u8, rest, '?');
    const nsid = if (query_start) |idx| rest[0..idx] else rest;
    if (zat.Nsid.parse(nsid) == null) return error.InvalidNsid;

    var aud: ?[]const u8 = null;
    if (query_start) |idx| {
        var params = std.mem.splitScalar(u8, rest[idx + 1 ..], '&');
        while (params.next()) |param| {
            if (std.mem.startsWith(u8, param, "aud=")) {
                aud = param["aud=".len..];
                break;
            }
        }
    }
    return .{ .nsid = nsid, .aud = aud };
}

fn fetchPermissionSetLexicon(allocator: std.mem.Allocator, nsid: []const u8) !std.json.Parsed(std.json.Value) {
    const now = clock.nowSeconds();
    if (try lexicon_cache.get(allocator, nsid, now)) |body| {
        return try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
    }
    var handle_resolver = zat.HandleResolver.init(store.currentIo(), allocator);
    defer handle_resolver.deinit();
    const did = try handle_resolver.resolveLexiconAuthority(zat.Nsid.parse(nsid) orelse return error.InvalidNsid);
    var did_resolver = service_auth.didResolver(allocator);
    defer did_resolver.deinit();
    var did_doc = try did_resolver.resolve(zat.Did.parse(did) orelse return error.InvalidLexiconDid);
    defer did_doc.deinit();
    const endpoint = did_doc.pdsEndpoint() orelse return error.LexiconPdsNotFound;

    const escaped_did = try zat.oauth.percentEncodeAlloc(allocator, did);
    const escaped_nsid = try zat.oauth.percentEncodeAlloc(allocator, nsid);
    const url = try std.fmt.allocPrint(
        allocator,
        "{s}/xrpc/com.atproto.repo.getRecord?repo={s}&collection=com.atproto.lexicon.schema&rkey={s}",
        .{ endpoint, escaped_did, escaped_nsid },
    );

    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    const result = try outbound.fetch(allocator, store.currentIo(), &transport, .{
        .url = url,
        .accept = "application/json",
        .max_response_size = max_lexicon_response_size,
    });
    if (result.status != .ok) return error.LexiconFetchFailed;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, result.body, .{});
    lexicon_cache.put(nsid, result.body, now + lexicon_cache_ttl_seconds) catch {};
    return parsed;
}

fn mainPermissionSet(lexicon: std.json.Parsed(std.json.Value)) !std.json.ObjectMap {
    const root = switch (lexicon.value) {
        .object => |object| object,
        else => return error.InvalidLexicon,
    };
    const value = switch (root.get("value") orelse return error.InvalidLexicon) {
        .object => |object| object,
        else => return error.InvalidLexicon,
    };
    const defs = switch (value.get("defs") orelse return error.InvalidLexicon) {
        .object => |object| object,
        else => return error.InvalidLexicon,
    };
    const main = switch (defs.get("main") orelse return error.InvalidLexicon) {
        .object => |object| object,
        else => return error.InvalidLexicon,
    };
    const def_type = jsonString(main, "type") orelse return error.InvalidLexicon;
    if (!std.mem.eql(u8, def_type, "permission-set")) return error.NotPermissionSet;
    return main;
}

fn buildExpandedScope(
    allocator: std.mem.Allocator,
    include_nsid: []const u8,
    include_aud: ?[]const u8,
    main: std.json.ObjectMap,
) ![]const u8 {
    const permissions = switch (main.get("permissions") orelse return error.InvalidPermissionSet) {
        .array => |array| array,
        else => return error.InvalidPermissionSet,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    var first = true;
    for (permissions.items) |item| {
        const permission = switch (item) {
            .object => |object| object,
            else => continue,
        };
        const resource = jsonString(permission, "resource") orelse continue;
        if (std.mem.eql(u8, resource, "repo")) {
            try appendRepoScopes(&out.writer, &first, include_nsid, permission);
        } else if (std.mem.eql(u8, resource, "rpc")) {
            try appendRpcScopes(allocator, &out.writer, &first, include_nsid, include_aud, permission);
        } else if (std.mem.eql(u8, resource, "space")) {
            try appendSpaceScopes(&out.writer, &first, include_nsid, permission);
        }
    }
    return out.toOwnedSlice();
}

fn appendRepoScopes(
    writer: *std.Io.Writer,
    first: *bool,
    include_nsid: []const u8,
    permission: std.json.ObjectMap,
) !void {
    const collections = switch (permission.get("collection") orelse return) {
        .array => |array| array,
        else => return,
    };
    const actions_value = switch (permission.get("action") orelse .null) {
        .array => |array| array,
        else => null,
    };
    if (actions_value) |actions| {
        if (!validRepoActions(actions.items)) return;
    }

    for (collections.items) |collection_value| {
        const collection = switch (collection_value) {
            .string => |string| string,
            else => return,
        };
        if (!isParentAuthorityOf(include_nsid, collection)) return;
    }

    for (collections.items) |collection_value| {
        const collection = switch (collection_value) {
            .string => |string| string,
            else => unreachable,
        };
        if (!first.*) try writer.writeByte(' ');
        first.* = false;
        try writer.print("repo:{s}", .{collection});
        if (actions_value) |actions| {
            if (!isDefaultRepoActions(actions.items)) {
                try appendActionParams(writer, actions.items);
            }
        }
    }
}

fn appendRpcScopes(
    allocator: std.mem.Allocator,
    writer: *std.Io.Writer,
    first: *bool,
    include_nsid: []const u8,
    include_aud: ?[]const u8,
    permission: std.json.ObjectMap,
) !void {
    const lxms = switch (permission.get("lxm") orelse return) {
        .array => |array| array,
        else => return,
    };
    const explicit_aud = jsonString(permission, "aud");
    const inherit_aud = jsonBool(permission, "inheritAud") == true;
    if (explicit_aud != null and !std.mem.eql(u8, explicit_aud.?, "*")) return;
    if (explicit_aud != null and inherit_aud) return;
    const aud = explicit_aud orelse if (inherit_aud) include_aud else null;
    if (aud == null) return;
    const escaped_aud = try zat.oauth.percentEncodeAlloc(allocator, aud.?);
    defer allocator.free(escaped_aud);

    for (lxms.items) |lxm_value| {
        const lxm = switch (lxm_value) {
            .string => |string| string,
            else => return,
        };
        if (!isParentAuthorityOf(include_nsid, lxm)) return;
    }

    for (lxms.items) |lxm_value| {
        const lxm = switch (lxm_value) {
            .string => |string| string,
            else => unreachable,
        };
        if (!first.*) try writer.writeByte(' ');
        first.* = false;
        try writer.print("rpc:{s}?aud={s}", .{ lxm, escaped_aud });
    }
}

fn appendSpaceScopes(
    writer: *std.Io.Writer,
    first: *bool,
    include_nsid: []const u8,
    permission: std.json.ObjectMap,
) !void {
    const space_type = jsonString(permission, "spaceType") orelse return;
    if (!validPermissionSetNsid(include_nsid, space_type) or std.mem.eql(u8, space_type, "*")) return;
    const authority = jsonString(permission, "authority");
    if (authority) |value| {
        if (!std.mem.eql(u8, value, "*") and !std.mem.eql(u8, value, "self") and zat.Did.parse(value) == null) return;
    }
    const skey = jsonString(permission, "skey");
    if (skey) |value| {
        if (!std.mem.eql(u8, value, "*") and zat.Rkey.parse(value) == null) return;
    }
    var collection_buf: [64][]const u8 = undefined;
    const maybe_collections = try optionalStringArray(permission, "collection", &collection_buf);
    if (maybe_collections) |collections| {
        for (collections) |collection| {
            if (!std.mem.eql(u8, collection, "*") and zat.Nsid.parse(collection) == null) return;
        }
    }
    const actions = switch (permission.get("action") orelse .null) {
        .array => |array| array.items,
        .null => null,
        else => return,
    };
    if (actions) |values| if (!validSpaceActions(values)) return;
    const manages = switch (permission.get("manage") orelse .null) {
        .array => |array| array.items,
        .null => null,
        else => return,
    };
    if (manages) |values| if (!validSpaceManage(values)) return;

    if (!first.*) try writer.writeByte(' ');
    first.* = false;
    try writer.print("space:{s}", .{space_type});
    var has_query = false;
    if (authority) |value| try appendSpaceParam(writer, &has_query, "authority", value);
    if (skey) |value| try appendSpaceParam(writer, &has_query, "skey", value);
    if (maybe_collections) |collections| {
        for (collections) |collection| try appendSpaceParam(writer, &has_query, "collection", collection);
    }
    if (actions) |values| {
        for (values) |value| try appendSpaceParam(writer, &has_query, "action", value.string);
    }
    if (manages) |values| {
        for (values) |value| try appendSpaceParam(writer, &has_query, "manage", value.string);
    }
}

fn appendSpaceParam(writer: *std.Io.Writer, has_query: *bool, name: []const u8, value: []const u8) !void {
    try writer.writeByte(if (has_query.*) '&' else '?');
    has_query.* = true;
    try writer.print("{s}={s}", .{ name, value });
}

fn isParentAuthorityOf(include_nsid: []const u8, other: []const u8) bool {
    if (std.mem.eql(u8, other, "*")) return false;
    if (zat.Nsid.parse(other) == null) return false;
    const dot = std.mem.lastIndexOfScalar(u8, include_nsid, '.') orelse return false;
    if (dot >= other.len - 1) return false;
    return std.mem.eql(u8, include_nsid[0..dot], other[0..dot]) and other[dot] == '.';
}

fn validPermissionSetNsid(include_nsid: []const u8, other: []const u8) bool {
    return std.mem.eql(u8, include_nsid, other) or isParentAuthorityOf(include_nsid, other);
}

fn validRepoActions(actions: []const std.json.Value) bool {
    if (actions.len == 0) return false;
    for (actions) |action| {
        if (action != .string) return false;
        if (!(std.mem.eql(u8, action.string, "create") or
            std.mem.eql(u8, action.string, "update") or
            std.mem.eql(u8, action.string, "delete"))) return false;
    }
    return true;
}

fn validSpaceActions(actions: []const std.json.Value) bool {
    if (actions.len == 0) return false;
    for (actions) |action| {
        if (action != .string) return false;
        if (!(std.mem.eql(u8, action.string, "read_self") or
            std.mem.eql(u8, action.string, "read") or
            std.mem.eql(u8, action.string, "create") or
            std.mem.eql(u8, action.string, "update") or
            std.mem.eql(u8, action.string, "delete"))) return false;
    }
    return true;
}

fn validSpaceManage(actions: []const std.json.Value) bool {
    if (actions.len == 0) return false;
    for (actions) |action| {
        if (action != .string) return false;
        if (!(std.mem.eql(u8, action.string, "create") or
            std.mem.eql(u8, action.string, "update") or
            std.mem.eql(u8, action.string, "delete"))) return false;
    }
    return true;
}

fn isDefaultRepoActions(actions: []const std.json.Value) bool {
    return actions.len == 3 and
        hasRepoAction(actions, "create") and
        hasRepoAction(actions, "update") and
        hasRepoAction(actions, "delete");
}

fn hasRepoAction(actions: []const std.json.Value, needle: []const u8) bool {
    for (actions) |action| {
        if (action == .string and std.mem.eql(u8, action.string, needle)) return true;
    }
    return false;
}

fn appendActionParams(writer: *std.Io.Writer, actions: []const std.json.Value) !void {
    var first = true;
    inline for (&.{ "create", "update", "delete" }) |candidate| {
        if (hasRepoAction(actions, candidate)) {
            try writer.writeByte(if (first) '?' else '&');
            first = false;
            try writer.print("action={s}", .{candidate});
        }
    }
}

fn jsonString(object: std.json.ObjectMap, key: []const u8) ?[]const u8 {
    return switch (object.get(key) orelse return null) {
        .string => |string| string,
        else => null,
    };
}

fn jsonBool(object: std.json.ObjectMap, key: []const u8) ?bool {
    return switch (object.get(key) orelse return null) {
        .bool => |value| value,
        else => null,
    };
}

fn optionalStringArray(object: std.json.ObjectMap, key: []const u8, buf: *[64][]const u8) !?[]const []const u8 {
    const array = switch (object.get(key) orelse return null) {
        .array => |array| array,
        else => return error.InvalidPermissionSet,
    };
    if (array.items.len == 0 or array.items.len > buf.len) return error.InvalidPermissionSet;
    for (array.items, 0..) |item, idx| {
        buf[idx] = switch (item) {
            .string => |string| string,
            else => return error.InvalidPermissionSet,
        };
    }
    return buf[0..array.items.len];
}

test "permission set expansion includes repo permissions under include authority" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","title":"demo","detail":"demo detail","permissions":[{"type":"permission","resource":"repo","action":["create","update","delete"],"collection":["fm.plyr.track","fm.plyr.like"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.authFullApp", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("repo:fm.plyr.track repo:fm.plyr.like", expanded);
}

test "plyr staging auth permission set expands repo collections" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","title":"Full plyr.fm Access","detail":"Provides full access to all plyr.fm features including uploading and managing tracks, playlists, likes, and comments.","permissions":[{"type":"permission","resource":"repo","action":["create","update","delete"],"collection":["fm.plyr.stg.track","fm.plyr.stg.like","fm.plyr.stg.comment","fm.plyr.stg.list","fm.plyr.stg.actor.profile"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.stg.authFullApp", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings(
        "repo:fm.plyr.stg.track repo:fm.plyr.stg.like repo:fm.plyr.stg.comment repo:fm.plyr.stg.list repo:fm.plyr.stg.actor.profile",
        expanded,
    );
}

test "permission set expansion rejects mixed-authority repo permission" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"repo","action":["create","update","delete"],"collection":["fm.plyr.track","app.bsky.feed.post"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.authFullApp", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("", expanded);
}

test "rpc permissions inherit include audience" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"rpc","inheritAud":true,"lxm":["fm.plyr.getThing","fm.plyr.getOther"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.authFullApp", "did:web:api.plyr.fm#svc", main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("rpc:fm.plyr.getThing?aud=did%3Aweb%3Aapi.plyr.fm%23svc rpc:fm.plyr.getOther?aud=did%3Aweb%3Aapi.plyr.fm%23svc", expanded);
}

test "an encoded include audience is encoded once in the expanded scopes" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"rpc","inheritAud":true,"lxm":["chat.bsky.convo.listConvos"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    const main = try mainPermissionSet(parsed);
    const include = try parseIncludeScope("include:chat.bsky.authFullChatClient?aud=did:web:api.bsky.chat%23bsky_chat");
    const expanded = try buildExpandedScope(allocator, include.nsid, try includeAudience(allocator, include.aud), main);
    try std.testing.expectEqualStrings("rpc:chat.bsky.convo.listConvos?aud=did%3Aweb%3Aapi.bsky.chat%23bsky_chat", expanded);
    // And the grant it makes lets the proxy through to that service, and no other.
    try std.testing.expect(scope_rules.rpcAllows(expanded, "did:web:api.bsky.chat#bsky_chat", "chat.bsky.convo.listConvos"));
    try std.testing.expect(!scope_rules.rpcAllows(expanded, "did:web:api.bsky.app#bsky_appview", "chat.bsky.convo.listConvos"));
}

test "include audiences reject signed and truncated percent escapes" {
    for ([_][]const u8{ "did:web:example.com%+A", "did:web:example.com%-0", "did:web:example.com%2" }) |audience| {
        try std.testing.expectError(error.InvalidPercentEncoding, includeAudience(std.testing.allocator, audience));
    }
}

test "rpc permission entry is rejected when any method is outside the include authority" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"rpc","inheritAud":true,"lxm":["fm.plyr.getThing","com.atproto.repo.getRecord"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.authFullApp", "did:web:api.plyr.fm#svc", main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("", expanded);
}

test "rpc permissions reject specific explicit audiences" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"rpc","aud":"did:web:api.plyr.fm#svc","lxm":["fm.plyr.getThing"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.authFullApp", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("", expanded);
}

test "space permissions expand to scoped permissioned data grants" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"space","spaceType":"fm.plyr.privateMedia","authority":"*","skey":"self","collection":["fm.plyr.track"],"action":["read","create","update","delete"],"manage":["update","delete"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.privateMedia", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings(
        "space:fm.plyr.privateMedia?authority=*&skey=self&collection=fm.plyr.track&action=read&action=create&action=update&action=delete&manage=update&manage=delete",
        expanded,
    );
    try std.testing.expect(scope_rules.spaceAllows(expanded, .read, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(scope_rules.spaceAllows(expanded, .manage_update, "fm.plyr.privateMedia", "did:plc:alice", "self", null));
    try std.testing.expect(scope_rules.spaceAllows(expanded, .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.track"));
    try std.testing.expect(!scope_rules.spaceAllows(expanded, .create, "fm.plyr.privateMedia", "did:plc:alice", "self", "fm.plyr.comment"));
    try std.testing.expect(!scope_rules.spaceAllows(expanded, .create, "fm.plyr.privateMedia", "did:plc:alice", "other", "fm.plyr.track"));
}

test "space permissions require canonical spaceType" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"space","action":["read"],"did":["*"],"space":["fm.plyr.privateMedia"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.privateMedia", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("", expanded);
}

test "space permissions allow cross-namespace collections" {
    const allocator = std.testing.allocator;
    const text =
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"space","spaceType":"fm.plyr.privateMedia","action":["create"],"collection":["app.bsky.feed.post"]}]}}}}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    const main = try mainPermissionSet(parsed);
    const expanded = try buildExpandedScope(allocator, "fm.plyr.privateMedia", null, main);
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings("space:fm.plyr.privateMedia?collection=app.bsky.feed.post&action=create", expanded);
}

test "space permission resolves self authority at token issuance" {
    const allocator = std.testing.allocator;
    const expanded = try expandScopes(allocator, "space:fm.plyr.privateMedia?skey=self&collection=fm.plyr.track&action=read_self", "did:plc:alice");
    defer allocator.free(expanded);
    try std.testing.expectEqualStrings(
        "space:fm.plyr.privateMedia?authority=did:plc:alice&skey=self&collection=fm.plyr.track&action=read_self",
        expanded,
    );
}

test "spaceType scopes resolve to the same grant as positional ones" {
    const allocator = std.testing.allocator;
    const positional = try expandScopes(allocator, "space:fm.plyr.privateMedia?collection=fm.plyr.track&action=read", "did:plc:alice");
    defer allocator.free(positional);
    const named = try expandScopes(allocator, "space?spaceType=fm.plyr.privateMedia&collection=fm.plyr.track&action=read", "did:plc:alice");
    defer allocator.free(named);
    try std.testing.expectEqualStrings(positional, named);
    try std.testing.expect(!scope_rules.spaceAllows(named, .read, "fm.plyr.privateMedia", "did:plc:bob", "self", null));
    try std.testing.expectError(error.InvalidSpaceScope, expandScopes(allocator, "space:fm.plyr.privateMedia?spaceType=fm.plyr.other", "did:plc:alice"));
}

test "containsSpaceScope finds space grants in raw and expanded scope text" {
    try std.testing.expect(containsSpaceScope("space:fm.plyr.privateMedia?authority=did:plc:alice&action=read"));
    try std.testing.expect(containsSpaceScope("atproto blob:*/* space?type=fm.plyr.privateMedia"));
    try std.testing.expect(containsSpaceScope("repo:fm.plyr.track space:fm.plyr.privateMedia"));
    try std.testing.expect(!containsSpaceScope("atproto repo:fm.plyr.track blob:*/*"));
    try std.testing.expect(!containsSpaceScope("include:fm.plyr.authFullApp"));
    try std.testing.expect(!containsSpaceScope(""));
}

test "stored default collection grants follow declarations across refresh while explicit grants stay fixed" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    defer lexicon_cache.deinit();
    const did = "did:plc:dynamiccollections";
    const space_type = "test.dynamic.space";
    const expiry = clock.nowSeconds() + 600;
    _ = try store.createAccount(a, "dynamic.test", "dynamic@test.com", "password", did, true);
    try lexicon_cache.put(space_type,
        \\{"value":{"defs":{"main":{"type":"space","collections":["test.dynamic.first"]}}}}
    , expiry);
    try lexicon_cache.put("test.dynamic.access",
        \\{"value":{"defs":{"main":{"type":"permission-set","permissions":[{"type":"permission","resource":"space","spaceType":"test.dynamic.space"}]}}}}
    , expiry);
    const grant = try prepareScopes(a, "atproto include:test.dynamic.access", did);
    try std.testing.expect(std.mem.indexOf(u8, grant, "collection=") == null);
    try std.testing.expect(std.mem.indexOf(u8, grant, "authority=did:plc:dynamiccollections") != null);
    try store.putOAuthToken(did, "https://dynamic.test", grant, "access", "refresh", expiry, expiry, null, null);
    const token = (try store.getOAuthToken(a, "access")).?;
    const before = try resolveSpaceWriteScopes(a, token.scope, space_type);
    try std.testing.expect(scope_rules.spaceAllows(before, .create, space_type, did, "self", "test.dynamic.first"));
    try std.testing.expect(!scope_rules.spaceAllows(before, .create, space_type, did, "self", "test.dynamic.second"));
    const explicit = try prepareScopes(a, "space:test.dynamic.space?collection=test.dynamic.first&action=create", did);
    try lexicon_cache.put(space_type,
        \\{"value":{"defs":{"main":{"type":"space","collections":["test.dynamic.second"]}}}}
    , expiry);
    const after = try resolveSpaceWriteScopes(a, token.scope, space_type);
    try std.testing.expect(!scope_rules.spaceAllows(after, .create, space_type, did, "self", "test.dynamic.first"));
    try std.testing.expect(scope_rules.spaceAllows(after, .create, space_type, did, "self", "test.dynamic.second"));
    try std.testing.expect(!scope_rules.spaceAllows(after, .create, space_type, "did:plc:other", "self", "test.dynamic.second"));
    try std.testing.expect(!scope_rules.spaceAllows(after, .manage_create, space_type, did, "self", null));
    const fixed = try resolveSpaceWriteScopes(a, explicit, space_type);
    try std.testing.expect(scope_rules.spaceAllows(fixed, .create, space_type, did, "self", "test.dynamic.first"));
    try std.testing.expect(!scope_rules.spaceAllows(fixed, .create, space_type, did, "self", "test.dynamic.second"));
    try std.testing.expect(try store.rotateOAuthToken("refresh", "next-access", "next-refresh", expiry, expiry, expiry));
    const refreshed = (try store.getOAuthToken(a, "next-access")).?;
    try std.testing.expectEqualStrings(grant, try prepareScopes(a, refreshed.scope, did));
    const current = try resolveSpaceWriteScopes(a, refreshed.scope, space_type);
    try std.testing.expect(scope_rules.spaceAllows(current, .delete, space_type, did, "self", "test.dynamic.second"));
    try lexicon_cache.put(space_type,
        \\{"value":{"defs":{"main":{"type":"space","collections":[]}}}}
    , expiry);
    const empty = try resolveSpaceWriteScopes(a, token.scope, space_type);
    try std.testing.expect(!scope_rules.spaceAllows(empty, .create, space_type, did, "self", "test.dynamic.second"));
    try std.testing.expect(scope_rules.spaceAllows(empty, .read_self, space_type, did, "self", null));
    try lexicon_cache.put(space_type, "{}", expiry);
    try std.testing.expectError(error.InvalidSpaceTypeDeclaration, resolveSpaceWriteScopes(a, token.scope, space_type));
    try std.testing.expectEqualStrings(explicit, try resolveSpaceWriteScopes(a, explicit, space_type));
    const wildcard = try prepareScopes(a, "space:*", did);
    const broad = try resolveSpaceWriteScopes(a, wildcard, space_type);
    try std.testing.expect(!scope_rules.spaceAllows(broad, .create, space_type, did, "self", "test.dynamic.second"));
}