Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions packages/core/src/acl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { describe, expect, it, vi } from "vitest";
import { exportWorkspaceJson } from "./export.js";
import { queryFiles } from "./query.js";
import type { FileRow, StorageAdapter } from "./storage.js";
import { listTree } from "./tree.js";
import { filePermissionAllows, type TokenClaims } from "./acl.js";

function claimsWith(scopes: string[]): TokenClaims {
return {
workspaceId: "ws_test",
agentName: "agent_test",
scopes: new Set(scopes),
};
}

function file(path: string, permissions: string[] = []): FileRow {
return {
path,
revision: "rev_1",
contentType: "text/markdown",
content: "body",
encoding: "utf-8",
provider: "github",
lastEditedAt: "2026-05-31T00:00:00.000Z",
semantics: {
permissions,
},
};
}

function storage(files: FileRow[]): StorageAdapter {
const byPath = new Map(files.map((entry) => [entry.path, entry]));
return {
getFile: (path) => byPath.get(path) ?? null,
listFiles: () => files,
putFile: () => undefined,
deleteFile: () => undefined,
appendEvent: () => undefined,
listEvents: () => ({ items: [], nextCursor: null }),
getRecentEvents: () => [],
getOperation: () => null,
putOperation: () => undefined,
listOperations: () => ({ items: [], nextCursor: null }),
nextRevision: () => "rev_2",
nextOperationId: () => "op_1",
nextEventId: () => "evt_1",
enqueueWriteback: () => undefined,
getPendingWritebacks: () => [],
getWorkspaceId: () => "ws_test",
};
}

describe("ACL scope matching", () => {
it("keeps exact scope matching as the default", () => {
const claims = claimsWith(["relayfile:fs:read:/github/*"]);

expect(
filePermissionAllows(["scope:relayfile:fs:read:/github/LAYOUT.md"], "ws_test", claims),
).toBe(false);
expect(
filePermissionAllows(["scope:relayfile:fs:read:/github/*"], "ws_test", claims),
).toBe(true);
});

it("lets callers inject path-aware scope matching for tree, query, and export", () => {
const claims = claimsWith(["relayfile:fs:read:/github/*"]);
const rows = [
file("/.relayfile.acl", ["scope:relayfile:fs:read:/github/LAYOUT.md"]),
file("/github/LAYOUT.md"),
];
const repo = storage(rows);
const scopeMatches = vi.fn(
(scope: string, tokenClaims: TokenClaims | null, context) =>
scope === "relayfile:fs:read:/github/LAYOUT.md" &&
tokenClaims?.scopes.has("relayfile:fs:read:/github/*") === true &&
context.action === "read" &&
context.requestedPath === "/github/LAYOUT.md",
);

expect(listTree(repo, { path: "/github", depth: 1 }, claims).entries).toEqual(
[],
);

const aclOptions = { scopeMatches };
expect(
listTree(repo, { path: "/github", depth: 1 }, claims, aclOptions).entries.map(
(entry) => entry.path,
),
).toEqual(["/github/LAYOUT.md"]);
expect(
queryFiles(repo, { path: "/github" }, claims, aclOptions).items.map(
(entry) => entry.path,
),
).toEqual(["/github/LAYOUT.md"]);
expect(exportWorkspaceJson(repo, claims, aclOptions).map((entry) => entry.path)).toEqual([
"/github/LAYOUT.md",
]);
expect(scopeMatches).toHaveBeenCalled();
});
});
25 changes: 24 additions & 1 deletion packages/core/src/acl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ export interface ParsedPermissionRule {
value: string;
}

export interface ScopeMatchContext {
workspaceId: string;
requestedPath?: string;
action?: "read" | "write" | "manage";
}

export interface PermissionEvaluationOptions {
scopeMatches?: (
scope: string,
claims: TokenClaims | null,
context: ScopeMatchContext,
) => boolean;
requestedPath?: string;
action?: "read" | "write" | "manage";
}

// ---------------------------------------------------------------------------
// Functions — agent-3: extract from workspace.ts
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -87,6 +103,7 @@ export function filePermissionAllows(
permissions: string[] | undefined,
workspaceId: string,
claims: TokenClaims | null,
options: PermissionEvaluationOptions = {},
): boolean {
if (!permissions || permissions.length === 0) {
return true;
Expand All @@ -107,7 +124,13 @@ export function filePermissionAllows(
match = true;
break;
case "scope":
match = claims?.scopes.has(rule.value) ?? false;
match = options.scopeMatches
? options.scopeMatches(rule.value, claims, {
workspaceId,
requestedPath: options.requestedPath,
action: options.action,
})
: (claims?.scopes.has(rule.value) ?? false);
break;
case "agent":
match = claims?.agentName === rule.value;
Expand Down
14 changes: 11 additions & 3 deletions packages/core/src/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
*/

import type { StorageAdapter, FileRow } from "./storage.js";
import type { TokenClaims } from "./acl.js";
import type { PermissionEvaluationOptions, TokenClaims } from "./acl.js";
import { filePermissionAllows, resolveFilePermissions } from "./acl.js";

export type ExportFormat = "json" | "tar" | "patch";

export function exportWorkspaceJson(
storage: StorageAdapter,
claims: TokenClaims | null,
aclOptions: PermissionEvaluationOptions = {},
): FileRow[] {
const workspaceId = storage.getWorkspaceId();

Expand All @@ -28,6 +29,11 @@ export function exportWorkspaceJson(
resolveFilePermissions(storage, row.path, true),
workspaceId,
claims,
{
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: row.path,
},
Comment on lines +32 to +36

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Export ACL checks should always run as "read".

This is the content-export path, so honoring a caller-provided aclOptions.action can authorize exports against the wrong action. exportWorkspaceJson() should force action: "read" and only vary requestedPath.

Suggested fix
         {
           ...aclOptions,
-          action: aclOptions.action ?? "read",
+          action: "read",
           requestedPath: row.path,
         },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: row.path,
},
{
...aclOptions,
action: "read",
requestedPath: row.path,
},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/export.ts` around lines 32 - 36, In exportWorkspaceJson(),
ensure ACL checks always use action: "read" instead of honoring caller-provided
aclOptions.action; locate where aclOptions is spread into the ACL check object
(the snippet with "...aclOptions, action: aclOptions.action ?? 'read',
requestedPath: row.path") and change it to force action: "read" (keep
requestedPath: row.path and preserve other aclOptions fields).

),
)
.map((row) => materializeFile(storage, row));
Expand All @@ -36,15 +42,17 @@ export function exportWorkspaceJson(
export function exportWorkspacePatch(
storage: StorageAdapter,
claims: TokenClaims | null,
aclOptions: PermissionEvaluationOptions = {},
): string {
return buildUnifiedPatch(exportWorkspaceJson(storage, claims));
return buildUnifiedPatch(exportWorkspaceJson(storage, claims, aclOptions));
}

export async function exportWorkspaceTarGzip(
storage: StorageAdapter,
claims: TokenClaims | null,
aclOptions: PermissionEvaluationOptions = {},
): Promise<ArrayBuffer> {
return buildTarGzip(exportWorkspaceJson(storage, claims));
return buildTarGzip(exportWorkspaceJson(storage, claims, aclOptions));
}

export function buildUnifiedPatch(files: FileRow[]): string {
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { StorageAdapter, FileRow, Paginated, PaginationOptions } from "./st
import {
filePermissionAllows,
resolveFilePermissions,
type PermissionEvaluationOptions,
type TokenClaims,
} from "./acl.js";

Expand Down Expand Up @@ -39,6 +40,7 @@ export function queryFiles(
storage: StorageAdapter,
options: QueryOptions,
claims: TokenClaims | null,
aclOptions: PermissionEvaluationOptions = {},
): Paginated<QueryResultItem> {
const base = normalizePath(options.path ?? "/");
const provider = normalizeProvider(options.provider);
Expand Down Expand Up @@ -84,7 +86,13 @@ export function queryFiles(
if (!propertiesMatch(semantics.properties, expectedProperties)) {
continue;
}
if (!filePermissionAllows(effectivePermissions, workspaceId, claims)) {
if (
!filePermissionAllows(effectivePermissions, workspaceId, claims, {
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: row.path,
})
Comment on lines +89 to +94

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not let query authorization switch off "read".

queryFiles() is also a read surface. Allowing aclOptions.action to override the action here means a caller can evaluate file visibility with non-read semantics, which is the wrong contract for this API.

Suggested fix
       {
         ...aclOptions,
-        action: aclOptions.action ?? "read",
+        action: "read",
         requestedPath: row.path,
       })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (
!filePermissionAllows(effectivePermissions, workspaceId, claims, {
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: row.path,
})
if (
!filePermissionAllows(effectivePermissions, workspaceId, claims, {
...aclOptions,
action: "read",
requestedPath: row.path,
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/query.ts` around lines 89 - 94, The authorization check in
queryFiles() currently lets aclOptions.action override the intended "read"
semantics when calling filePermissionAllows, which can wrongly evaluate
visibility using non-read actions; change the call site so the action passed is
always "read" (ignore or override aclOptions.action) while still forwarding
other aclOptions, i.e. call filePermissionAllows(effectivePermissions,
workspaceId, claims, { ...aclOptions, action: "read", requestedPath: row.path
}), ensuring file visibility is always checked as a read operation.

) {
continue;
}

Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { StorageAdapter, PaginationOptions } from "./storage.js";
import {
filePermissionAllows,
resolveFilePermissions,
type PermissionEvaluationOptions,
type TokenClaims,
} from "./acl.js";

Expand Down Expand Up @@ -43,6 +44,7 @@ export function listTree(
storage: StorageAdapter,
options: ListTreeOptions,
claims: TokenClaims | null,
aclOptions: PermissionEvaluationOptions = {},
): TreeResult {
const base = normalizePath(options.path ?? "/");
const maxDepth = options.depth && options.depth > 0 ? options.depth : 1;
Expand All @@ -59,6 +61,11 @@ export function listTree(
resolveFilePermissions(storage, filePath, true),
workspaceId,
claims,
{
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: filePath,
},
Comment on lines +64 to +68

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Force "read" for tree ACL evaluation.

listTree() is a read API, so letting callers override action here changes authorization semantics and can make entry visibility depend on "write"/"manage" scopes instead of read scopes. Hardcode action: "read" and keep only requestedPath injected per row.

Suggested fix
         {
           ...aclOptions,
-          action: aclOptions.action ?? "read",
+          action: "read",
           requestedPath: filePath,
         },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{
...aclOptions,
action: aclOptions.action ?? "read",
requestedPath: filePath,
},
{
...aclOptions,
action: "read",
requestedPath: filePath,
},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/tree.ts` around lines 64 - 68, listTree() currently passes
through aclOptions.action allowing callers to change the ACL check; change it to
always use action: "read" so authorization is based on read scope only, i.e.,
replace the spread that includes action: aclOptions.action ?? "read" with a
literal action: "read" while still passing requestedPath (filePath) per row;
update any references where aclOptions is merged for ACL evaluation (e.g., the
object created near listTree() that includes requestedPath) to ensure callers
cannot override action.

)
) {
continue;
Expand Down
Loading