diff --git a/app/api/sandboxes/file/route.ts b/app/api/sandboxes/file/route.ts index a6f406cc5..f044dd62c 100644 --- a/app/api/sandboxes/file/route.ts +++ b/app/api/sandboxes/file/route.ts @@ -18,7 +18,7 @@ export async function OPTIONS() { /** * GET /api/sandboxes/file * - * Retrieves the raw contents of a file from the authenticated account's + * Retrieves the raw contents of a file from the authenticated or explicitly authorized account's * sandbox GitHub repository. Resolves the github_repo from the account's * snapshot, then fetches the file at the specified path. * @@ -27,6 +27,7 @@ export async function OPTIONS() { * Query parameters: * - path: string (required) - The file path within the repository * - include_revision: "true" (optional) - Read content and blob SHA together from main + * - account_id: UUID (optional) - Target account, checked by the sandbox-list access policy * * Paths must be canonical relative paths: dot/traversal, backslashes, malformed Unicode * and leading/trailing/doubled slashes return 400, including for legacy callers. @@ -36,6 +37,7 @@ export async function OPTIONS() { * - content: string - The raw file content * - encoding: "base64" - Present for recognized binary extensions; content is base64 * - sha: string - Present for include_revision=true; use as files[].expected_sha + * - account_id: string - Present only when an explicit account_id was authorized * * Error (400/401/403/404): * - status: "error" diff --git a/app/api/sandboxes/route.ts b/app/api/sandboxes/route.ts index a1e91c927..7b19012a4 100644 --- a/app/api/sandboxes/route.ts +++ b/app/api/sandboxes/route.ts @@ -63,6 +63,8 @@ export async function POST(request: NextRequest): Promise { * Defaults to "false"; repository filetree lookup still runs when available. * - sandbox_id: (optional) Filter by a specific sandbox ID. Must be a sandbox * that your account or organization is an admin of. + * - account_id: UUID (optional) - Target account, checked by the existing account-access policy. + * Successful explicit-target reads echo account_id; omitted-target response shape is unchanged. * * Response (200): * - status: "success" diff --git a/lib/contracts/__tests__/publishedSandboxFiles.test.ts b/lib/contracts/__tests__/publishedSandboxFiles.test.ts index f154cd518..3d15cf7a8 100644 --- a/lib/contracts/__tests__/publishedSandboxFiles.test.ts +++ b/lib/contracts/__tests__/publishedSandboxFiles.test.ts @@ -29,6 +29,7 @@ vi.mock("@/lib/github/getVersionedFileContent", () => ({ getVersionedFileContent const ajv = new Ajv({ allErrors: true }); ajv.addKeyword({ keyword: "example", valid: true }); +ajv.addFormat("uuid", /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i); function publishedContract(method: string, path: string, status: number) { expect( diff --git a/lib/contracts/fixtures/published-docs.json b/lib/contracts/fixtures/published-docs.json index 15e104d9f..25be0f3ba 100644 --- a/lib/contracts/fixtures/published-docs.json +++ b/lib/contracts/fixtures/published-docs.json @@ -955,7 +955,7 @@ ], "sourceHashes": { "content/docs/source/api-reference/openapi/accounts.json": "1a5a04f9ec358a15b8339b7029c9fed5fe69c6f042c8b03b6b4f03f3aafdeeed", - "content/docs/source/api-reference/openapi/content.json": "b89165f9296a1aa98139f64ae095eefd2a5b306950170d3f15a4826de95ed036", + "content/docs/source/api-reference/openapi/content.json": "a59fa965788414731d19e031ec4b44f4a83319bdc651cb0aa49fba5a534317b0", "content/docs/source/api-reference/openapi/research.json": "053556fdeec5379fbaf6cfdbd37c721cd0793f08fa728b82c281e0c6af249457", "content/docs/source/api-reference/openapi/releases.json": "7bfbdee327e8b3e27ba39cea3fcfe1fe930997d2ea05cb19a707f926ae3bdba2", "content/docs/source/api-reference/openapi/social.json": "49c837327886827b5bc33ae4daac76f12473ecf4a6f75cc073656e9247ba73ca", @@ -1118,6 +1118,39 @@ "path": "drafts/notes.txt", "include_revision": "true" }, + "scopedReadQuery": { + "path": "drafts/notes.txt", + "include_revision": "true", + "account_id": "11111111-1111-4111-8111-111111111111" + }, + "listQuery": { + "account_id": "11111111-1111-4111-8111-111111111111", + "metadata_only": "true" + }, + "accountScopeParameters": { + "list": { + "name": "account_id", + "in": "query", + "description": "Optional target account UUID authorized by the existing account-access policy. Omit for the authenticated account. Successful explicit-target reads echo this value as account_id; this does not grant file-write access.", + "required": false, + "schema": { + "type": "string", + "format": "uuid" + }, + "example": "11111111-1111-4111-8111-111111111111" + }, + "file": { + "name": "account_id", + "in": "query", + "description": "Optional target account UUID authorized by the existing account-access policy. Omit for the authenticated account. Successful explicit-target reads echo this value as account_id; this does not grant file-write access.", + "required": false, + "schema": { + "type": "string", + "format": "uuid" + }, + "example": "11111111-1111-4111-8111-111111111111" + } + }, "upload": { "path": "drafts", "message": "Update release notes", @@ -1191,6 +1224,156 @@ } }, "responses": [ + { + "method": "GET", + "path": "/api/sandboxes", + "status": 200, + "schema": { + "type": "object", + "required": [ + "status", + "sandboxes" + ], + "description": "Response containing sandbox information", + "properties": { + "status": { + "type": "string", + "enum": [ + "success", + "error" + ], + "description": "Status of the request" + }, + "sandboxes": { + "type": "array", + "items": { + "type": "object", + "required": [ + "sandboxId", + "sandboxStatus", + "timeout", + "createdAt" + ], + "description": "A sandbox environment instance", + "properties": { + "sandboxId": { + "type": "string", + "description": "Unique identifier for the sandbox", + "example": "sbx_abc123def456" + }, + "sandboxStatus": { + "type": "string", + "enum": [ + "pending", + "running", + "stopping", + "stopped", + "failed" + ], + "description": "Current lifecycle state of the sandbox", + "example": "running" + }, + "timeout": { + "type": "integer", + "description": "Milliseconds remaining before the sandbox stops automatically", + "example": 300000 + }, + "createdAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp when the sandbox was created", + "example": "2024-01-15T10:30:00.000Z" + }, + "runId": { + "type": "string", + "description": "Unique identifier for the command execution run. Only present if a command was provided when creating the sandbox. Use this with [GET /api/tasks/runs](/api-reference/tasks/runs) to check the status and retrieve results.", + "example": "run_xyz789abc123" + } + } + }, + "description": "Array of sandbox objects" + }, + "snapshot_id": { + "type": "string", + "description": "The account's saved snapshot ID used for creating new sandboxes. Null if no snapshot has been saved.", + "example": "snap_abc123def456", + "nullable": true + }, + "github_repo": { + "type": "string", + "description": "The GitHub repository URL associated with the account's sandbox environment. Used as the filesystem source when restoring sandboxes.", + "example": "https://github.com/username/repo", + "nullable": true + }, + "filetree": { + "type": "array", + "nullable": true, + "description": "The recursive file tree of the account's GitHub repository. Null if no github_repo is set or if the fetch fails.", + "items": { + "type": "object", + "required": [ + "path", + "type", + "sha" + ], + "description": "A single entry in a GitHub repository file tree", + "properties": { + "path": { + "type": "string", + "description": "The file or directory path relative to the repository root", + "example": "src/index.ts" + }, + "type": { + "type": "string", + "enum": [ + "blob", + "tree" + ], + "description": "The type of entry: blob for files, tree for directories" + }, + "sha": { + "type": "string", + "description": "The SHA hash of the entry", + "example": "abc123def456" + }, + "size": { + "type": "integer", + "description": "The size of the file in bytes. Only present for blob entries.", + "example": 1024 + } + } + } + }, + "error": { + "type": "string", + "description": "Error message (only present if status is error)" + }, + "account_id": { + "type": "string", + "format": "uuid", + "description": "On successful GET reads only: the explicitly requested, authorized target account UUID. Present even for an explicit self target; absent when account_id was omitted. This is read scope, not write authorization.", + "example": "11111111-1111-4111-8111-111111111111" + } + } + }, + "examples": { + "ownMetadata": { + "status": "success", + "sandboxes": [], + "snapshot_id": null, + "github_repo": null, + "filetree": null + }, + "targetMetadata": { + "status": "success", + "sandboxes": [], + "snapshot_id": null, + "github_repo": null, + "filetree": null, + "account_id": "11111111-1111-4111-8111-111111111111" + } + } + }, { "method": "GET", "path": "/api/sandboxes/file", @@ -1225,8 +1408,42 @@ "pattern": "^[a-f0-9]{40}$", "description": "Present when include_revision=true; use this reader-observed blob SHA as files[].expected_sha. Absent from legacy reads. It identifies the returned bytes, not an accepted Context source version.", "example": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "account_id": { + "type": "string", + "format": "uuid", + "description": "On successful GET reads only: the explicitly requested, authorized target account UUID. Present even for an explicit self target; absent when account_id was omitted. This is read scope, not write authorization.", + "example": "11111111-1111-4111-8111-111111111111" } } + }, + "examples": { + "legacyText": { + "status": "success", + "content": "Release notes" + }, + "versionedText": { + "status": "success", + "content": "Release notes", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "versionedBinary": { + "status": "success", + "content": "aGVsbG8=", + "encoding": "base64", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "targetText": { + "status": "success", + "content": "Release notes", + "account_id": "11111111-1111-4111-8111-111111111111" + }, + "targetVersionedText": { + "status": "success", + "content": "Release notes", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "account_id": "11111111-1111-4111-8111-111111111111" + } } }, { diff --git a/lib/sandbox/__tests__/accountScopedFiles.test.ts b/lib/sandbox/__tests__/accountScopedFiles.test.ts new file mode 100644 index 000000000..6f08b9628 --- /dev/null +++ b/lib/sandbox/__tests__/accountScopedFiles.test.ts @@ -0,0 +1,268 @@ +import Ajv from "ajv"; +import { NextRequest } from "next/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { GET as readFile } from "@/app/api/sandboxes/file/route"; +import { GET as listFiles } from "@/app/api/sandboxes/route"; +import { RECOUP_ORG_ID } from "@/lib/const"; +import fixture from "@/lib/contracts/fixtures/published-docs.json"; + +const mock = vi.hoisted(() => ({ + key: vi.fn(), + token: vi.fn(), + memberships: vi.fn(), + shared: vi.fn(), + snapshots: vi.fn(), + sandboxes: vi.fn(), + resolve: vi.fn(), + raw: vi.fn(), + versioned: vi.fn(), + tree: vi.fn(), +})); +vi.mock("@/lib/auth/getAccountIdByApiKey", () => ({ getAccountIdByApiKey: mock.key })); +vi.mock("@/lib/privy/getOrCreateAccountIdByAuthToken", () => ({ + getOrCreateAccountIdByAuthToken: mock.token, +})); +vi.mock("@/lib/supabase/account_organization_ids/getAccountOrganizations", () => ({ + getAccountOrganizations: mock.memberships, +})); +vi.mock("@/lib/supabase/account_organization_ids/selectAccountOrganizationIds", () => ({ + selectAccountOrganizationIds: mock.shared, +})); +vi.mock("@/lib/supabase/account_snapshots/selectAccountSnapshots", () => ({ + selectAccountSnapshots: mock.snapshots, +})); +vi.mock("@/lib/supabase/account_sandboxes/selectAccountSandboxes", () => ({ + selectAccountSandboxes: mock.sandboxes, +})); +vi.mock("@/lib/github/resolveSubmodulePath", () => ({ resolveSubmodulePath: mock.resolve })); +vi.mock("@/lib/github/getRawFileContent", () => ({ getRawFileContent: mock.raw })); +vi.mock("@/lib/github/getVersionedFileContent", () => ({ + getVersionedFileContent: mock.versioned, +})); +vi.mock("@/lib/github/getRepoFileTree", () => ({ getRepoFileTree: mock.tree })); +vi.mock("@/lib/sandbox/getSandboxStatus", () => ({ getSandboxStatus: vi.fn() })); +vi.mock("@/lib/sandbox/createSandboxPostHandler", () => ({ createSandboxPostHandler: vi.fn() })); +vi.mock("@/lib/sandbox/deleteSandboxHandler", () => ({ deleteSandboxHandler: vi.fn() })); +vi.mock("@/lib/sandbox/updateSnapshotPatchHandler", () => ({ + updateSnapshotPatchHandler: vi.fn(), +})); + +const caller = "11111111-1111-4111-8111-111111111111"; +const target = "22222222-2222-4222-8222-222222222222"; +const org = "33333333-3333-4333-8333-333333333333"; +const sha = "a".repeat(40); +const ajv = new Ajv({ allErrors: true }); +ajv.addKeyword({ keyword: "example", valid: true }); +ajv.addFormat("uuid", /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i); +ajv.addFormat("date-time", value => !Number.isNaN(Date.parse(value))); +const matchesPublishedResponse = (kind: "file" | "list", body: unknown) => { + const path = kind === "file" ? "/api/sandboxes/file" : "/api/sandboxes"; + const contract = fixture.guardedGitFiles.responses.find( + item => item.method === "GET" && item.path === path && item.status === 200, + ); + expect(contract).toBeDefined(); + const validate = ajv.compile(contract!.schema); + expect(validate(body), JSON.stringify(validate.errors)).toBe(true); +}; +const bearer = { authorization: "Bearer synthetic-privy-token" }; +const apiKey = { "x-api-key": "recoup_sk_synthetic" }; +const repo = (account: string) => `https://github.com/example/${account}`; +const invoke = ( + kind: "file" | "list", + query: Record = {}, + headers: Record = bearer, +) => { + const params = new URLSearchParams(kind === "file" ? { path: "draft.txt", ...query } : query); + return (kind === "file" ? readFile : listFiles)( + new NextRequest( + `https://api.example/api/sandboxes${kind === "file" ? "/file" : ""}?${params}`, + { + headers, + }, + ), + ); +}; +const expectNoRepositoryAccess = () => { + for (const leaf of [ + mock.snapshots, + mock.sandboxes, + mock.resolve, + mock.raw, + mock.versioned, + mock.tree, + ]) { + expect(leaf).not.toHaveBeenCalled(); + } +}; + +beforeEach(() => { + vi.resetAllMocks(); + mock.key.mockResolvedValue(caller); + mock.token.mockResolvedValue(caller); + mock.memberships.mockResolvedValue([{ organization_id: org }]); + mock.shared.mockResolvedValue([{ account_id: target, organization_id: org }]); + mock.snapshots.mockImplementation(async account => [ + { github_repo: repo(account), snapshot_id: account }, + ]); + mock.sandboxes.mockResolvedValue([]); + mock.resolve.mockImplementation(async input => input); + mock.raw.mockResolvedValue({ content: "selected file" }); + mock.versioned.mockResolvedValue({ content: "selected revision", sha }); + mock.tree.mockResolvedValue([{ path: "draft.txt", type: "blob", sha }]); +}); + +describe.each(["file", "list"] as const)("account-scoped %s GET route", kind => { + it.each([bearer, apiKey, { authorization: "Bearer recoup_sk_synthetic" }])( + "reads and acknowledges only the authorized target with %j", + async headers => { + const response = await invoke(kind, { account_id: target }, headers); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body).toMatchObject({ status: "success", account_id: target }); + matchesPublishedResponse(kind, body); + expect(mock.memberships).toHaveBeenCalledWith({ accountId: caller }); + expect(mock.shared).toHaveBeenCalledWith(target, [org]); + expect(mock.snapshots).toHaveBeenCalledExactlyOnceWith(target); + if (kind === "file") + expect(mock.resolve).toHaveBeenCalledWith({ githubRepo: repo(target), path: "draft.txt" }); + else { + expect(mock.sandboxes).toHaveBeenCalledWith({ accountIds: [target], sandboxId: undefined }); + expect(mock.tree).toHaveBeenCalledWith(repo(target)); + } + }, + ); + + it("keeps the authenticated-account legacy response unchanged", async () => { + const response = await invoke(kind); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body).not.toHaveProperty("account_id"); + matchesPublishedResponse(kind, body); + expect(mock.snapshots).toHaveBeenCalledExactlyOnceWith(caller); + expect(mock.memberships).not.toHaveBeenCalled(); + }); + + it("accepts an explicit self target without requiring organization membership", async () => { + mock.memberships.mockResolvedValue([]); + const response = await invoke(kind, { account_id: caller }); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ account_id: caller }); + expect(mock.memberships).not.toHaveBeenCalled(); + }); + + it.each([{ shared: [] }, { shared: null }])( + "denies missing shared membership (%j) before repository access", + async ({ shared }) => { + mock.shared.mockResolvedValue(shared); + const response = await invoke(kind, { account_id: target }); + expect(response.status).toBe(403); + expectNoRepositoryAccess(); + }, + ); + + it("denies a caller without organizations before repository access", async () => { + mock.memberships.mockResolvedValue([]); + expect((await invoke(kind, { account_id: target })).status).toBe(403); + expectNoRepositoryAccess(); + }); + + it.each([org, RECOUP_ORG_ID])( + "retains the existing organization/admin rule %s", + async membership => { + mock.memberships.mockResolvedValue([{ organization_id: membership }]); + const response = await invoke(kind, { account_id: membership === org ? org : target }); + expect(response.status).toBe(200); + expect(await response.json()).toHaveProperty("account_id", membership === org ? org : target); + expect(mock.shared).not.toHaveBeenCalled(); + }, + ); + + it.each(["", "not-a-uuid"])( + "rejects malformed targets %j before auth/provider lookup", + async account_id => { + expect((await invoke(kind, { account_id })).status).toBe(400); + expect(mock.key).not.toHaveBeenCalled(); + expect(mock.token).not.toHaveBeenCalled(); + expectNoRepositoryAccess(); + }, + ); + + it.each([{}, { ...bearer, ...apiKey }])( + "rejects missing/conflicting authentication %j", + async headers => { + expect((await invoke(kind, { account_id: target }, headers)).status).toBe(401); + expectNoRepositoryAccess(); + }, + ); + + it("rejects an invalid API key before target lookup", async () => { + mock.key.mockResolvedValue(null); + expect((await invoke(kind, { account_id: target }, apiKey)).status).toBe(401); + expect(mock.memberships).not.toHaveBeenCalled(); + expectNoRepositoryAccess(); + }); +}); + +it("pairs selected-account content and SHA without falling back to a raw read", async () => { + const response = await invoke("file", { account_id: target, include_revision: "true" }); + expect(await response.json()).toEqual({ + status: "success", + account_id: target, + content: "selected revision", + sha, + }); + expect(mock.versioned).toHaveBeenCalledWith({ + githubRepo: repo(target), + path: "draft.txt", + format: undefined, + }); + expect(mock.raw).not.toHaveBeenCalled(); +}); + +it("executes the published scoped read/list queries with the documented acknowledgement", async () => { + for (const kind of ["file", "list"] as const) { + const query = + kind === "file" ? fixture.guardedGitFiles.scopedReadQuery : fixture.guardedGitFiles.listQuery; + expect(fixture.guardedGitFiles.accountScopeParameters[kind]).toMatchObject({ + name: "account_id", + in: "query", + required: false, + schema: { type: "string", format: "uuid" }, + }); + const response = await invoke(kind, query); + const body = await response.json(); + expect(response.status).toBe(200); + expect(body.account_id).toBe(query.account_id); + matchesPublishedResponse(kind, body); + } +}); + +it("preserves binary encoding with the selected account", async () => { + mock.raw.mockResolvedValue({ content: "aGVsbG8=", encoding: "base64" }); + const response = await invoke("file", { account_id: target, path: "image.png" }); + expect(await response.json()).toMatchObject({ + account_id: target, + encoding: "base64", + content: "aGVsbG8=", + }); + expect(mock.raw).toHaveBeenCalledWith({ + githubRepo: repo(target), + path: "image.png", + format: "base64", + }); +}); + +it("never falls back to the caller repository when the selected account has none", async () => { + mock.snapshots.mockResolvedValue([]); + expect((await invoke("file", { account_id: target })).status).toBe(404); + expect(mock.snapshots).toHaveBeenCalledExactlyOnceWith(target); + expect(mock.raw).not.toHaveBeenCalled(); +}); + +it.each(["../secret", "draft//notes.txt", "\\secret"])( + "retains canonical path rejection: %s", + async path => { + expect((await invoke("file", { account_id: target, path })).status).toBe(400); + expectNoRepositoryAccess(); + }, +); diff --git a/lib/sandbox/__tests__/validateGetSandboxesRequest.test.ts b/lib/sandbox/__tests__/validateGetSandboxesRequest.test.ts index 413325b44..29e022d76 100644 --- a/lib/sandbox/__tests__/validateGetSandboxesRequest.test.ts +++ b/lib/sandbox/__tests__/validateGetSandboxesRequest.test.ts @@ -174,6 +174,7 @@ describe("validateGetSandboxesRequest", () => { expect(result).toEqual({ accountIds: ["550e8400-e29b-41d4-a716-446655440000"], sandboxId: "sbx_abc123", + targetAccountId: "550e8400-e29b-41d4-a716-446655440000", }); }); }); diff --git a/lib/sandbox/getSandboxesFileHandler.ts b/lib/sandbox/getSandboxesFileHandler.ts index 9ff91292b..a1988cc4b 100644 --- a/lib/sandbox/getSandboxesFileHandler.ts +++ b/lib/sandbox/getSandboxesFileHandler.ts @@ -11,12 +11,13 @@ import { isBinaryFile } from "@/lib/github/isBinaryFile"; * Handler for retrieving file contents from a sandbox's GitHub repository. * Requires authentication via x-api-key header or Authorization bearer token. * - * Resolves the github_repo from the authenticated account's snapshot, + * Resolves the github_repo from the authenticated or explicitly authorized account's snapshot, * then fetches the raw file content from the repository. * Binary files (images, PDFs, fonts, etc.) are automatically returned as base64. * * Query parameters: * - path: The file path within the repository (required) + * - account_id: Optional authorized account UUID; echoed on success * * @param request - The request object. * @returns A NextResponse with the file content or error. @@ -66,6 +67,7 @@ export async function getSandboxesFileHandler(request: NextRequest): Promise