From e0a0c70559dc6b18b6bdf6c3fc4f849fa48059d2 Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 21:38:28 -0700 Subject: [PATCH 1/6] feat: add RBAC contracts and persistence --- .github/workflows/ci.yml | 3 + package.json | 2 + .../src/authorization/permission-sql.test.ts | 11 + .../src/authorization/permission-sql.ts | 29 ++ .../src/authorization/service.ts | 166 +++++++ .../src/db/authorization-store.test.ts | 86 ++++ .../src/db/authorization-store.ts | 445 ++++++++++++++++++ packages/control-plane/src/db/user-merge.ts | 388 +++++++++------ .../integration/browser-auth-callback.test.ts | 13 + .../test/integration/browser-auth.test.ts | 1 + .../control-plane/test/integration/cleanup.ts | 2 +- .../migration-0071-rbac-foundation.test.ts | 134 ++++++ .../test/integration/rbac-foundation.test.ts | 27 ++ .../integration/session-read-state.test.ts | 3 + .../test/integration/user-merge.test.ts | 128 ++++- .../test/integration/user-store.test.ts | 22 + packages/shared/package.json | 4 + packages/shared/src/index.ts | 1 + packages/shared/src/rbac.test.ts | 133 ++++++ packages/shared/src/rbac.ts | 219 +++++++++ scripts/bootstrap-workspace-owner.test.ts | 310 ++++++++++++ scripts/bootstrap-workspace-owner.ts | 284 +++++++++++ .../d1/migrations/0071_rbac_foundation.sql | 71 +++ terraform/environments/production/outputs.tf | 5 + 24 files changed, 2347 insertions(+), 140 deletions(-) create mode 100644 packages/control-plane/src/authorization/permission-sql.test.ts create mode 100644 packages/control-plane/src/authorization/permission-sql.ts create mode 100644 packages/control-plane/src/authorization/service.ts create mode 100644 packages/control-plane/src/db/authorization-store.test.ts create mode 100644 packages/control-plane/src/db/authorization-store.ts create mode 100644 packages/control-plane/test/integration/migration-0071-rbac-foundation.test.ts create mode 100644 packages/control-plane/test/integration/rbac-foundation.test.ts create mode 100644 packages/shared/src/rbac.test.ts create mode 100644 packages/shared/src/rbac.ts create mode 100644 scripts/bootstrap-workspace-owner.test.ts create mode 100644 scripts/bootstrap-workspace-owner.ts create mode 100644 terraform/d1/migrations/0071_rbac_foundation.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9f75ac730..712ab60350 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,6 +77,9 @@ jobs: - name: Test complexity reporter run: npm run test:lint-complexity + - name: Test Owner bootstrap CLI + run: npm run test:rbac-bootstrap-owner + - name: Check Prettier formatting run: npm run format:check diff --git a/package.json b/package.json index aef1af3ae6..35871e3ed3 100644 --- a/package.json +++ b/package.json @@ -14,12 +14,14 @@ "format:check": "prettier --check .", "test": "npm run test --workspaces --if-present", "test:lint-complexity": "node --test scripts/lint-complexity-message.test.mjs", + "test:rbac-bootstrap-owner": "node --experimental-transform-types --test scripts/bootstrap-workspace-owner.test.ts", "test:coverage": "npm run test:coverage --workspaces --if-present", "test:integration": "npm run test:integration --workspaces --if-present", "typecheck": "npm run build -w @open-inspect/shared && npm run typecheck --workspaces --if-present", "knip": "knip", "build": "npm run build -w @open-inspect/shared && npm run build --workspaces --if-present", "build:opencomputer-template": "npm run build-template -w @open-inspect/opencomputer-infra --", + "rbac:bootstrap-owner": "node --experimental-transform-types scripts/bootstrap-workspace-owner.ts", "prepare": "node -e \"if (process.env.CI) process.exit(0)\" && husky" }, "devDependencies": { diff --git a/packages/control-plane/src/authorization/permission-sql.test.ts b/packages/control-plane/src/authorization/permission-sql.test.ts new file mode 100644 index 0000000000..662aea9420 --- /dev/null +++ b/packages/control-plane/src/authorization/permission-sql.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; +import { rolePermissionPredicate } from "./permission-sql"; + +describe("rolePermissionPredicate", () => { + it("never grants ownership transfer through a custom role", () => { + const predicate = rolePermissionPredicate("workspace.transfer_ownership"); + + expect(predicate.sql).not.toContain("role_permissions"); + expect(predicate.values).toEqual(["owner"]); + }); +}); diff --git a/packages/control-plane/src/authorization/permission-sql.ts b/packages/control-plane/src/authorization/permission-sql.ts new file mode 100644 index 0000000000..31213fed04 --- /dev/null +++ b/packages/control-plane/src/authorization/permission-sql.ts @@ -0,0 +1,29 @@ +import { + BUILT_IN_ROLE_KEYS, + isCustomRolePermission, + permissionsForBuiltInRole, + type PermissionId, +} from "@open-inspect/shared/rbac"; + +/** Builds a parameterized role predicate that enforces built-in and custom-role grant rules. */ +export function rolePermissionPredicate(permission: PermissionId): { + sql: string; + values: string[]; +} { + const builtInRoles = BUILT_IN_ROLE_KEYS.filter((role) => + permissionsForBuiltInRole(role).includes(permission) + ); + const customRolePermission = isCustomRolePermission(permission); + const customRoleSql = customRolePermission + ? `r.key IS NULL AND EXISTS ( + SELECT 1 FROM role_permissions custom_permission + WHERE custom_permission.role_id = r.id + AND custom_permission.permission_id = ? + )` + : "0"; + return { + sql: `(r.key IN (${builtInRoles.map(() => "?").join(", ")}) + OR (${customRoleSql}))`, + values: [...builtInRoles, ...(customRolePermission ? [permission] : [])], + }; +} diff --git a/packages/control-plane/src/authorization/service.ts b/packages/control-plane/src/authorization/service.ts new file mode 100644 index 0000000000..36da1c984b --- /dev/null +++ b/packages/control-plane/src/authorization/service.ts @@ -0,0 +1,166 @@ +import { + isRegisteredPermission, + isCustomRolePermission, + permissionsForBuiltInRole, + type BuiltInRoleKey, + type EffectiveAuthorization, + type PermissionId, + type RoleSummary, + type WorkspaceMember, +} from "@open-inspect/shared/rbac"; +import { + AuthorizationStore, + type AuthorizationMutationOutcome, + type AuthorizationRoleRecord, +} from "../db/authorization-store"; +import type { SqlDatabase } from "../db/sql-database"; + +/** Represents an authorization denial that can be translated directly to an API response. */ +export class AuthorizationError extends Error { + /** Creates a denial with its HTTP status, stable error code, and optional missing grant. */ + constructor( + readonly status: number, + readonly code: string, + readonly permission?: PermissionId + ) { + super(code); + this.name = "AuthorizationError"; + } +} + +/** Signals that RBAC state changed or violated an invariant during a guarded mutation. */ +export class RbacConflictError extends Error { + /** Creates a conflict suitable for retry or refreshed administrative state. */ + constructor(message: string) { + super(message); + this.name = "RbacConflictError"; + } +} + +/** Resolves effective grants and coordinates invariant-preserving workspace RBAC mutations. */ +export class AuthorizationService { + private readonly store: AuthorizationStore; + + /** Creates a service backed by the workspace authorization database. */ + constructor(db: SqlDatabase) { + this.store = new AuthorizationStore(db); + } + + /** Resolves a user's assigned role and grants, withholding all grants while suspended. */ + async getEffectiveAuthorization(userId: string): Promise { + const record = await this.store.getEffectiveAuthorization(userId); + if (!record?.role) throw new AuthorizationError(403, "assignment_required"); + + const permissions = + record.suspendedAt === null + ? await this.loadRolePermissions(record.role.id, record.role.key) + : []; + + return { + userId: record.userId, + suspendedAt: record.suspendedAt, + role: record.role, + permissions, + }; + } + + /** Returns active authorization when the grant is present, or throws a structured denial. */ + async requirePermission( + userId: string, + permission: PermissionId + ): Promise { + const authorization = await this.getEffectiveAuthorization(userId); + if (authorization.suspendedAt !== null) { + throw new AuthorizationError(403, "active_user_required"); + } + if (!authorization.permissions.includes(permission)) { + throw new AuthorizationError(403, "permission_required", permission); + } + return authorization; + } + + /** Lists roles with their effective permissions and current assignment counts. */ + async listRoles(): Promise { + const roles = await this.store.listRoles(); + return Promise.all(roles.map((role) => this.toRoleSummary(role))); + } + + /** Returns a role's effective authorization summary, or null when it does not exist. */ + async getRole(roleId: string): Promise { + const role = await this.store.getRole(roleId); + return role ? this.toRoleSummary(role) : null; + } + + /** Lists assigned workspace members with suspension and role state. */ + async listMembers(): Promise { + return this.store.listMembers(); + } + + /** Replaces a member's role under actor revalidation and ownership invariants. */ + async replaceMemberRole(input: { + targetUserId: string; + roleId: string; + actorUserId: string; + requestId: string; + }): Promise { + this.requireApplied( + await this.store.replaceMemberRole({ + targetUserId: input.targetUserId, + roleId: input.roleId, + actorUserId: input.actorUserId, + requestId: input.requestId, + now: Date.now(), + }), + "Member role precondition conflict" + ); + } + + /** Suspends or reactivates a member while preserving an active workspace owner. */ + async replaceMemberStatus(input: { + targetUserId: string; + suspended: boolean; + actorUserId: string; + requestId: string; + }): Promise { + this.requireApplied( + await this.store.replaceMemberStatus({ + targetUserId: input.targetUserId, + suspended: input.suspended, + actorUserId: input.actorUserId, + requestId: input.requestId, + now: Date.now(), + }), + "Member status precondition conflict" + ); + } + + private async loadRolePermissions( + roleId: string, + roleKey: BuiltInRoleKey | null + ): Promise { + if (roleKey) return permissionsForBuiltInRole(roleKey); + return (await this.store.getCustomRolePermissions(roleId)).filter( + (permission): permission is PermissionId => + isRegisteredPermission(permission) && isCustomRolePermission(permission) + ); + } + + private async toRoleSummary(role: AuthorizationRoleRecord): Promise { + return { + ...role, + permissions: await this.loadRolePermissions(role.id, role.key), + }; + } + + private requireApplied(outcome: AuthorizationMutationOutcome, conflictMessage: string): void { + if (outcome.status === "actor_authorization_changed") { + throw new RbacConflictError("Actor authorization changed"); + } + if (outcome.status === "not_found") { + throw new AuthorizationError(404, "role_not_found"); + } + if (outcome.status === "conflict") { + throw new RbacConflictError(conflictMessage); + } + } +} diff --git a/packages/control-plane/src/db/authorization-store.test.ts b/packages/control-plane/src/db/authorization-store.test.ts new file mode 100644 index 0000000000..7800455036 --- /dev/null +++ b/packages/control-plane/src/db/authorization-store.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { AuthorizationStore } from "./authorization-store"; +import type { SqlDatabase, SqlResult, SqlStatement } from "./sql-database"; + +function result(changes: number, rows: unknown[] = []): SqlResult { + return { results: rows, meta: { changes } }; +} + +function fakeDatabase(options: { + batchResults?: SqlResult[]; + batchError?: Error; + allResults?: unknown[]; +}): SqlDatabase { + const statement: SqlStatement = { + bind: () => statement, + first: async () => null as T | null, + run: async () => result(0) as SqlResult, + all: async () => result(0, options.allResults) as SqlResult, + }; + return { + prepare: () => statement, + batch: async () => { + if (options.batchError) throw options.batchError; + return (options.batchResults ?? []) as SqlResult[]; + }, + }; +} + +const replaceMemberStatusInput: Parameters[0] = { + targetUserId: "target", + suspended: true, + actorUserId: "actor", + requestId: "request", + now: 100, +}; + +describe("AuthorizationStore", () => { + it("maps persistence role fields at the store boundary", async () => { + const store = new AuthorizationStore( + fakeDatabase({ + allResults: [ + { + id: "role_custom", + key: null, + name: "Custom", + description: null, + is_system: 0, + assignment_count: "4", + }, + ], + }) + ); + + await expect(store.listRoles()).resolves.toEqual([ + { + id: "role_custom", + key: null, + name: "Custom", + description: null, + assignmentCount: 4, + }, + ]); + }); + + it.each(["applied", "actor_authorization_changed", "not_found", "conflict"] as const)( + "returns the %s member status replacement batch outcome", + async (status) => { + const store = new AuthorizationStore( + fakeDatabase({ + batchResults: [result(0, [{ status }]), result(1), result(1), result(1)], + }) + ); + + await expect(store.replaceMemberStatus(replaceMemberStatusInput)).resolves.toEqual({ + status, + }); + } + ); + + it("does not classify an unexpected database failure as a conflict", async () => { + const failure = new Error("database unavailable"); + const store = new AuthorizationStore(fakeDatabase({ batchError: failure })); + + await expect(store.replaceMemberStatus(replaceMemberStatusInput)).rejects.toBe(failure); + }); +}); diff --git a/packages/control-plane/src/db/authorization-store.ts b/packages/control-plane/src/db/authorization-store.ts new file mode 100644 index 0000000000..f03b546055 --- /dev/null +++ b/packages/control-plane/src/db/authorization-store.ts @@ -0,0 +1,445 @@ +import { + BUILT_IN_ROLE_REGISTRY, + type BuiltInRoleKey, + type PermissionId, + type WorkspaceMember, +} from "@open-inspect/shared/rbac"; +import { rolePermissionPredicate } from "../authorization/permission-sql"; +import type { SqlDatabase, SqlStatement } from "./sql-database"; + +const OWNER_ROLE_ID = BUILT_IN_ROLE_REGISTRY.owner.id; + +interface EffectiveRow { + user_id: string; + suspended_at: number | null; + role_id: string | null; + role_key: BuiltInRoleKey | null; + role_name: string | null; +} + +interface RoleRow { + id: string; + key: BuiltInRoleKey | null; + name: string; + description: string | null; + assignment_count: number; +} + +interface MemberRow { + user_id: string; + display_name: string | null; + email: string | null; + suspended_at: number | null; + role_id: string; + role_key: BuiltInRoleKey | null; + role_name: string; +} + +/** Persistence view of a user's assignment and suspension state before grants are resolved. */ +export interface EffectiveAuthorizationRecord { + userId: string; + suspendedAt: number | null; + role: { id: string; key: BuiltInRoleKey | null; name: string } | null; +} + +/** Persistence view of a role and the number of users currently assigned to it. */ +export interface AuthorizationRoleRecord { + id: string; + key: BuiltInRoleKey | null; + name: string; + description: string | null; + assignmentCount: number; +} + +interface AuditInput { + requestId: string; + actorUserId: string; + action: string; + resourceType: string; + resourceId?: string | null; + targetUserId?: string | null; + reasonCode: string; + occurredAt: number; +} + +interface SqlCondition { + sql: string; + values: unknown[]; +} + +function userIsOwner(userId: string): SqlCondition { + return { + sql: `EXISTS ( + SELECT 1 FROM user_role_assignments assignment + WHERE assignment.user_id = ? AND assignment.role_id = ? + )`, + values: [userId, OWNER_ROLE_ID], + }; +} + +function anotherUnsuspendedOwner(targetUserId: string): SqlCondition { + return { + sql: `EXISTS ( + SELECT 1 FROM users other_user + JOIN user_role_assignments other_assignment ON other_assignment.user_id = other_user.id + WHERE other_assignment.role_id = ? AND other_user.suspended_at IS NULL + AND other_user.id <> ? + )`, + values: [OWNER_ROLE_ID, targetUserId], + }; +} + +/** Result of an atomic RBAC mutation after authorization and invariant checks. */ +export type AuthorizationMutationOutcome = + | { status: "applied" } + | { status: "actor_authorization_changed" } + | { status: "not_found" } + | { status: "conflict" }; + +function toEffectiveAuthorizationRecord(row: EffectiveRow): EffectiveAuthorizationRecord { + return { + userId: row.user_id, + suspendedAt: row.suspended_at, + role: + row.role_id && row.role_name + ? { id: row.role_id, key: row.role_key, name: row.role_name } + : null, + }; +} + +function toRoleRecord(row: RoleRow): AuthorizationRoleRecord { + return { + id: row.id, + key: row.key, + name: row.name, + description: row.description, + assignmentCount: Number(row.assignment_count), + }; +} + +function toMember(row: MemberRow): WorkspaceMember { + return { + userId: row.user_id, + displayName: row.display_name, + email: row.email, + suspendedAt: row.suspended_at, + role: { id: row.role_id, key: row.role_key, name: row.role_name }, + }; +} + +/** Persists RBAC reads and authorization-guarded, audited member mutations. */ +export class AuthorizationStore { + /** Creates a store using the workspace's SQL database. */ + constructor(private readonly db: SqlDatabase) {} + + /** Loads assignment and suspension state without resolving the role's permissions. */ + async getEffectiveAuthorization(userId: string): Promise { + const row = await this.db + .prepare( + `SELECT u.id AS user_id, u.suspended_at, + r.id AS role_id, r.key AS role_key, r.name AS role_name + FROM users u + LEFT JOIN user_role_assignments ura ON ura.user_id = u.id + LEFT JOIN roles r ON r.id = ura.role_id + WHERE u.id = ?` + ) + .bind(userId) + .first(); + return row ? toEffectiveAuthorizationRecord(row) : null; + } + + /** Loads raw custom-role grants for policy-layer validation against the registry. */ + async getCustomRolePermissions(roleId: string): Promise { + const result = await this.db + .prepare( + "SELECT permission_id FROM role_permissions WHERE role_id = ? ORDER BY permission_id" + ) + .bind(roleId) + .all<{ permission_id: string }>(); + return result.results.map((row) => row.permission_id); + } + + /** Lists built-in and custom roles with current assignment counts. */ + async listRoles(): Promise { + const result = await this.db + .prepare( + `SELECT r.id, r.key, r.name, r.description, + COUNT(ura.user_id) AS assignment_count + FROM roles r + LEFT JOIN user_role_assignments ura ON ura.role_id = r.id + GROUP BY r.id + ORDER BY r.is_system DESC, r.normalized_name ASC` + ) + .all(); + return result.results.map(toRoleRecord); + } + + /** Loads a role and its assignment count, or null when absent. */ + async getRole(roleId: string): Promise { + const row = await this.db + .prepare( + `SELECT r.id, r.key, r.name, r.description, + COUNT(ura.user_id) AS assignment_count + FROM roles r + LEFT JOIN user_role_assignments ura ON ura.role_id = r.id + WHERE r.id = ? GROUP BY r.id` + ) + .bind(roleId) + .first(); + return row ? toRoleRecord(row) : null; + } + + /** Lists users with role assignments; unassigned users are intentionally excluded. */ + async listMembers(): Promise { + const result = await this.db + .prepare( + `SELECT u.id AS user_id, u.display_name, u.email, u.suspended_at, + r.id AS role_id, r.key AS role_key, r.name AS role_name + FROM users u + JOIN user_role_assignments ura ON ura.user_id = u.id + JOIN roles r ON r.id = ura.role_id + ORDER BY COALESCE(u.display_name, u.email, u.id) COLLATE NOCASE` + ) + .all(); + return result.results.map(toMember); + } + + /** Atomically revalidates the actor, preserves owner invariants, updates the role, and audits. */ + async replaceMemberRole(input: { + targetUserId: string; + roleId: string; + actorUserId: string; + requestId: string; + now: number; + }): Promise { + const transferGuard = rolePermissionPredicate("workspace.transfer_ownership"); + const targetIsOwner = userIsOwner(input.targetUserId); + const otherOwnerExists = anotherUnsuspendedOwner(input.targetUserId); + const mutation = this.mutationConditions( + input.actorUserId, + ["workspace.members.manage"], + { + sql: `EXISTS (SELECT 1 FROM roles WHERE id = ?) + AND EXISTS (SELECT 1 FROM user_role_assignments WHERE user_id = ?) + AND ( + ? = ? + OR NOT (${targetIsOwner.sql}) + OR (${otherOwnerExists.sql}) + )`, + values: [ + input.roleId, + input.targetUserId, + input.roleId, + OWNER_ROLE_ID, + ...targetIsOwner.values, + ...otherOwnerExists.values, + ], + }, + { + actor: { + sql: `(? <> ? AND NOT (${targetIsOwner.sql})) OR ${transferGuard.sql}`, + values: [input.roleId, OWNER_ROLE_ID, ...targetIsOwner.values, ...transferGuard.values], + }, + } + ); + const results = await this.db.batch([ + mutation.outcome, + this.auditStatement( + { + requestId: input.requestId, + actorUserId: input.actorUserId, + action: "workspace.member_role_updated", + resourceType: "user", + resourceId: input.targetUserId, + targetUserId: input.targetUserId, + reasonCode: "member_role_updated", + occurredAt: input.now, + }, + mutation.applied, + mutation.auditId + ), + this.db + .prepare(`UPDATE users SET updated_at = ? WHERE id = ? AND ${mutation.writes.sql}`) + .bind(input.now, input.targetUserId, ...mutation.writes.values), + this.db + .prepare( + `UPDATE user_role_assignments SET role_id = ? + WHERE user_id = ? AND ${mutation.writes.sql}` + ) + .bind(input.roleId, input.targetUserId, ...mutation.writes.values), + ]); + return this.readMutationOutcome(results[0]); + } + + /** Atomically revalidates the actor, preserves owner invariants, changes status, and audits. */ + async replaceMemberStatus(input: { + targetUserId: string; + suspended: boolean; + actorUserId: string; + requestId: string; + now: number; + }): Promise { + const transferGuard = rolePermissionPredicate("workspace.transfer_ownership"); + const targetIsOwner = userIsOwner(input.targetUserId); + const otherOwnerExists = anotherUnsuspendedOwner(input.targetUserId); + const mutation = this.mutationConditions( + input.actorUserId, + ["workspace.members.manage"], + { + sql: `EXISTS ( + SELECT 1 FROM users + JOIN user_role_assignments ON user_role_assignments.user_id = users.id + WHERE users.id = ? + ) + AND ( + ? = 0 + OR NOT (${targetIsOwner.sql}) + OR (${otherOwnerExists.sql}) + )`, + values: [ + input.targetUserId, + input.suspended ? 1 : 0, + ...targetIsOwner.values, + ...otherOwnerExists.values, + ], + }, + { + actor: { + sql: `NOT (${targetIsOwner.sql}) OR ${transferGuard.sql}`, + values: [...targetIsOwner.values, ...transferGuard.values], + }, + } + ); + const statements: SqlStatement[] = [ + mutation.outcome, + this.auditStatement( + { + requestId: input.requestId, + actorUserId: input.actorUserId, + action: "workspace.member_status_updated", + resourceType: "user", + resourceId: input.targetUserId, + targetUserId: input.targetUserId, + reasonCode: "member_status_updated", + occurredAt: input.now, + }, + mutation.applied, + mutation.auditId + ), + ]; + if (input.suspended) { + statements.push( + this.db + .prepare(`DELETE FROM auth_sessions WHERE userId = ? AND ${mutation.writes.sql}`) + .bind(input.targetUserId, ...mutation.writes.values) + ); + } + statements.push( + this.db + .prepare( + `UPDATE users SET suspended_at = ?, updated_at = ? + WHERE id = ? AND ${mutation.writes.sql}` + ) + .bind( + input.suspended ? input.now : null, + input.now, + input.targetUserId, + ...mutation.writes.values + ) + ); + const results = await this.db.batch(statements); + return this.readMutationOutcome(results[0]); + } + + private mutationConditions( + actorUserId: string, + permissions: PermissionId[], + resourceCondition: SqlCondition, + options?: { actor?: SqlCondition; notFound?: SqlCondition } + ): { + outcome: SqlStatement; + applied: SqlCondition; + writes: SqlCondition; + auditId: string; + } { + const permissionGuards = permissions.map(rolePermissionPredicate); + const actor: SqlCondition = { + sql: `EXISTS ( + SELECT 1 FROM users u + JOIN user_role_assignments ura ON ura.user_id = u.id + JOIN roles r ON r.id = ura.role_id + WHERE u.id = ? AND u.suspended_at IS NULL + AND ${permissionGuards.map((guard) => guard.sql).join(" AND ")} + ${options?.actor ? `AND (${options.actor.sql})` : ""} + )`, + values: [ + actorUserId, + ...permissionGuards.flatMap((guard) => guard.values), + ...(options?.actor?.values ?? []), + ], + }; + const applied: SqlCondition = { + sql: `(${actor.sql}) AND (${resourceCondition.sql})`, + values: [...actor.values, ...resourceCondition.values], + }; + const auditId = crypto.randomUUID(); + return { + outcome: this.db + .prepare( + `SELECT CASE + WHEN NOT (${actor.sql}) THEN 'actor_authorization_changed' + ${options?.notFound ? `WHEN (${options.notFound.sql}) THEN 'not_found'` : ""} + WHEN NOT (${resourceCondition.sql}) THEN 'conflict' + ELSE 'applied' + END AS status` + ) + .bind(...actor.values, ...(options?.notFound?.values ?? []), ...resourceCondition.values), + applied, + writes: { + sql: "EXISTS (SELECT 1 FROM authorization_audit_events WHERE id = ?)", + values: [auditId], + }, + auditId, + }; + } + + private readMutationOutcome(result: { results: unknown[] }): AuthorizationMutationOutcome { + const status = (result.results[0] as { status?: unknown } | undefined)?.status; + if ( + status !== "applied" && + status !== "actor_authorization_changed" && + status !== "not_found" && + status !== "conflict" + ) { + throw new Error("Invalid authorization mutation outcome"); + } + return { status }; + } + + private auditStatement( + input: AuditInput, + condition: SqlCondition, + auditId: string + ): SqlStatement { + return this.db + .prepare( + `INSERT INTO authorization_audit_events + (id, occurred_at, request_id, principal_kind, + actor_user_id_snapshot, action, resource_type, resource_id, + target_user_id_snapshot, reason_code) + SELECT ?, ?, ?, 'user', ?, ?, ?, ?, ?, ? WHERE ${condition.sql}` + ) + .bind( + auditId, + input.occurredAt, + input.requestId, + input.actorUserId, + input.action, + input.resourceType, + input.resourceId ?? null, + input.targetUserId ?? null, + input.reasonCode, + ...condition.values + ); + } +} diff --git a/packages/control-plane/src/db/user-merge.ts b/packages/control-plane/src/db/user-merge.ts index d14079eb40..e098a2815a 100644 --- a/packages/control-plane/src/db/user-merge.ts +++ b/packages/control-plane/src/db/user-merge.ts @@ -1,4 +1,4 @@ -import type { SqlDatabase, SqlStatement } from "./sql-database"; +import type { SqlDatabase, SqlResult, SqlStatement } from "./sql-database"; /** * Split-merge primitive: converge a loser canonical user's entire graph onto @@ -26,8 +26,9 @@ import type { SqlDatabase, SqlStatement } from "./sql-database"; * the preceding statement, so a stop exactly between those two statements * is not re-derivable from the database. The CLI prints a recovery record * before executing to cover that residual case. - * - Browser sessions (`auth_sessions`) are re-pointed, not deleted — the - * merged person stays signed in as the survivor. + * - Browser sessions (`auth_sessions`) issued to the loser are deleted. An + * issued bearer credential is never rewritten to authenticate as another + * canonical user. * - Verification never transfers to an unproven address: the loser's email * (and its `email_verified` flag) backfills the survivor only when the * survivor has no email of its own. @@ -57,20 +58,147 @@ export interface UserMergeOptions { readonly dryRun?: boolean; } -interface UserMergeCounts { - identitiesDeduped: number; - identitiesRepointed: number; - readStatesDeduped: number; - readStatesRepointed: number; - sessionsRepointed: number; - authSessionsRepointed: number; - automationsOwnedRepointed: number; - automationsCreatedRepointed: number; - scmTokensRepointed: number; - canonicalEmailBackfilled: number; - usersDeleted: number; +const USER_MERGE_COUNT_KEYS = [ + "identitiesDeduped", + "identitiesRepointed", + "readStatesDeduped", + "readStatesRepointed", + "sessionsRepointed", + "authSessionsDeleted", + "automationsOwnedRepointed", + "automationsCreatedRepointed", + "scmTokensRepointed", + "skillProfileItemsMerged", + "skillProfilesDeduped", + "skillProfilesRepointed", + "roleAssignmentsRemoved", + "providerAccountAuthorizationsRepointed", + "providerAccountAuthorizationAttemptsRepointed", + "keyboardShortcutPreferencesDeduped", + "keyboardShortcutPreferencesRepointed", + "auditEventsCreated", + "canonicalEmailBackfilled", + "usersDeleted", +] as const; + +type UserMergeCountKey = (typeof USER_MERGE_COUNT_KEYS)[number]; +type UserMergeCounts = Record; + +interface MergeOperation { + readonly key: UserMergeCountKey; + readonly execute: (db: SqlDatabase, survivorId: string, loserId: string) => SqlStatement; + readonly preview: (db: SqlDatabase, survivorId: string, loserId: string) => SqlStatement; + readonly subtract?: UserMergeCountKey; +} + +function regularRepoint(key: UserMergeCountKey, table: string, column = "user_id"): MergeOperation { + return { + key, + execute: (db, survivorId, loserId) => + db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).bind(survivorId, loserId), + preview: (db, _survivorId, loserId) => + db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE ${column} = ?`).bind(loserId), + }; } +function regularDelete(key: UserMergeCountKey, table: string, column = "user_id"): MergeOperation { + return { + key, + execute: (db, _survivorId, loserId) => + db.prepare(`DELETE FROM ${table} WHERE ${column} = ?`).bind(loserId), + preview: (db, _survivorId, loserId) => + db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE ${column} = ?`).bind(loserId), + }; +} + +function dedupeThenRepoint(options: { + readonly dedupeKey: UserMergeCountKey; + readonly repointKey: UserMergeCountKey; + readonly table: string; + readonly collision: string; +}): readonly [MergeOperation, MergeOperation] { + return [ + { + key: options.dedupeKey, + execute: (db, survivorId, loserId) => + db + .prepare(`DELETE FROM ${options.table} WHERE user_id = ? AND ${options.collision}`) + .bind(loserId, survivorId), + preview: (db, survivorId, loserId) => + db + .prepare( + `SELECT COUNT(*) AS count FROM ${options.table} + WHERE user_id = ? AND ${options.collision}` + ) + .bind(loserId, survivorId), + }, + { + ...regularRepoint(options.repointKey, options.table), + subtract: options.dedupeKey, + }, + ]; +} + +const BEFORE_SKILL_PROFILE_OPERATIONS = [ + ...dedupeThenRepoint({ + dedupeKey: "identitiesDeduped", + repointKey: "identitiesRepointed", + table: "user_identities", + collision: `EXISTS ( + SELECT 1 FROM user_identities AS survivor_identity + WHERE survivor_identity.user_id = ? + AND survivor_identity.provider = user_identities.provider + AND survivor_identity.provider_user_id = user_identities.provider_user_id + )`, + }), + ...dedupeThenRepoint({ + dedupeKey: "readStatesDeduped", + repointKey: "readStatesRepointed", + table: "session_read_states", + collision: `EXISTS ( + SELECT 1 FROM session_read_states AS survivor_state + WHERE survivor_state.user_id = ? + AND survivor_state.session_id = session_read_states.session_id + )`, + }), + regularRepoint("sessionsRepointed", "sessions"), + regularDelete("authSessionsDeleted", "auth_sessions", "userId"), + regularRepoint("automationsOwnedRepointed", "automations"), + regularRepoint("automationsCreatedRepointed", "automations", "created_by"), + regularRepoint("scmTokensRepointed", "user_scm_tokens"), +] as const satisfies readonly MergeOperation[]; + +const SKILL_PROFILE_OPERATIONS = dedupeThenRepoint({ + dedupeKey: "skillProfilesDeduped", + repointKey: "skillProfilesRepointed", + table: "skill_profiles", + collision: `EXISTS ( + SELECT 1 FROM skill_profiles survivor_profile + WHERE survivor_profile.user_id = ? AND survivor_profile.name = skill_profiles.name + )`, +}); + +const FINAL_REPOINT_OPERATIONS = [ + regularRepoint("providerAccountAuthorizationsRepointed", "model_provider_account_authorizations"), + regularRepoint( + "providerAccountAuthorizationAttemptsRepointed", + "model_provider_account_authorization_attempts" + ), + ...dedupeThenRepoint({ + dedupeKey: "keyboardShortcutPreferencesDeduped", + repointKey: "keyboardShortcutPreferencesRepointed", + table: "keyboard_shortcut_preferences", + collision: `EXISTS (SELECT 1 FROM keyboard_shortcut_preferences WHERE user_id = ?)`, + }), +] as const satisfies readonly MergeOperation[]; + +const TABLE_OPERATIONS = [ + ...BEFORE_SKILL_PROFILE_OPERATIONS, + ...SKILL_PROFILE_OPERATIONS, + ...FINAL_REPOINT_OPERATIONS, +] as const; + +/** Counts and identities produced by a user merge or dry-run preview. */ export interface UserMergeResult { readonly survivorId: string; readonly loserId: string; @@ -78,6 +206,9 @@ export interface UserMergeResult { readonly counts: UserMergeCounts; } +/** + * Merge a canonical user into a survivor after validating their RBAC assignments. + */ export async function mergeUsers( db: SqlDatabase, options: UserMergeOptions @@ -87,9 +218,13 @@ export async function mergeUsers( throw new UserMergeError("Survivor and loser must be different users"); } const survivor = await db - .prepare(`SELECT id, email FROM users WHERE id = ?`) + .prepare(`SELECT id, email, suspended_at FROM users WHERE id = ?`) .bind(survivorId) - .first<{ id: string; email: string | null }>(); + .first<{ + id: string; + email: string | null; + suspended_at: number | null; + }>(); if (!survivor) { throw new UserMergeError(`Survivor user ${survivorId} not found`); } @@ -98,10 +233,45 @@ export async function mergeUsers( const loser = await db .prepare(`SELECT id, email, email_verified FROM users WHERE id = ?`) .bind(loserId) - .first<{ id: string; email: string | null; email_verified: number }>(); + .first<{ + id: string; + email: string | null; + email_verified: number; + }>(); + if (!loser) { + return { survivorId, loserId, dryRun: options.dryRun === true, counts: emptyCounts() }; + } const survivorEmail = normalizeEmail(survivor.email); const loserEmail = normalizeEmail(loser?.email); + const [survivorAssignment, loserAssignment] = await db.batch<{ + role_id: string; + role_key: string | null; + }>([ + db + .prepare( + `SELECT ura.role_id, r.key AS role_key FROM user_role_assignments ura + JOIN roles r ON r.id = ura.role_id WHERE ura.user_id = ?` + ) + .bind(survivorId), + db + .prepare( + `SELECT ura.role_id, r.key AS role_key FROM user_role_assignments ura + JOIN roles r ON r.id = ura.role_id WHERE ura.user_id = ?` + ) + .bind(loserId), + ]); + const survivorRole = survivorAssignment.results[0]; + const loserRole = loserAssignment.results[0]; + if (!survivorRole || !loserRole) { + throw new UserMergeError("Both users must have explicit role assignments before merging"); + } + if (survivorRole && loserRole && survivorRole.role_id !== loserRole.role_id) { + throw new UserMergeError("Resolve conflicting user roles before merging"); + } + if (loserRole?.role_key === "owner" && survivor.suspended_at !== null) { + throw new UserMergeError("The surviving Owner must be active before merging"); + } // The loser's email backfills an email-less survivor after the loser row's // deletion frees the unique slot; its verification state carries with it. const backfillEmail = !survivorEmail && loserEmail ? loserEmail : null; @@ -117,79 +287,59 @@ export async function mergeUsers( } const statements: SqlStatement[] = []; - const track: Partial> = {}; - const add = (key: keyof UserMergeCounts, statement: SqlStatement) => { + const track: Partial> = {}; + const add = (key: UserMergeCountKey, statement: SqlStatement) => { track[key] = statements.length; statements.push(statement); }; + const addOperations = (operations: readonly MergeOperation[]) => { + for (const operation of operations) { + add(operation.key, operation.execute(db, survivorId, loserId)); + } + }; // Dedup before re-pointing: drop loser rows whose target slot the survivor // already occupies (identities under idx_user_identities_provider; read // states routinely, where both split rows read the same session). + addOperations(BEFORE_SKILL_PROFILE_OPERATIONS); + + // Merge items before deleting colliding skill profiles. add( - "identitiesDeduped", + "skillProfileItemsMerged", db .prepare( - `DELETE FROM user_identities - WHERE user_id = ? - AND EXISTS ( - SELECT 1 FROM user_identities AS survivor_identity - WHERE survivor_identity.user_id = ? - AND survivor_identity.provider = user_identities.provider - AND survivor_identity.provider_user_id = user_identities.provider_user_id - )` + `INSERT OR IGNORE INTO skill_profile_items (profile_id, skill_id) + SELECT survivor_profile.id, loser_item.skill_id + FROM skill_profiles loser_profile + JOIN skill_profiles survivor_profile + ON survivor_profile.user_id = ? AND survivor_profile.name = loser_profile.name + JOIN skill_profile_items loser_item ON loser_item.profile_id = loser_profile.id + WHERE loser_profile.user_id = ?` ) - .bind(loserId, survivorId) + .bind(survivorId, loserId) ); + addOperations(SKILL_PROFILE_OPERATIONS); + + // Preserve the survivor's RBAC assignment before deleting the loser. add( - "identitiesRepointed", - db.prepare(`UPDATE user_identities SET user_id = ? WHERE user_id = ?`).bind(survivorId, loserId) + "roleAssignmentsRemoved", + db.prepare("DELETE FROM user_role_assignments WHERE user_id = ?").bind(loserId) ); + addOperations(FINAL_REPOINT_OPERATIONS); + + // Record the merge before deleting the user so the snapshots remain explicit. add( - "readStatesDeduped", + "auditEventsCreated", db .prepare( - `DELETE FROM session_read_states - WHERE user_id = ? - AND EXISTS ( - SELECT 1 FROM session_read_states AS survivor_state - WHERE survivor_state.user_id = ? - AND survivor_state.session_id = session_read_states.session_id - )` + `INSERT INTO authorization_audit_events + (id, occurred_at, request_id, principal_kind, + actor_service_snapshot, action, resource_type, resource_id, + target_user_id_snapshot, reason_code) + VALUES (?, ?, 'user-merge', 'service', 'control-plane', + 'workspace.user_merged', 'user', ?, ?, 'operator_merge')` ) - .bind(loserId, survivorId) - ); - add( - "readStatesRepointed", - db - .prepare(`UPDATE session_read_states SET user_id = ? WHERE user_id = ?`) - .bind(survivorId, loserId) - ); - add( - "sessionsRepointed", - db.prepare(`UPDATE sessions SET user_id = ? WHERE user_id = ?`).bind(survivorId, loserId) - ); - // Browser sessions re-point (FK → users): the person stays signed in and - // is simply the survivor from the next request on. - add( - "authSessionsRepointed", - db.prepare(`UPDATE auth_sessions SET userId = ? WHERE userId = ?`).bind(survivorId, loserId) - ); - add( - "automationsOwnedRepointed", - db.prepare(`UPDATE automations SET user_id = ? WHERE user_id = ?`).bind(survivorId, loserId) - ); - // Value-conditional: created_by is compared for exact equality with the - // loser's canonical id, so legacy GitHub numeric ids pass through. - add( - "automationsCreatedRepointed", - db - .prepare(`UPDATE automations SET created_by = ? WHERE created_by = ?`) - .bind(survivorId, loserId) - ); - add( - "scmTokensRepointed", - db.prepare(`UPDATE user_scm_tokens SET user_id = ? WHERE user_id = ?`).bind(survivorId, loserId) + .bind(crypto.randomUUID(), Date.now(), survivorId, loserId) ); add("usersDeleted", db.prepare(`DELETE FROM users WHERE id = ?`).bind(loserId)); @@ -213,10 +363,10 @@ export async function mergeUsers( ); } - const results = await db.batch(statements); + const results: SqlResult[] = await db.batch(statements); const counts = emptyCounts(); - for (const [key, index] of Object.entries(track) as [keyof UserMergeCounts, number][]) { + for (const [key, index] of Object.entries(track) as [UserMergeCountKey, number][]) { counts[key] = results[index]?.meta.changes ?? 0; } if (loser) { @@ -228,19 +378,7 @@ export async function mergeUsers( } function emptyCounts(): UserMergeCounts { - return { - identitiesDeduped: 0, - identitiesRepointed: 0, - readStatesDeduped: 0, - readStatesRepointed: 0, - sessionsRepointed: 0, - authSessionsRepointed: 0, - automationsOwnedRepointed: 0, - automationsCreatedRepointed: 0, - scmTokensRepointed: 0, - canonicalEmailBackfilled: 0, - usersDeleted: 0, - }; + return Object.fromEntries(USER_MERGE_COUNT_KEYS.map((key) => [key, 0])) as UserMergeCounts; } async function previewCounts( @@ -249,48 +387,34 @@ async function previewCounts( loserId: string, backfillEmail: string | null ): Promise { - const [ - identitiesDeduped, - identities, - readStatesDeduped, - readStates, - sessions, - authSessions, - automationsOwned, - automationsCreated, - scmTokens, - users, - ] = await db.batch<{ count: number }>([ + const operationResults = await db.batch<{ count: number }>( + TABLE_OPERATIONS.map((operation) => operation.preview(db, survivorId, loserId)) + ); + const operationCounts = emptyCounts(); + for (const [index, operation] of TABLE_OPERATIONS.entries()) { + const total = operationResults[index]?.results[0]?.count ?? 0; + operationCounts[operation.key] = + total - (operation.subtract ? operationCounts[operation.subtract] : 0); + } + + const [skillProfileItemsMerged, roleAssignments, users] = await db.batch<{ count: number }>([ db .prepare( - `SELECT COUNT(*) AS count FROM user_identities - WHERE user_id = ? - AND EXISTS ( - SELECT 1 FROM user_identities AS survivor_identity - WHERE survivor_identity.user_id = ? - AND survivor_identity.provider = user_identities.provider - AND survivor_identity.provider_user_id = user_identities.provider_user_id + `SELECT COUNT(*) AS count FROM skill_profile_items loser_item + JOIN skill_profiles loser_profile ON loser_profile.id = loser_item.profile_id + JOIN skill_profiles survivor_profile + ON survivor_profile.user_id = ? AND survivor_profile.name = loser_profile.name + WHERE loser_profile.user_id = ? + AND NOT EXISTS ( + SELECT 1 FROM skill_profile_items survivor_item + WHERE survivor_item.profile_id = survivor_profile.id + AND survivor_item.skill_id = loser_item.skill_id )` ) - .bind(loserId, survivorId), - db.prepare(`SELECT COUNT(*) AS count FROM user_identities WHERE user_id = ?`).bind(loserId), + .bind(survivorId, loserId), db - .prepare( - `SELECT COUNT(*) AS count FROM session_read_states - WHERE user_id = ? - AND EXISTS ( - SELECT 1 FROM session_read_states AS survivor_state - WHERE survivor_state.user_id = ? - AND survivor_state.session_id = session_read_states.session_id - )` - ) - .bind(loserId, survivorId), - db.prepare(`SELECT COUNT(*) AS count FROM session_read_states WHERE user_id = ?`).bind(loserId), - db.prepare(`SELECT COUNT(*) AS count FROM sessions WHERE user_id = ?`).bind(loserId), - db.prepare(`SELECT COUNT(*) AS count FROM auth_sessions WHERE userId = ?`).bind(loserId), - db.prepare(`SELECT COUNT(*) AS count FROM automations WHERE user_id = ?`).bind(loserId), - db.prepare(`SELECT COUNT(*) AS count FROM automations WHERE created_by = ?`).bind(loserId), - db.prepare(`SELECT COUNT(*) AS count FROM user_scm_tokens WHERE user_id = ?`).bind(loserId), + .prepare(`SELECT COUNT(*) AS count FROM user_role_assignments WHERE user_id = ?`) + .bind(loserId), db.prepare(`SELECT COUNT(*) AS count FROM users WHERE id = ?`).bind(loserId), ]); @@ -311,16 +435,10 @@ async function previewCounts( } return { - ...emptyCounts(), - identitiesDeduped: count(identitiesDeduped), - identitiesRepointed: count(identities) - count(identitiesDeduped), - readStatesDeduped: count(readStatesDeduped), - readStatesRepointed: count(readStates) - count(readStatesDeduped), - sessionsRepointed: count(sessions), - authSessionsRepointed: count(authSessions), - automationsOwnedRepointed: count(automationsOwned), - automationsCreatedRepointed: count(automationsCreated), - scmTokensRepointed: count(scmTokens), + ...operationCounts, + skillProfileItemsMerged: count(skillProfileItemsMerged), + roleAssignmentsRemoved: count(roleAssignments), + auditEventsCreated: count(users), canonicalEmailBackfilled, usersDeleted: count(users), }; diff --git a/packages/control-plane/test/integration/browser-auth-callback.test.ts b/packages/control-plane/test/integration/browser-auth-callback.test.ts index dc3f54a226..df32d4b147 100644 --- a/packages/control-plane/test/integration/browser-auth-callback.test.ts +++ b/packages/control-plane/test/integration/browser-auth-callback.test.ts @@ -317,6 +317,19 @@ describe("browser auth callback", () => { .bind(session.user.id) .first<{ id: string }>(); expect(account).not.toBeNull(); + await expect( + env.DB.prepare( + `SELECT r.key FROM user_role_assignments ura + JOIN roles r ON r.id = ura.role_id WHERE ura.user_id = ?` + ) + .bind(session.user.id) + .first() + ).resolves.toEqual({ key: "member" }); + await expect( + env.DB.prepare( + "SELECT COUNT(*) AS count FROM authorization_audit_events WHERE action = 'workspace.owner_bootstrapped'" + ).first() + ).resolves.toEqual({ count: 0 }); const enrichment = await resolveGitHubEnrichmentForRequest( env, diff --git a/packages/control-plane/test/integration/browser-auth.test.ts b/packages/control-plane/test/integration/browser-auth.test.ts index 2aaa7de112..9eb77f58b5 100644 --- a/packages/control-plane/test/integration/browser-auth.test.ts +++ b/packages/control-plane/test/integration/browser-auth.test.ts @@ -29,6 +29,7 @@ const EXPECTED_COLUMNS: Record = { ["created_at", "INTEGER", 1, 0], ["updated_at", "INTEGER", 1, 0], ["email_verified", "INTEGER", 1, 0], + ["suspended_at", "INTEGER", 0, 0], ], user_identities: [ ["id", "TEXT", 0, 1], diff --git a/packages/control-plane/test/integration/cleanup.ts b/packages/control-plane/test/integration/cleanup.ts index 98b5ebf436..10f84a361e 100644 --- a/packages/control-plane/test/integration/cleanup.ts +++ b/packages/control-plane/test/integration/cleanup.ts @@ -6,6 +6,6 @@ import { env } from "cloudflare:test"; */ export async function cleanD1Tables(): Promise { await env.DB.exec( - "DELETE FROM auth_verifications; DELETE FROM auth_sessions; DELETE FROM automation_model_provider_auth; DELETE FROM automation_slack_channels; DELETE FROM automation_runs; DELETE FROM automation_invocations; DELETE FROM automation_repositories; DELETE FROM automation_environments; DELETE FROM automations; DELETE FROM pr_autofix_feedback; DELETE FROM session_model_provider_auth; DELETE FROM session_read_states; DELETE FROM session_pull_requests; DELETE FROM session_repositories; DELETE FROM child_admission_leases; DELETE FROM session_skill_revisions; DELETE FROM session_skill_manifests; DELETE FROM sessions; DELETE FROM model_provider_account_authorization_attempts; DELETE FROM model_provider_account_authorizations; DELETE FROM model_provider_account_defaults; DELETE FROM model_provider_account_credentials; DELETE FROM model_provider_accounts; DELETE FROM skill_profile_items; DELETE FROM skill_profiles; DELETE FROM skill_assignments; DELETE FROM skill_import_sources; DELETE FROM skill_revision_files; DELETE FROM skill_revisions; DELETE FROM skills; UPDATE skills_catalog_state SET generation = 0 WHERE singleton = 1; DELETE FROM user_scm_tokens; DELETE FROM repo_metadata; DELETE FROM repo_secrets; DELETE FROM global_secrets; DELETE FROM commit_signing_configuration; DELETE FROM integration_settings; DELETE FROM integration_repo_settings; DELETE FROM integration_environment_settings; DELETE FROM model_preferences; DELETE FROM mcp_servers; DELETE FROM keyboard_shortcut_preferences; DELETE FROM user_identities; DELETE FROM users; DELETE FROM image_builds; DELETE FROM environment_secrets; DELETE FROM environment_repositories; DELETE FROM environments;" + "DELETE FROM auth_verifications; DELETE FROM auth_sessions; DELETE FROM automation_model_provider_auth; DELETE FROM automation_slack_channels; DELETE FROM automation_runs; DELETE FROM automation_invocations; DELETE FROM automation_repositories; DELETE FROM automation_environments; DELETE FROM automations; DELETE FROM pr_autofix_feedback; DELETE FROM session_model_provider_auth; DELETE FROM session_read_states; DELETE FROM session_pull_requests; DELETE FROM session_repositories; DELETE FROM child_admission_leases; DELETE FROM session_skill_revisions; DELETE FROM session_skill_manifests; DELETE FROM sessions; DELETE FROM model_provider_account_authorization_attempts; DELETE FROM model_provider_account_authorizations; DELETE FROM model_provider_account_defaults; DELETE FROM model_provider_account_credentials; DELETE FROM model_provider_accounts; DELETE FROM skill_profile_items; DELETE FROM skill_profiles; DELETE FROM skill_assignments; DELETE FROM skill_import_sources; DELETE FROM skill_revision_files; DELETE FROM skill_revisions; DELETE FROM skills; UPDATE skills_catalog_state SET generation = 0 WHERE singleton = 1; DELETE FROM user_scm_tokens; DELETE FROM repo_metadata; DELETE FROM repo_secrets; DELETE FROM global_secrets; DELETE FROM commit_signing_configuration; DELETE FROM integration_settings; DELETE FROM integration_repo_settings; DELETE FROM model_preferences; DELETE FROM mcp_servers; DELETE FROM keyboard_shortcut_preferences; DELETE FROM authorization_audit_events; DELETE FROM user_role_assignments; DELETE FROM role_permissions WHERE role_id IN (SELECT id FROM roles WHERE is_system = 0); DELETE FROM roles WHERE is_system = 0; DELETE FROM user_identities; DELETE FROM users; DELETE FROM image_builds; DELETE FROM environment_secrets; DELETE FROM environment_repositories; DELETE FROM environments;" ); } diff --git a/packages/control-plane/test/integration/migration-0071-rbac-foundation.test.ts b/packages/control-plane/test/integration/migration-0071-rbac-foundation.test.ts new file mode 100644 index 0000000000..2c98a72e70 --- /dev/null +++ b/packages/control-plane/test/integration/migration-0071-rbac-foundation.test.ts @@ -0,0 +1,134 @@ +import { env } from "cloudflare:test"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { cleanD1Tables } from "./cleanup"; + +const migration = () => { + const entry = env.TEST_MIGRATIONS.find((candidate) => candidate.name.startsWith("0071")); + if (!entry) throw new Error("Migration 0071 not found in TEST_MIGRATIONS"); + return entry; +}; + +async function tableColumns(table: string): Promise { + const result = await env.DB.prepare(`PRAGMA table_info(${table})`).all<{ name: string }>(); + return result.results.map((column) => column.name); +} + +async function restoreMigration(): Promise { + if (!(await tableColumns("users")).includes("suspended_at")) { + await env.DB.batch(migration().queries.map((query) => env.DB.prepare(query))); + } +} + +beforeEach(cleanD1Tables); +afterEach(async () => { + await restoreMigration(); + await cleanD1Tables(); +}); + +describe("migration 0071: RBAC foundation", () => { + it("backfills existing users before enabling Member defaults", async () => { + await env.DB.exec(` + DROP TRIGGER assign_default_role_after_user_insert; + DROP TABLE authorization_audit_events; + DROP TABLE user_role_assignments; + DROP TABLE role_permissions; + DROP TABLE roles; + ALTER TABLE users DROP COLUMN suspended_at; + `); + await env.DB.batch([ + env.DB.prepare( + `INSERT INTO users + (id, display_name, email, email_verified, avatar_url, created_at, updated_at) + VALUES + ('11111111111111111111111111111111', 'Existing One', 'one@example.com', 1, NULL, 100, 100), + ('22222222222222222222222222222222', 'Existing Two', 'two@example.com', 1, NULL, 200, 200)` + ), + env.DB.prepare( + `INSERT INTO sessions + (id, repo_owner, repo_name, status, created_at, updated_at, user_id) + VALUES + ('existing-session', 'acme', 'repo', 'completed', 300, 300, + '11111111111111111111111111111111'), + ('anonymous-session', 'acme', 'repo', 'completed', 400, 400, NULL)` + ), + env.DB.prepare( + `INSERT INTO user_identities + (id, user_id, provider, provider_user_id, provider_issuer, created_at, updated_at) + VALUES ('existing-identity', '11111111111111111111111111111111', + 'github', 'legacy-github-id', 'https://github.com', 100, 100)` + ), + env.DB.prepare( + `INSERT INTO automations + (id, name, instructions, model, created_by, user_id, created_at, updated_at) + VALUES ('existing-automation', 'Existing', 'Run', 'anthropic/claude-sonnet-4-6', + 'legacy-github-id', NULL, 100, 100)` + ), + ]); + + await env.DB.batch(migration().queries.map((query) => env.DB.prepare(query))); + + expect( + await env.DB.prepare( + `SELECT u.id, u.suspended_at, r.key AS role_key + FROM users u + JOIN user_role_assignments ura ON ura.user_id = u.id + JOIN roles r ON r.id = ura.role_id + ORDER BY u.id` + ).all() + ).toMatchObject({ + results: [ + { + id: "11111111111111111111111111111111", + suspended_at: null, + role_key: "administrator", + }, + { + id: "22222222222222222222222222222222", + suspended_at: null, + role_key: "administrator", + }, + ], + }); + expect( + await env.DB.prepare( + "SELECT user_id FROM automations WHERE id = 'existing-automation'" + ).first() + ).toEqual({ user_id: "11111111111111111111111111111111" }); + expect(await tableColumns("roles")).toEqual([ + "id", + "key", + "name", + "normalized_name", + "description", + "is_system", + ]); + expect(await tableColumns("user_role_assignments")).toEqual(["user_id", "role_id"]); + expect(await tableColumns("authorization_audit_events")).toEqual([ + "id", + "occurred_at", + "request_id", + "principal_kind", + "actor_user_id_snapshot", + "actor_service_snapshot", + "action", + "resource_type", + "resource_id", + "target_user_id_snapshot", + "reason_code", + ]); + + await env.DB.prepare( + `INSERT INTO users + (id, display_name, email, email_verified, avatar_url, created_at, updated_at) + VALUES ('33333333333333333333333333333333', 'New User', NULL, 0, NULL, 500, 500)` + ).run(); + expect( + await env.DB.prepare( + `SELECT r.key FROM user_role_assignments ura + JOIN roles r ON r.id = ura.role_id + WHERE ura.user_id = '33333333333333333333333333333333'` + ).first() + ).toEqual({ key: "member" }); + expect((await env.DB.prepare("PRAGMA foreign_key_check").all()).results).toEqual([]); + }); +}); diff --git a/packages/control-plane/test/integration/rbac-foundation.test.ts b/packages/control-plane/test/integration/rbac-foundation.test.ts new file mode 100644 index 0000000000..bb73a61d85 --- /dev/null +++ b/packages/control-plane/test/integration/rbac-foundation.test.ts @@ -0,0 +1,27 @@ +import { env } from "cloudflare:test"; +import { + BUILT_IN_ROLE_REGISTRY, + PERMISSION_IDS, + permissionsForBuiltInRole, +} from "@open-inspect/shared/rbac"; +import { describe, expect, it } from "vitest"; + +describe("RBAC foundation migration", () => { + it("seeds built-in roles without persisting their code-owned permissions", async () => { + const roles = await env.DB.prepare( + "SELECT id, key FROM roles WHERE is_system = 1 ORDER BY key" + ).all<{ id: string; key: string }>(); + + expect(roles.results).toEqual( + Object.values(BUILT_IN_ROLE_REGISTRY).sort((left, right) => left.key.localeCompare(right.key)) + ); + + expect( + await env.DB.prepare( + `SELECT COUNT(*) AS count FROM role_permissions rp + JOIN roles r ON r.id = rp.role_id WHERE r.is_system = 1` + ).first() + ).toEqual({ count: 0 }); + expect(permissionsForBuiltInRole("owner")).toHaveLength(PERMISSION_IDS.length); + }); +}); diff --git a/packages/control-plane/test/integration/session-read-state.test.ts b/packages/control-plane/test/integration/session-read-state.test.ts index 6470fba0b1..b8b79f46e6 100644 --- a/packages/control-plane/test/integration/session-read-state.test.ts +++ b/packages/control-plane/test/integration/session-read-state.test.ts @@ -284,6 +284,9 @@ describe("session read state", () => { action: "mark_latest_message_read", }); + await env.DB.prepare("DELETE FROM user_role_assignments WHERE user_id = ?") + .bind("deleted-user") + .run(); await env.DB.prepare("DELETE FROM users WHERE id = ?").bind("deleted-user").run(); expect(await env.DB.prepare("SELECT * FROM session_read_states").all()).toMatchObject({ results: [], diff --git a/packages/control-plane/test/integration/user-merge.test.ts b/packages/control-plane/test/integration/user-merge.test.ts index cb94043b29..43d6272c1e 100644 --- a/packages/control-plane/test/integration/user-merge.test.ts +++ b/packages/control-plane/test/integration/user-merge.test.ts @@ -61,6 +61,15 @@ async function insertScmToken(providerUserId: string, userId: string) { .run(); } +async function insertSkillProfile(id: string, userId: string, name: string) { + await env.DB.prepare( + `INSERT INTO skill_profiles (id, user_id, name, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)` + ) + .bind(id, userId, name, SEED_NOW_MS, SEED_NOW_MS) + .run(); +} + beforeEach(async () => { await cleanD1Tables(); }); @@ -79,6 +88,7 @@ describe("mergeUsers", () => { await insertSession("session-loser", LOSER); await insertAutomation("auto-1", LOSER, LOSER); await insertScmToken("583231", LOSER); + await insertSkillProfile("profile-loser", LOSER, "Personal profile"); await insertAuthSession({ id: "authsess-loser", userId: LOSER }); // Survivor: the email-owning row the user already signs into. await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com", emailVerified: 1 }); @@ -100,10 +110,11 @@ describe("mergeUsers", () => { expect(result.counts).toMatchObject({ identitiesRepointed: 1, sessionsRepointed: 1, - authSessionsRepointed: 1, + authSessionsDeleted: 1, automationsOwnedRepointed: 1, automationsCreatedRepointed: 1, scmTokensRepointed: 1, + skillProfilesRepointed: 1, readStatesDeduped: 1, readStatesRepointed: 1, usersDeleted: 1, @@ -119,12 +130,12 @@ describe("mergeUsers", () => { user_id: string; }>() ).toEqual({ user_id: SURVIVOR }); - // The loser's browser session survives, re-keyed to the survivor. + // Bearer sessions issued to the loser are invalidated, never re-keyed. expect( await env.DB.prepare(`SELECT userId FROM auth_sessions WHERE id = 'authsess-loser'`).first<{ userId: string; }>() - ).toEqual({ userId: SURVIVOR }); + ).toBeNull(); expect( await env.DB.prepare( `SELECT user_id, created_by FROM automations WHERE id = 'auto-1'` @@ -133,6 +144,9 @@ describe("mergeUsers", () => { created_by: string; }>() ).toEqual({ user_id: SURVIVOR, created_by: SURVIVOR }); + expect( + await env.DB.prepare(`SELECT user_id FROM skill_profiles WHERE id = 'profile-loser'`).first() + ).toEqual({ user_id: SURVIVOR }); // Read-state dedup kept the survivor's row on the shared session. expect( await env.DB.prepare( @@ -144,6 +158,19 @@ describe("mergeUsers", () => { ).toEqual({ last_read_message_id: "msg-survivor" }); expect(await getUserRow(LOSER)).toBeNull(); expect(await countTableRows("users")).toBe(1); + expect( + await env.DB.prepare( + `SELECT principal_kind, actor_user_id_snapshot, actor_service_snapshot, + resource_id, target_user_id_snapshot + FROM authorization_audit_events WHERE action = 'workspace.user_merged'` + ).first() + ).toEqual({ + principal_kind: "service", + actor_user_id_snapshot: null, + actor_service_snapshot: "control-plane", + resource_id: SURVIVOR, + target_user_id_snapshot: LOSER, + }); }); it("backfills the loser's email onto an email-less survivor, carrying verification as-was", async () => { @@ -201,7 +228,7 @@ describe("mergeUsers", () => { expect(await getUserRow(SURVIVOR)).toMatchObject({ email: null }); const executed = await mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER }); - expect(executed.counts.canonicalEmailBackfilled).toBe(preview.counts.canonicalEmailBackfilled); + expect(executed.counts).toEqual(preview.counts); }); it("leaves non-canonical created_by values (legacy GitHub numeric ids) untouched", async () => { @@ -219,6 +246,99 @@ describe("mergeUsers", () => { ).toEqual({ created_by: "583231", user_id: SURVIVOR }); }); + it("keeps preview and execution counts aligned for newer user-owned records", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + const authorizationId = "c".repeat(64); + const attemptId = "d".repeat(64); + await env.DB.batch([ + env.DB.prepare( + `INSERT INTO model_provider_account_authorizations ( + id, user_id, provider, operation, display_name, next_poll_at, + expires_at, state, created_at, updated_at + ) VALUES (?, ?, 'openai', 'create', 'Personal', ?, ?, 'initiating', ?, ?)` + ).bind(authorizationId, LOSER, SEED_NOW_MS, SEED_NOW_MS + 60_000, SEED_NOW_MS, SEED_NOW_MS), + env.DB.prepare( + `INSERT INTO model_provider_account_authorization_attempts + (id, user_id, attempted_at) VALUES (?, ?, ?)` + ).bind(attemptId, LOSER, SEED_NOW_MS), + env.DB.prepare( + `INSERT INTO keyboard_shortcut_preferences (user_id, shortcuts, updated_at) + VALUES (?, '{}', ?)` + ).bind(LOSER, SEED_NOW_MS), + ]); + + const preview = await mergeUsers(env.DB, { + survivorId: SURVIVOR, + loserId: LOSER, + dryRun: true, + }); + + expect(preview.counts).toMatchObject({ + providerAccountAuthorizationsRepointed: 1, + providerAccountAuthorizationAttemptsRepointed: 1, + keyboardShortcutPreferencesDeduped: 0, + keyboardShortcutPreferencesRepointed: 1, + }); + expect( + await env.DB.prepare(`SELECT user_id FROM model_provider_account_authorizations WHERE id = ?`) + .bind(authorizationId) + .first() + ).toEqual({ user_id: LOSER }); + + const result = await mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER }); + + expect(result.counts).toEqual(preview.counts); + expect( + await env.DB.prepare(`SELECT user_id FROM model_provider_account_authorizations WHERE id = ?`) + .bind(authorizationId) + .first() + ).toEqual({ user_id: SURVIVOR }); + expect( + await env.DB.prepare( + `SELECT user_id FROM model_provider_account_authorization_attempts WHERE id = ?` + ) + .bind(attemptId) + .first() + ).toEqual({ user_id: SURVIVOR }); + expect( + await env.DB.prepare(`SELECT shortcuts FROM keyboard_shortcut_preferences WHERE user_id = ?`) + .bind(SURVIVOR) + .first() + ).toEqual({ shortcuts: "{}" }); + }); + + it("keeps keyboard preference collision preview and execution counts aligned", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + await env.DB.batch([ + env.DB.prepare( + `INSERT INTO keyboard_shortcut_preferences (user_id, shortcuts, updated_at) + VALUES (?, '{"survivor":true}', ?)` + ).bind(SURVIVOR, SEED_NOW_MS), + env.DB.prepare( + `INSERT INTO keyboard_shortcut_preferences (user_id, shortcuts, updated_at) + VALUES (?, '{"loser":true}', ?)` + ).bind(LOSER, SEED_NOW_MS), + ]); + + const preview = await mergeUsers(env.DB, { + survivorId: SURVIVOR, + loserId: LOSER, + dryRun: true, + }); + const result = await mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER }); + + expect(preview.counts.keyboardShortcutPreferencesDeduped).toBe(1); + expect(preview.counts.keyboardShortcutPreferencesRepointed).toBe(0); + expect(result.counts).toEqual(preview.counts); + expect( + await env.DB.prepare(`SELECT shortcuts FROM keyboard_shortcut_preferences WHERE user_id = ?`) + .bind(SURVIVOR) + .first() + ).toEqual({ shortcuts: '{"survivor":true}' }); + }); + it("is idempotent: re-running after a completed merge is a zero-count no-op", async () => { await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); await insertCanonicalUser({ id: LOSER, email: null }); diff --git a/packages/control-plane/test/integration/user-store.test.ts b/packages/control-plane/test/integration/user-store.test.ts index f5596c5ce8..53351771d1 100644 --- a/packages/control-plane/test/integration/user-store.test.ts +++ b/packages/control-plane/test/integration/user-store.test.ts @@ -166,6 +166,28 @@ describe("UserStore", () => { expect(user!.updatedAt).toBeGreaterThanOrEqual(beforeUpdate!.updatedAt); }); + it("does not repair a missing role assignment during identity resolution", async () => { + const first = await store.resolveOrCreateUser({ + provider: "github", + providerUserId: "missing-assignment", + }); + await env.DB.prepare("DELETE FROM user_role_assignments WHERE user_id = ?") + .bind(first.id) + .run(); + + await store.resolveOrCreateUser({ + provider: "github", + providerUserId: "missing-assignment", + }); + + const assignment = await env.DB.prepare( + "SELECT role_id FROM user_role_assignments WHERE user_id = ?" + ) + .bind(first.id) + .first(); + expect(assignment).toBeNull(); + }); + it("links new identity to existing user by matching email", async () => { const github = await store.resolveOrCreateUser({ provider: "github", diff --git a/packages/shared/package.json b/packages/shared/package.json index 4a66e00a6a..743f771145 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -50,6 +50,10 @@ "import": "./dist/user-id.js", "types": "./dist/user-id.d.ts" }, + "./rbac": { + "import": "./dist/rbac.js", + "types": "./dist/rbac.d.ts" + }, "./browser-auth-routes": { "import": "./dist/browser-auth-routes.js", "types": "./dist/browser-auth-routes.d.ts" diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index b4d5fc30ce..dc98903814 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -20,3 +20,4 @@ export * from "./browser-auth-routes"; export * from "./sign-in-provider"; export * from "./slack"; export * from "./pull-request-tool"; +export * from "./rbac"; diff --git a/packages/shared/src/rbac.test.ts b/packages/shared/src/rbac.test.ts new file mode 100644 index 0000000000..7e3853a9cb --- /dev/null +++ b/packages/shared/src/rbac.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it } from "vitest"; +import { + BUILT_IN_ROLE_KEYS, + BUILT_IN_ROLE_REGISTRY, + PERMISSION_IDS, + SCOPED_PERMISSION_PAIRS, + effectiveAuthorizationSchema, + permissionsForBuiltInRole, + resolveScopedPermission, + replaceMemberRoleInputSchema, + replaceMemberStatusInputSchema, +} from "./rbac"; + +describe("RBAC registry", () => { + it("defines stable built-in role identities", () => { + expect(BUILT_IN_ROLE_REGISTRY).toEqual({ + owner: { + id: "role_builtin_owner", + key: "owner", + }, + administrator: { + id: "role_builtin_administrator", + key: "administrator", + }, + member: { + id: "role_builtin_member", + key: "member", + }, + viewer: { + id: "role_builtin_viewer", + key: "viewer", + }, + }); + expect(BUILT_IN_ROLE_KEYS).toEqual( + Object.values(BUILT_IN_ROLE_REGISTRY).map((role) => role.key) + ); + expect(new Set(Object.values(BUILT_IN_ROLE_REGISTRY).map((role) => role.id)).size).toBe( + BUILT_IN_ROLE_KEYS.length + ); + }); + + it("contains unique, sorted permission identifiers", () => { + expect(PERMISSION_IDS).toHaveLength(42); + expect(new Set(PERMISSION_IDS).size).toBe(PERMISSION_IDS.length); + expect(PERMISSION_IDS).toEqual([...PERMISSION_IDS].sort()); + }); + + it("owns every any/own permission pair and resolves any before own", () => { + const scopedPermissions = Object.values(SCOPED_PERMISSION_PAIRS).flatMap(({ any, own }) => [ + any, + own, + ]); + expect(new Set(scopedPermissions)).toEqual( + new Set(PERMISSION_IDS.filter((permission) => /\.(any|own)$/.test(permission))) + ); + expect( + resolveScopedPermission("automations.manage", [ + "automations.manage.own", + "automations.manage.any", + ]) + ).toBe("any"); + expect(resolveScopedPermission("automations.manage", ["automations.manage.own"])).toBe("own"); + expect(resolveScopedPermission("automations.manage", [])).toBeNull(); + }); + + it("assigns every permission explicitly to Owner", () => { + expect(permissionsForBuiltInRole("owner")).toEqual(PERMISSION_IDS); + }); + + it("reserves ownership transfer for Owner", () => { + for (const role of BUILT_IN_ROLE_KEYS) { + expect(permissionsForBuiltInRole(role).includes("workspace.transfer_ownership")).toBe( + role === "owner" + ); + } + }); + + it("grants Members workspace-wide session operations", () => { + const permissions = permissionsForBuiltInRole("member"); + expect(permissions).toEqual( + expect.arrayContaining([ + "sessions.read", + "sessions.collaborate", + "sessions.create", + "sessions.lifecycle", + "sessions.sandbox_access", + "sessions.delete", + ]) + ); + }); + + it("grants workspace analytics to Members and Viewers", () => { + expect(permissionsForBuiltInRole("member")).toContain("analytics.read"); + expect(permissionsForBuiltInRole("viewer")).toContain("analytics.read"); + }); + + it("makes Member a superset of Viewer", () => { + expect(permissionsForBuiltInRole("member")).toEqual( + expect.arrayContaining(permissionsForBuiltInRole("viewer")) + ); + }); + + it("reserves personal profile management for Member and above", () => { + expect(permissionsForBuiltInRole("member")).toContain("skill_profiles.manage_own"); + expect(permissionsForBuiltInRole("viewer")).not.toContain("skill_profiles.manage_own"); + }); + + it("requires an assigned role and uses suspension timestamps in public contracts", () => { + expect( + effectiveAuthorizationSchema.parse({ + userId: "11111111111111111111111111111111", + suspendedAt: null, + role: { id: "role_builtin_member", key: "member", name: "Member" }, + permissions: [], + }) + ).toMatchObject({ suspendedAt: null }); + expect(() => + effectiveAuthorizationSchema.parse({ + userId: "11111111111111111111111111111111", + suspendedAt: null, + role: null, + permissions: [], + }) + ).toThrow(); + expect(replaceMemberRoleInputSchema.parse({ roleId: "role_custom" })).toEqual({ + roleId: "role_custom", + }); + expect(replaceMemberStatusInputSchema.parse({ suspended: true })).toEqual({ suspended: true }); + expect(() => + replaceMemberStatusInputSchema.parse({ suspended: true, suspendedAt: 123 }) + ).toThrow(); + }); +}); diff --git a/packages/shared/src/rbac.ts b/packages/shared/src/rbac.ts new file mode 100644 index 0000000000..5ebf1af74e --- /dev/null +++ b/packages/shared/src/rbac.ts @@ -0,0 +1,219 @@ +import { z } from "zod"; +import { isCanonicalUserId } from "./user-id"; + +/** Stable identities for system-defined roles that cannot be replaced by custom roles. */ +export const BUILT_IN_ROLE_REGISTRY = { + owner: { + id: "role_builtin_owner", + key: "owner", + }, + administrator: { + id: "role_builtin_administrator", + key: "administrator", + }, + member: { + id: "role_builtin_member", + key: "member", + }, + viewer: { + id: "role_builtin_viewer", + key: "viewer", + }, +} as const; + +/** A key identifying one of the workspace's system-defined roles. */ +export type BuiltInRoleKey = keyof typeof BUILT_IN_ROLE_REGISTRY; +/** Built-in role keys in canonical registry order. */ +export const BUILT_IN_ROLE_KEYS = Object.keys(BUILT_IN_ROLE_REGISTRY) as BuiltInRoleKey[]; + +/** Canonical permission identifiers accepted by the RBAC policy and persistence layers. */ +export const PERMISSION_IDS = [ + "analytics.read", + "automations.create", + "automations.manage.any", + "automations.manage.own", + "automations.read", + "automations.trigger.any", + "automations.trigger.own", + "commit_signing.manage", + "environments.images.manage", + "environments.manage", + "environments.read", + "environments.secrets.manage", + "environments.settings.manage", + "environments.use", + "global_secrets.manage", + "image_builds.read", + "integrations.manage", + "integrations.read", + "mcp_servers.manage", + "mcp_servers.read", + "models.preferences.manage", + "provider_accounts.manage", + "provider_accounts.read", + "repositories.images.manage", + "repositories.read", + "repositories.secrets.manage", + "repositories.settings.manage", + "repositories.use", + "scm_settings.manage", + "sessions.collaborate", + "sessions.create", + "sessions.delete", + "sessions.lifecycle", + "sessions.read", + "sessions.sandbox_access", + "skill_profiles.manage_own", + "skills.manage", + "skills.read", + "workspace.members.manage", + "workspace.members.read", + "workspace.roles.read", + "workspace.transfer_ownership", +] as const; + +/** A permission identifier recognized by the RBAC policy. */ +export type PermissionId = (typeof PERMISSION_IDS)[number]; + +/** Maps ownership-sensitive capabilities to their workspace-wide and owner-only grants. */ +export const SCOPED_PERMISSION_PAIRS = { + "automations.manage": { + any: "automations.manage.any", + own: "automations.manage.own", + }, + "automations.trigger": { + any: "automations.trigger.any", + own: "automations.trigger.own", + }, +} as const satisfies Record; + +/** A capability whose effective grant depends on resource ownership. */ +export type ScopedPermissionStem = keyof typeof SCOPED_PERMISSION_PAIRS; +/** The resource ownership boundary granted for a scoped capability. */ +export type PermissionScope = "any" | "own"; + +/** Resolves the strongest granted scope for a capability, preferring workspace-wide access. */ +export function resolveScopedPermission( + stem: ScopedPermissionStem, + permissions: readonly PermissionId[] +): PermissionScope | null { + const pair = SCOPED_PERMISSION_PAIRS[stem]; + if (permissions.includes(pair.any)) return "any"; + if (permissions.includes(pair.own)) return "own"; + return null; +} + +const VIEWER_PERMISSIONS = new Set([ + "analytics.read", + "automations.read", + "environments.read", + "image_builds.read", + "mcp_servers.read", + "repositories.read", + "sessions.read", + "skills.read", +]); + +const MEMBER_PERMISSIONS = new Set([ + ...VIEWER_PERMISSIONS, + "automations.create", + "automations.manage.own", + "automations.trigger.own", + "environments.use", + "provider_accounts.read", + "repositories.use", + "sessions.collaborate", + "sessions.create", + "sessions.delete", + "sessions.lifecycle", + "sessions.sandbox_access", + "skill_profiles.manage_own", +]); + +/** Validates permission identifiers at API and storage boundaries. */ +export const permissionIdSchema = z.enum(PERMISSION_IDS); +/** Validates keys for system-defined roles. */ +export const builtInRoleKeySchema = z.enum(BUILT_IN_ROLE_KEYS); + +/** Returns the canonical effective grants for a system-defined role. */ +export function permissionsForBuiltInRole(role: BuiltInRoleKey): PermissionId[] { + if (role === "owner") return [...PERMISSION_IDS]; + if (role === "administrator") { + return PERMISSION_IDS.filter((permission) => permission !== "workspace.transfer_ownership"); + } + const permissions = role === "member" ? MEMBER_PERMISSIONS : VIEWER_PERMISSIONS; + return PERMISSION_IDS.filter((permission) => permissions.has(permission)); +} + +/** Narrows untrusted permission text to the canonical permission registry. */ +export function isRegisteredPermission(value: string): value is PermissionId { + return (PERMISSION_IDS as readonly string[]).includes(value); +} + +/** Reports whether a permission may be delegated through a custom role. */ +export function isCustomRolePermission(permission: PermissionId): boolean { + return permission !== "workspace.transfer_ownership"; +} + +/** Validates the role identity embedded in authorization responses. */ +export const roleReferenceSchema = z + .object({ + id: z.string().min(1), + key: builtInRoleKeySchema.nullable(), + name: z.string().min(1), + }) + .strict(); + +/** Validates an administrative role view with effective grants and assignment count. */ +export const roleSummarySchema = roleReferenceSchema.extend({ + description: z.string().nullable(), + permissions: z.array(permissionIdSchema), + assignmentCount: z.number().int().nonnegative(), +}); + +/** Validates a user's role, suspension state, and currently effective permissions. */ +export const effectiveAuthorizationSchema = z + .object({ + userId: z.string().refine(isCanonicalUserId, "Invalid canonical user ID"), + suspendedAt: z.number().int().nonnegative().nullable(), + role: roleReferenceSchema, + permissions: z.array(permissionIdSchema), + }) + .strict(); + +/** Validates the member record exposed by workspace administration APIs. */ +export const workspaceMemberSchema = z + .object({ + userId: z.string().refine(isCanonicalUserId, "Invalid canonical user ID"), + displayName: z.string().nullable(), + email: z.string().nullable(), + suspendedAt: z.number().int().nonnegative().nullable(), + role: roleReferenceSchema, + }) + .strict(); + +/** Validates the complete role-list response. */ +export const roleListResponseSchema = z.array(roleSummarySchema); +/** Validates the complete workspace-member-list response. */ +export const workspaceMemberListResponseSchema = z.array(workspaceMemberSchema); + +/** Validates a request to atomically replace a member's assigned role. */ +export const replaceMemberRoleInputSchema = z + .object({ + roleId: z.string().min(1), + }) + .strict(); + +/** Validates a request to suspend or reactivate a workspace member. */ +export const replaceMemberStatusInputSchema = z + .object({ + suspended: z.boolean(), + }) + .strict(); + +/** Administrative role data with effective grants and current assignment count. */ +export type RoleSummary = z.infer; +/** The authorization state used to make permission decisions for a user. */ +export type EffectiveAuthorization = z.infer; +/** A workspace member and their current RBAC assignment state. */ +export type WorkspaceMember = z.infer; diff --git a/scripts/bootstrap-workspace-owner.test.ts b/scripts/bootstrap-workspace-owner.test.ts new file mode 100644 index 0000000000..58eefd90bc --- /dev/null +++ b/scripts/bootstrap-workspace-owner.test.ts @@ -0,0 +1,310 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { buildBootstrapSql, parseArgs } from "./bootstrap-workspace-owner.ts"; + +const USER_ID = "11111111111111111111111111111111"; +const OTHER_USER_ID = "22222222222222222222222222222222"; + +function createDatabase(): DatabaseSync { + const database = new DatabaseSync(":memory:"); + database.exec(` + PRAGMA foreign_keys = ON; + CREATE TABLE users ( + id TEXT PRIMARY KEY, + suspended_at INTEGER + ); + CREATE TABLE roles ( + id TEXT PRIMARY KEY, + key TEXT UNIQUE, + is_system INTEGER NOT NULL + ); + CREATE TABLE user_role_assignments ( + user_id TEXT PRIMARY KEY REFERENCES users(id), + role_id TEXT NOT NULL REFERENCES roles(id) + ); + CREATE TABLE authorization_audit_events ( + id TEXT PRIMARY KEY, + occurred_at INTEGER NOT NULL, + request_id TEXT NOT NULL, + principal_kind TEXT NOT NULL, + actor_user_id_snapshot TEXT, + actor_service_snapshot TEXT, + action TEXT NOT NULL, + resource_type TEXT NOT NULL, + resource_id TEXT, + target_user_id_snapshot TEXT, + reason_code TEXT NOT NULL + ); + INSERT INTO roles (id, key, is_system) VALUES + ('role_builtin_owner', 'owner', 1), + ('role_builtin_member', 'member', 1); + INSERT INTO users (id, suspended_at) VALUES ('${USER_ID}', NULL); + INSERT INTO user_role_assignments (user_id, role_id) + VALUES ('${USER_ID}', 'role_builtin_member'); + `); + return database; +} + +function sql(execute: boolean, auditId = "audit-id", now = 100): string { + return buildBootstrapSql({ userId: USER_ID, execute, auditId, now }); +} + +function preflight(database: DatabaseSync): Record { + return { ...database.prepare(sql(false, "unused", 0)).get() }; +} + +function execute(database: DatabaseSync, auditId: string, now: number): void { + database.exec(sql(true, auditId, now)); +} + +function insertPriorAudit( + database: DatabaseSync, + targetUserId = OTHER_USER_ID, + id = "audit-history" +): void { + database + .prepare( + `INSERT INTO authorization_audit_events + (id, occurred_at, request_id, principal_kind, + actor_service_snapshot, action, resource_type, target_user_id_snapshot, + reason_code) + VALUES (?, 1, 'operator-cli:history', 'service', + 'operator-cli', 'workspace.owner_bootstrapped', 'workspace', ?, + 'operator_cli')` + ) + .run(id, targetUserId); +} + +describe("Owner bootstrap CLI arguments", () => { + it("defaults to a remote dry run and accepts explicit execution", () => { + assert.deepEqual(parseArgs(["--database", "open-inspect-prod", "--user", USER_ID]), { + database: "open-inspect-prod", + userId: USER_ID, + execute: false, + }); + assert.deepEqual( + parseArgs(["--database", "open-inspect-dev", "--user", USER_ID, "--execute"]), + { + database: "open-inspect-dev", + userId: USER_ID, + execute: true, + } + ); + }); + + it("rejects unknown, duplicate, missing, and non-canonical arguments", () => { + assert.throws(() => parseArgs(["--database", "db", "--user", USER_ID, "--force"]), /Unknown/); + assert.throws( + () => parseArgs(["--database", "db", "--database", "other", "--user", USER_ID]), + /Duplicate/ + ); + assert.throws(() => parseArgs(["--database", "--user", USER_ID]), /Missing value/); + assert.throws( + () => parseArgs(["--database", "db", "--user", "owner@example.com"]), + /canonical/ + ); + assert.throws( + () => parseArgs(["--database", "db", "--user", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaA"]), + /canonical/ + ); + }); +}); + +describe("Owner bootstrap SQL", () => { + it("reports ready for an unsuspended target with one assignment and no Owner", () => { + const database = createDatabase(); + + assert.deepEqual(preflight(database), { + report: "preflight", + status: "ready", + detail: "selected user can be bootstrapped", + user_id: USER_ID, + suspended_at: null, + role_id: "role_builtin_member", + }); + assert.equal( + database.prepare("SELECT role_id FROM user_role_assignments").get()!.role_id, + "role_builtin_member" + ); + assert.equal( + database.prepare("SELECT COUNT(*) AS count FROM authorization_audit_events").get()!.count, + 0 + ); + }); + + it("assigns Owner and writes exactly one redacted successful service audit", () => { + const database = createDatabase(); + execute(database, "audit-'success", 100); + + assert.deepEqual( + { + ...database + .prepare( + `SELECT role_id + FROM user_role_assignments WHERE user_id = ?` + ) + .get(USER_ID), + }, + { role_id: "role_builtin_owner" } + ); + assert.deepEqual( + { + ...database + .prepare( + `SELECT id, occurred_at, request_id, principal_kind, actor_user_id_snapshot, + actor_service_snapshot, action, resource_type, resource_id, + target_user_id_snapshot, reason_code + FROM authorization_audit_events` + ) + .get(), + }, + { + id: "audit-'success", + occurred_at: 100, + request_id: "operator-cli:audit-'success", + principal_kind: "service", + actor_user_id_snapshot: null, + actor_service_snapshot: "operator-cli", + action: "workspace.owner_bootstrapped", + resource_type: "workspace", + resource_id: null, + target_user_id_snapshot: USER_ID, + reason_code: "operator_cli", + } + ); + }); + + it("is an idempotent no-op for the current unsuspended Owner", () => { + const database = createDatabase(); + execute(database, "audit-first", 100); + execute(database, "audit-second", 200); + + assert.deepEqual(preflight(database), { + report: "preflight", + status: "no-op", + detail: "selected user is already the current unsuspended Owner", + user_id: USER_ID, + suspended_at: null, + role_id: "role_builtin_owner", + }); + assert.equal( + database.prepare("SELECT COUNT(*) AS count FROM authorization_audit_events").get()!.count, + 1 + ); + }); + + it("ignores prior bootstrap audit history when current Owner state is missing", () => { + const database = createDatabase(); + insertPriorAudit(database); + + assert.equal(preflight(database).status, "ready"); + execute(database, "audit-current", 100); + assert.equal( + database.prepare("SELECT role_id FROM user_role_assignments").get()!.role_id, + "role_builtin_owner" + ); + assert.equal( + database.prepare("SELECT COUNT(*) AS count FROM authorization_audit_events").get()!.count, + 2 + ); + }); + + it("cannot replay generated SQL after ownership conditions change", () => { + const database = createDatabase(); + const generated = sql(true, "audit-replay", 100); + database.exec(generated); + database.exec(` + UPDATE user_role_assignments + SET role_id = 'role_builtin_member' + WHERE user_id = '${USER_ID}'; + INSERT INTO users (id, suspended_at) VALUES ('${OTHER_USER_ID}', NULL); + INSERT INTO user_role_assignments (user_id, role_id) + VALUES ('${OTHER_USER_ID}', 'role_builtin_owner'); + `); + + database.exec(generated); + + assert.equal( + database.prepare("SELECT role_id FROM user_role_assignments WHERE user_id = ?").get(USER_ID)! + .role_id, + "role_builtin_member" + ); + }); + + it("refuses another unsuspended Owner without changing the selected user", () => { + const database = createDatabase(); + database.exec(` + INSERT INTO users (id, suspended_at) VALUES ('${OTHER_USER_ID}', NULL); + INSERT INTO user_role_assignments (user_id, role_id) + VALUES ('${OTHER_USER_ID}', 'role_builtin_owner'); + `); + + assert.deepEqual(preflight(database), { + report: "preflight", + status: "refused", + detail: "another unsuspended Owner already exists", + user_id: USER_ID, + suspended_at: null, + role_id: "role_builtin_member", + }); + execute(database, "audit-refused", 100); + assert.equal( + database.prepare("SELECT role_id FROM user_role_assignments WHERE user_id = ?").get(USER_ID)! + .role_id, + "role_builtin_member" + ); + }); + + it("requires the RBAC schema and an unsuspended target with exactly one assignment", () => { + const missingSchema = new DatabaseSync(":memory:"); + assert.throws(() => execute(missingSchema, "audit-missing-schema", 100), /no such table/); + + const incompleteSchema = createDatabase(); + incompleteSchema.exec("ALTER TABLE authorization_audit_events DROP COLUMN reason_code"); + assert.deepEqual(preflight(incompleteSchema), { + report: "preflight", + status: "refused", + detail: "required RBAC schema is missing or incomplete", + user_id: USER_ID, + suspended_at: null, + role_id: "role_builtin_member", + }); + + const suspended = createDatabase(); + suspended.exec(`UPDATE users SET suspended_at = 1 WHERE id = '${USER_ID}'`); + assert.equal(preflight(suspended).detail, "target user is suspended"); + execute(suspended, "audit-suspended", 100); + + const missingAssignment = createDatabase(); + missingAssignment.exec(`DELETE FROM user_role_assignments WHERE user_id = '${USER_ID}'`); + assert.equal( + preflight(missingAssignment).detail, + "target must have exactly one role assignment" + ); + execute(missingAssignment, "audit-unassigned", 100); + }); + + it("treats a current target Owner as a no-op without requiring audit history", () => { + const database = createDatabase(); + database.exec( + `UPDATE user_role_assignments SET role_id = 'role_builtin_owner' WHERE user_id = '${USER_ID}'` + ); + assert.equal(preflight(database).status, "no-op"); + execute(database, "audit-no-op", 100); + assert.equal( + database.prepare("SELECT COUNT(*) AS count FROM authorization_audit_events").get()!.count, + 0 + ); + }); + + it("uses only current RBAC schema and the generated audit ID as execution provenance", () => { + const generated = sql(true, "audit-exact", 100); + + assert.doesNotMatch( + generated, + /workspace_bootstrap|authorization_version|access_status|mutation_id|policy_id|operation_result|decision_outcome|metadata_json|actor_provider|assigned_by|assigned_at/ + ); + assert.match(generated, /SELECT 1 FROM authorization_audit_events WHERE id = 'audit-exact'/); + }); +}); diff --git a/scripts/bootstrap-workspace-owner.ts b/scripts/bootstrap-workspace-owner.ts new file mode 100644 index 0000000000..e0a1ac66b1 --- /dev/null +++ b/scripts/bootstrap-workspace-owner.ts @@ -0,0 +1,284 @@ +/** + * Bootstrap the first workspace Owner by canonical user ID. + * + * Dry-run (remote D1 by default): + * npm run rbac:bootstrap-owner -- --database --user + * + * Execute after reviewing the preflight result: + * npm run rbac:bootstrap-owner -- --database --user --execute + * + * Wrangler uses the normal CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID + * environment variables or the credentials established by `wrangler login`. + */ + +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const CANONICAL_USER_ID = /^[0-9a-f]{32}$/; +const OWNER_ROLE_ID = "role_builtin_owner"; +const VALUE_OPTIONS = new Set(["database", "user"]); +const FLAG_OPTIONS = new Set(["execute"]); + +/** Validated command-line options for the Owner bootstrap operation. */ +export interface BootstrapCliOptions { + database: string; + userId: string; + execute: boolean; +} + +/** Inputs used to build an Owner bootstrap preflight or execution script. */ +export interface BootstrapSqlOptions { + userId: string; + execute: boolean; + auditId: string; + now: number; +} + +/** Parse and validate Owner bootstrap command-line arguments. */ +export function parseArgs(argv: string[]): BootstrapCliOptions { + const values = new Map(); + const flags = new Set(); + + for (let index = 0; index < argv.length; index++) { + const argument = argv[index]; + if (!argument.startsWith("--")) throw new Error(`Unexpected argument: ${argument}`); + const name = argument.slice(2); + if (FLAG_OPTIONS.has(name)) { + if (flags.has(name)) throw new Error(`Duplicate option: --${name}`); + flags.add(name); + continue; + } + if (!VALUE_OPTIONS.has(name)) throw new Error(`Unknown option: --${name}`); + if (values.has(name)) throw new Error(`Duplicate option: --${name}`); + const value = argv[++index]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`Missing value for --${name}`); + } + values.set(name, value); + } + + const database = values.get("database"); + if (!database?.trim()) throw new Error("--database is required"); + const userId = values.get("user"); + if (!userId) throw new Error("--user is required"); + if (!CANONICAL_USER_ID.test(userId)) { + throw new Error("--user must be a canonical 32-character lowercase hexadecimal user ID"); + } + + return { + database: database.trim(), + userId, + execute: flags.has("execute"), + }; +} + +function sqlLiteral(value: string | number): string { + if (typeof value === "number") { + if (!Number.isSafeInteger(value)) throw new Error(`Unsafe SQL integer: ${value}`); + return String(value); + } + return `'${value.replaceAll("'", "''")}'`; +} + +/** Build guarded SQL for an Owner bootstrap preflight or execution. */ +export function buildBootstrapSql(options: BootstrapSqlOptions): string { + const userId = sqlLiteral(options.userId); + const auditId = sqlLiteral(options.auditId); + const requestId = sqlLiteral(`operator-cli:${options.auditId}`); + const now = sqlLiteral(options.now); + const ownerRoleId = sqlLiteral(OWNER_ROLE_ID); + const targetIsOwner = `EXISTS ( + SELECT 1 FROM user_role_assignments assignment + WHERE assignment.user_id = ${userId} AND assignment.role_id = ${ownerRoleId} + )`; + const anotherUnsuspendedOwner = `EXISTS ( + SELECT 1 FROM users owner + JOIN user_role_assignments assignment ON assignment.user_id = owner.id + WHERE assignment.role_id = ${ownerRoleId} + AND owner.suspended_at IS NULL AND owner.id <> ${userId} + )`; + const schemaReady = `(SELECT COUNT(*) FROM pragma_table_info('users') + WHERE name IN ('id', 'suspended_at')) = 2 + AND (SELECT COUNT(*) FROM pragma_table_info('roles') + WHERE name IN ('id', 'key', 'is_system')) = 3 + AND (SELECT COUNT(*) FROM pragma_table_info('user_role_assignments') + WHERE name IN ('user_id', 'role_id')) = 2 + AND (SELECT COUNT(*) FROM pragma_table_info('authorization_audit_events') + WHERE name IN ( + 'id', 'occurred_at', 'request_id', 'principal_kind', + 'actor_user_id_snapshot', 'actor_service_snapshot', 'action', 'resource_type', + 'resource_id', 'target_user_id_snapshot', 'reason_code' + )) = 11`; + const commonPreconditions = `${schemaReady} + AND (SELECT COUNT(*) FROM users WHERE id = ${userId}) = 1 + AND (SELECT COUNT(*) FROM user_role_assignments WHERE user_id = ${userId}) = 1 + AND EXISTS ( + SELECT 1 FROM users WHERE id = ${userId} AND suspended_at IS NULL + ) + AND EXISTS ( + SELECT 1 FROM roles + WHERE id = ${ownerRoleId} AND key = 'owner' AND is_system = 1 + )`; + const ready = `${commonPreconditions} + AND NOT (${targetIsOwner}) + AND NOT (${anotherUnsuspendedOwner})`; + const exactAudit = `EXISTS ( + SELECT 1 FROM authorization_audit_events + WHERE id = ${auditId} + AND occurred_at = ${now} + AND request_id = ${requestId} + AND principal_kind = 'service' + AND actor_user_id_snapshot IS NULL + AND actor_service_snapshot = 'operator-cli' + AND action = 'workspace.owner_bootstrapped' + AND resource_type = 'workspace' + AND resource_id IS NULL + AND target_user_id_snapshot = ${userId} + AND reason_code = 'operator_cli' + )`; + + const preflight = `SELECT 'preflight' AS report, + CASE + WHEN NOT (${schemaReady}) THEN 'refused' + WHEN (SELECT COUNT(*) FROM users WHERE id = ${userId}) <> 1 THEN 'refused' + WHEN (SELECT COUNT(*) FROM user_role_assignments WHERE user_id = ${userId}) <> 1 THEN 'refused' + WHEN NOT EXISTS (SELECT 1 FROM users WHERE id = ${userId} AND suspended_at IS NULL) THEN 'refused' + WHEN NOT EXISTS ( + SELECT 1 FROM roles WHERE id = ${ownerRoleId} AND key = 'owner' AND is_system = 1 + ) THEN 'refused' + WHEN ${anotherUnsuspendedOwner} THEN 'refused' + WHEN ${targetIsOwner} THEN 'no-op' + ELSE 'ready' + END AS status, + CASE + WHEN NOT (${schemaReady}) THEN 'required RBAC schema is missing or incomplete' + WHEN (SELECT COUNT(*) FROM users WHERE id = ${userId}) <> 1 THEN 'target user does not exist exactly once' + WHEN (SELECT COUNT(*) FROM user_role_assignments WHERE user_id = ${userId}) <> 1 THEN 'target must have exactly one role assignment' + WHEN NOT EXISTS (SELECT 1 FROM users WHERE id = ${userId} AND suspended_at IS NULL) THEN 'target user is suspended' + WHEN NOT EXISTS ( + SELECT 1 FROM roles WHERE id = ${ownerRoleId} AND key = 'owner' AND is_system = 1 + ) THEN 'built-in Owner role is missing or inconsistent' + WHEN ${anotherUnsuspendedOwner} THEN 'another unsuspended Owner already exists' + WHEN ${targetIsOwner} THEN 'selected user is already the current unsuspended Owner' + ELSE 'selected user can be bootstrapped' + END AS detail, + ${userId} AS user_id, + (SELECT suspended_at FROM users WHERE id = ${userId}) AS suspended_at, + (SELECT role_id FROM user_role_assignments WHERE user_id = ${userId}) AS role_id;`; + + if (!options.execute) return `${preflight}\n`; + + return `${preflight} + +INSERT INTO authorization_audit_events + (id, occurred_at, request_id, principal_kind, + actor_service_snapshot, action, resource_type, + target_user_id_snapshot, reason_code) +SELECT ${auditId}, ${now}, ${requestId}, 'service', + 'operator-cli', 'workspace.owner_bootstrapped', 'workspace', + ${userId}, 'operator_cli' +WHERE ${ready}; + +UPDATE user_role_assignments +SET role_id = ${ownerRoleId} +WHERE user_id = ${userId} AND (${ready}) AND ${exactAudit}; + +SELECT 'postcondition' AS report, + CASE + WHEN (${targetIsOwner}) AND (${exactAudit}) THEN 'executed' + WHEN ${targetIsOwner} THEN 'no-op' + ELSE 'refused' + END AS status, + u.id AS user_id, + u.suspended_at, + assignment.role_id, + EXISTS(SELECT 1 FROM authorization_audit_events WHERE id = ${auditId}) AS audit_written +FROM users u +JOIN user_role_assignments assignment ON assignment.user_id = u.id +WHERE u.id = ${userId}; +`; +} + +interface WranglerResult { + results?: Array>; + success?: boolean; +} + +function reportRows(stdout: string): Array> { + const parsed = JSON.parse(stdout) as WranglerResult[]; + const rows = parsed.flatMap((result) => result.results ?? []).filter((row) => row.report); + for (const row of rows) console.log(JSON.stringify(row)); + return rows; +} + +function runWrangler(database: string, operation: readonly string[]): string { + const child = spawnSync( + "npx", + ["wrangler", "d1", "execute", database, "--remote", ...operation, "--json"], + { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 } + ); + if (child.status !== 0) { + throw new Error(`Owner bootstrap refused or failed:\n${child.stderr || child.stdout}`); + } + return child.stdout; +} + +function preflight(database: string, userId: string): string { + const sql = buildBootstrapSql({ userId, execute: false, auditId: "unused", now: 0 }); + const rows = reportRows(runWrangler(database, ["--command", sql])); + const status = rows.find((row) => row.report === "preflight")?.status; + if (typeof status !== "string") throw new Error("Wrangler returned no Owner bootstrap preflight"); + return status; +} + +/** Run the remote Owner bootstrap workflow and verify its postcondition. */ +export async function run(options: BootstrapCliOptions): Promise { + console.error(`${options.execute ? "Executing" : "Dry-running"} Owner bootstrap on remote D1...`); + const status = preflight(options.database, options.userId); + if (status === "refused") throw new Error("Owner bootstrap preflight was refused"); + if (status === "no-op") return; + if (!options.execute) { + console.error("Dry run only. Re-run with --execute after reviewing the preflight result."); + return; + } + + const directory = await mkdtemp(join(tmpdir(), "open-inspect-owner-bootstrap-")); + const sqlPath = join(directory, "bootstrap.sql"); + try { + await writeFile( + sqlPath, + buildBootstrapSql({ + userId: options.userId, + execute: true, + auditId: crypto.randomUUID(), + now: Date.now(), + }), + { encoding: "utf8", mode: 0o600 } + ); + runWrangler(options.database, ["--file", sqlPath]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + + if (preflight(options.database, options.userId) !== "no-op") { + throw new Error("Owner bootstrap postcondition verification failed"); + } + console.error( + "Owner bootstrap command completed; verify /health reports ownerAssignment=present." + ); +} + +async function main(): Promise { + await run(parseArgs(process.argv.slice(2))); +} + +const invokedPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : null; +if (invokedPath === import.meta.url) { + main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/terraform/d1/migrations/0071_rbac_foundation.sql b/terraform/d1/migrations/0071_rbac_foundation.sql new file mode 100644 index 0000000000..4297c3da2e --- /dev/null +++ b/terraform/d1/migrations/0071_rbac_foundation.sql @@ -0,0 +1,71 @@ +ALTER TABLE users ADD COLUMN suspended_at INTEGER; + +CREATE TABLE roles ( + id TEXT PRIMARY KEY, + key TEXT UNIQUE, + name TEXT NOT NULL, + normalized_name TEXT NOT NULL UNIQUE, + description TEXT, + is_system INTEGER NOT NULL DEFAULT 0 CHECK (is_system IN (0, 1)), + CHECK ( + (is_system = 1 AND key IN ('owner', 'administrator', 'member', 'viewer')) + OR (is_system = 0 AND key IS NULL) + ) +); + +-- Custom-role grants only; protected built-in grants are code-owned. +CREATE TABLE role_permissions ( + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE, + permission_id TEXT NOT NULL, + PRIMARY KEY (role_id, permission_id) +); + +CREATE TABLE user_role_assignments ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE RESTRICT, + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE RESTRICT +); + +CREATE TABLE authorization_audit_events ( + id TEXT PRIMARY KEY, + occurred_at INTEGER NOT NULL, + request_id TEXT NOT NULL, + principal_kind TEXT NOT NULL, + actor_user_id_snapshot TEXT, + actor_service_snapshot TEXT, + action TEXT NOT NULL, + resource_type TEXT NOT NULL, + resource_id TEXT, + target_user_id_snapshot TEXT, + reason_code TEXT NOT NULL +); + +CREATE INDEX idx_role_assignments_role ON user_role_assignments(role_id, user_id); + +INSERT INTO roles ( + id, key, name, normalized_name, description, is_system +) VALUES + ('role_builtin_owner', 'owner', 'Owner', 'owner', 'Full workspace control', 1), + ('role_builtin_administrator', 'administrator', 'Administrator', 'administrator', 'Operational administration without ownership transfer', 1), + ('role_builtin_member', 'member', 'Member', 'member', 'Session and automation collaboration', 1), + ('role_builtin_viewer', 'viewer', 'Viewer', 'viewer', 'Read-only workspace visibility', 1); + +INSERT INTO user_role_assignments (user_id, role_id) +SELECT id, 'role_builtin_administrator' FROM users; + +CREATE TRIGGER assign_default_role_after_user_insert +AFTER INSERT ON users +BEGIN + INSERT INTO user_role_assignments (user_id, role_id) + VALUES (NEW.id, 'role_builtin_member') + ON CONFLICT(user_id) DO NOTHING; +END; + +UPDATE automations +SET user_id = ( + SELECT identity.user_id + FROM user_identities identity + WHERE identity.provider = 'github' + AND identity.provider_user_id = automations.created_by +) +WHERE user_id IS NULL + AND created_by <> 'anonymous'; diff --git a/terraform/environments/production/outputs.tf b/terraform/environments/production/outputs.tf index ab60312de4..68cd16cd84 100644 --- a/terraform/environments/production/outputs.tf +++ b/terraform/environments/production/outputs.tf @@ -18,6 +18,11 @@ output "d1_database_id" { value = cloudflare_d1_database.main.id } +output "d1_database_name" { + description = "The name of the D1 database used by operator CLI commands" + value = cloudflare_d1_database.main.name +} + # Cloudflare Workers output "control_plane_url" { description = "Control plane worker URL" From 46b620d5c522a0de5cae3f95fb3a55aa84abbe70 Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 21:47:36 -0700 Subject: [PATCH 2/6] feat: enforce workspace permissions at the HTTP boundary --- .../src/auth/identity-enforcement.test.ts | 58 ++-- .../src/auth/identity-enforcement.ts | 20 +- .../authorization/service-permissions.test.ts | 10 + .../src/authorization/service-permissions.ts | 45 +++ .../src/router.analytics.test.ts | 21 +- .../src/router.create-session.test.ts | 155 +++++++++- .../control-plane/src/router.policy.test.ts | 175 +++++++++++ .../src/router.scm-credentials.test.ts | 17 +- .../src/router.session-prompt.test.ts | 13 +- .../src/router.spawn-child.test.ts | 70 ++++- packages/control-plane/src/router.ts | 279 +++++++++++++++++- .../control-plane/src/routes/analytics.ts | 5 + packages/control-plane/src/routes/autofix.ts | 2 + .../src/routes/automations.test.ts | 11 +- .../control-plane/src/routes/automations.ts | 17 ++ .../control-plane/src/routes/browser-auth.ts | 5 +- .../src/routes/commit-signing.ts | 7 + .../src/routes/environment-secrets.ts | 5 + .../control-plane/src/routes/environments.ts | 34 ++- .../control-plane/src/routes/image-builds.ts | 10 + .../src/routes/integration-settings.ts | 19 ++ .../src/routes/keyboard-shortcuts.ts | 39 +-- .../control-plane/src/routes/mcp-servers.ts | 6 + .../src/routes/model-preferences.ts | 6 + .../src/routes/model-provider-accounts.ts | 6 + packages/control-plane/src/routes/rbac.ts | 114 +++++++ packages/control-plane/src/routes/repos.ts | 9 + .../control-plane/src/routes/scm-settings.ts | 31 +- packages/control-plane/src/routes/secrets.ts | 7 + .../src/routes/session-attachments.ts | 3 + .../src/routes/session-child-spawn.ts | 6 + .../src/routes/session-children.ts | 6 + .../src/routes/session-create.ts | 22 ++ .../control-plane/src/routes/session-diffs.ts | 6 + .../src/routes/session-index.test.ts | 38 ++- .../control-plane/src/routes/session-index.ts | 28 +- .../src/routes/session-media-stream.ts | 4 + .../src/routes/session-media-upload.ts | 2 + .../src/routes/session-prompt.ts | 2 + .../src/routes/session-pull-requests.ts | 2 + .../src/routes/session-runtime-proxy.ts | 29 +- .../src/routes/session-skills.ts | 7 +- .../src/routes/session-ws-token.test.ts | 43 ++- .../src/routes/session-ws-token.ts | 6 +- packages/control-plane/src/routes/shared.ts | 150 +++++++++- .../src/routes/sign-in-providers.ts | 2 + packages/control-plane/src/routes/skills.ts | 53 +++- .../src/webhooks/automation-event.ts | 3 + .../src/webhooks/automation-webhook.ts | 2 + packages/control-plane/src/webhooks/github.ts | 9 +- packages/control-plane/src/webhooks/sentry.ts | 2 + .../automations-slack-route.test.ts | 4 - .../control-plane/test/integration/helpers.ts | 30 +- .../test/integration/image-builds.test.ts | 18 +- .../test/integration/service-auth.test.ts | 216 +++++++++++++- .../linear-bot/src/webhook-handler.test.ts | 54 ++++ packages/linear-bot/src/webhook-handler.ts | 18 +- packages/slack-bot/src/attachments.test.ts | 4 +- packages/slack-bot/src/attachments.ts | 5 +- .../slack-bot/src/sessions/prompt-delivery.ts | 2 +- 60 files changed, 1766 insertions(+), 206 deletions(-) create mode 100644 packages/control-plane/src/authorization/service-permissions.test.ts create mode 100644 packages/control-plane/src/authorization/service-permissions.ts create mode 100644 packages/control-plane/src/routes/rbac.ts diff --git a/packages/control-plane/src/auth/identity-enforcement.test.ts b/packages/control-plane/src/auth/identity-enforcement.test.ts index 74a7247382..e33bec55b7 100644 --- a/packages/control-plane/src/auth/identity-enforcement.test.ts +++ b/packages/control-plane/src/auth/identity-enforcement.test.ts @@ -31,12 +31,17 @@ const SLACK_BOT_PRINCIPAL: Principal = { }; function createCtx(principal?: Principal): RequestContext { + const statement = { + bind: vi.fn(() => statement), + first: vi.fn(async () => ({ active: 1 })), + }; return { trace_id: "trace-test", request_id: "req-test", principal, + db: { prepare: vi.fn(() => statement) }, executionCtx: TEST_BACKGROUND_TASK_CONTEXT, - } as RequestContext; + } as unknown as RequestContext; } function loggedEvents(spy: { mock: { calls: unknown[][] } }): Array> { @@ -93,26 +98,7 @@ describe("applyIdentityEnforcement — identityless principals", () => { }); describe("applyIdentityEnforcement — forbidden-field rejection", () => { - it("rejects forbidden keys with a 400 naming the field", async () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); - const { rejection } = applyIdentityEnforcement(createCtx(USER_PRINCIPAL), "session-lifecycle", { - userId: "someone", - title: "ok", - }); - expect(rejection).toBeDefined(); - expect(rejection!.status).toBe(400); - expect(((await rejection!.clone().json()) as { error: string }).error).toBe( - "Field 'userId' is not accepted from verified callers" - ); - const logged = loggedEvents(warn).find((e) => e.event === "identity.forbidden_field_rejected"); - expect(logged).toMatchObject({ route: "session-lifecycle", field: "userId" }); - }); - it("accepts bodies carrying only permitted fields", () => { - expect( - applyIdentityEnforcement(createCtx(USER_PRINCIPAL), "session-lifecycle", { title: "ok" }) - .rejection - ).toBeUndefined(); expect( applyIdentityEnforcement(createCtx(USER_PRINCIPAL), "session-create", { scmLogin: "ada", @@ -194,11 +180,9 @@ describe("applyIdentityEnforcement — requires-user rejection", () => { }); it("does not gate routes that accept participantless principals", () => { - for (const route of ["prompt", "session-lifecycle"] as const) { - const result = applyIdentityEnforcement(createCtx(ACTORLESS_BOT), route, {}); - expect(result.rejection).toBeUndefined(); - expect(result.enforced).toMatchObject({ participantUserId: null }); - } + const result = applyIdentityEnforcement(createCtx(ACTORLESS_BOT), "prompt", {}); + expect(result.rejection).toBeUndefined(); + expect(result.enforced).toMatchObject({ participantUserId: null }); }); }); @@ -241,6 +225,30 @@ describe("resolveCanonicalUserId", () => { ); }); + it("rejects a canonical identity whose workspace access is suspended", async () => { + const ctx = createCtx(USER_PRINCIPAL); + const statement = { + bind: vi.fn(() => statement), + first: vi.fn(async () => null), + }; + ctx.db = { prepare: vi.fn(() => statement) } as never; + + const result = await resolveCanonicalUserId( + { resolveOrCreateUser: vi.fn() } as unknown as UserStore, + ctx, + { + participantUserId: "canon-1", + canonicalUserId: "canon-1", + actor: null, + spawnSource: "user", + }, + display + ); + + expect(result).toBeInstanceOf(Response); + expect((result as Response).status).toBe(403); + }); + it("fails closed with a 500 if a participant ever lacks both a canonical user and an actor", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const userStore = { resolveOrCreateUser: vi.fn() } as unknown as UserStore; diff --git a/packages/control-plane/src/auth/identity-enforcement.ts b/packages/control-plane/src/auth/identity-enforcement.ts index 7ae8620c11..29db52541c 100644 --- a/packages/control-plane/src/auth/identity-enforcement.ts +++ b/packages/control-plane/src/auth/identity-enforcement.ts @@ -198,7 +198,23 @@ export async function resolveCanonicalUserId( enforced: DerivedIdentity & { participantUserId: string }, display: { displayName?: string; email?: string; avatarUrl?: string } ): Promise<{ userId: string } | Response> { - if (enforced.canonicalUserId) return { userId: enforced.canonicalUserId }; + const requireActive = async (userId: string): Promise<{ userId: string } | Response> => { + try { + const active = await ctx.db + .prepare("SELECT 1 AS active FROM users WHERE id = ? AND suspended_at IS NULL") + .bind(userId) + .first<{ active: number }>(); + return active ? { userId } : error("Workspace access is disabled", 403); + } catch (cause) { + logger.error("Failed to verify workspace access", { + error: cause instanceof Error ? cause : String(cause), + request_id: ctx.request_id, + trace_id: ctx.trace_id, + }); + return error("Authorization unavailable", 503); + } + }; + if (enforced.canonicalUserId) return requireActive(enforced.canonicalUserId); const actor = enforced.actor; if (!actor) { // Unreachable while deriveIdentity holds its invariant (a participant @@ -219,7 +235,7 @@ export async function resolveCanonicalUserId( providerEmail: display.email, avatarUrl: display.avatarUrl, }); - return { userId: user.id }; + return requireActive(user.id); } catch (e) { logger.error("Failed to resolve verified actor identity", { error: e instanceof Error ? e : String(e), diff --git a/packages/control-plane/src/authorization/service-permissions.test.ts b/packages/control-plane/src/authorization/service-permissions.test.ts new file mode 100644 index 0000000000..5b20f99fd2 --- /dev/null +++ b/packages/control-plane/src/authorization/service-permissions.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from "vitest"; +import { serviceAllowsPermission } from "./service-permissions"; + +describe("serviceAllowsPermission", () => { + it("allows launch capabilities but denies management capabilities", () => { + expect(serviceAllowsPermission("slack-bot", "sessions.create")).toBe(true); + expect(serviceAllowsPermission("slack-bot", "global_secrets.manage")).toBe(false); + expect(serviceAllowsPermission("github-bot", "sessions.sandbox_access")).toBe(false); + }); +}); diff --git a/packages/control-plane/src/authorization/service-permissions.ts b/packages/control-plane/src/authorization/service-permissions.ts new file mode 100644 index 0000000000..1eb964df0f --- /dev/null +++ b/packages/control-plane/src/authorization/service-permissions.ts @@ -0,0 +1,45 @@ +import type { PermissionId } from "@open-inspect/shared/rbac"; +import type { ServiceName } from "@open-inspect/shared/service-auth"; + +const SERVICE_PERMISSION_CEILINGS: Record = { + web: [], + "github-bot": [ + "repositories.read", + "repositories.use", + "environments.read", + "environments.use", + "sessions.create", + "sessions.read", + "sessions.collaborate", + "sessions.lifecycle", + "skills.read", + ], + "slack-bot": [ + "repositories.read", + "repositories.use", + "environments.read", + "environments.use", + "sessions.create", + "sessions.read", + "sessions.collaborate", + "sessions.lifecycle", + "sessions.sandbox_access", + "skills.read", + ], + "linear-bot": [ + "repositories.read", + "repositories.use", + "environments.read", + "environments.use", + "sessions.create", + "sessions.read", + "sessions.collaborate", + "sessions.lifecycle", + "skills.read", + ], +}; + +/** Checks the hard permission ceiling for a trusted service, independent of user grants. */ +export function serviceAllowsPermission(service: ServiceName, permission: PermissionId): boolean { + return SERVICE_PERMISSION_CEILINGS[service].includes(permission); +} diff --git a/packages/control-plane/src/router.analytics.test.ts b/packages/control-plane/src/router.analytics.test.ts index 9972051573..4c8d5db66f 100644 --- a/packages/control-plane/src/router.analytics.test.ts +++ b/packages/control-plane/src/router.analytics.test.ts @@ -27,7 +27,7 @@ describe("analytics router integration", () => { vi.clearAllMocks(); }); - it("serves analytics routes even when the SCM provider is not github", async () => { + it("does not let an actorless service read analytics", async () => { mockStore.getSummary.mockResolvedValue({ totalSessions: 1, activeUsers: 1, @@ -63,21 +63,8 @@ describe("analytics router integration", () => { TEST_BACKGROUND_TASK_CONTEXT ); - expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual({ - totalSessions: 1, - activeUsers: 1, - totalCost: 0, - avgCost: 0, - totalPrs: 0, - statusBreakdown: { - created: 1, - active: 0, - completed: 0, - failed: 0, - archived: 0, - cancelled: 0, - }, - }); + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); + expect(mockStore.getSummary).not.toHaveBeenCalled(); }); }); diff --git a/packages/control-plane/src/router.create-session.test.ts b/packages/control-plane/src/router.create-session.test.ts index 0114453cd2..908eff8bb5 100644 --- a/packages/control-plane/src/router.create-session.test.ts +++ b/packages/control-plane/src/router.create-session.test.ts @@ -1,6 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { generateEncryptionKey } from "./auth/crypto"; -import type { Principal } from "./auth/principal"; import { SessionIndexStore } from "./db/session-index"; import { UserStore } from "./db/user-store"; import { handleRequest } from "./router"; @@ -15,6 +14,7 @@ import { SessionInternalPaths } from "./session/contracts"; import { resolveManagedSkills } from "./session/skill-resolution"; import { resolveSessionProviderAuth } from "./session/provider-account-resolution"; import { ProviderAccountSelectionPolicyError } from "./model-provider-accounts/selection-policy"; +import { resolveEnvironmentTarget, resolveSessionRepositories } from "./repos/resolve"; vi.mock("./db/session-index", () => ({ SessionIndexStore: vi.fn(), @@ -45,10 +45,14 @@ vi.mock("./routes/shared", async (importOriginal) => { }; }); -const USER_PRINCIPAL: Principal = { - kind: "user", - userId: "user-1", -}; +vi.mock("./repos/resolve", async (importOriginal) => { + const actual = (await importOriginal()) as Record; + return { + ...actual, + resolveEnvironmentTarget: vi.fn(), + resolveSessionRepositories: vi.fn(), + }; +}); describe("handleCreateSession D1 ordering", () => { beforeEach(() => { @@ -68,6 +72,16 @@ describe("handleCreateSession D1 ordering", () => { repoId: 12345, defaultBranch: "main", } as never); + vi.mocked(resolveEnvironmentTarget).mockResolvedValue([ + { repoOwner: "acme", repoName: "environment-repo", baseBranch: "main" }, + ]); + vi.mocked(resolveSessionRepositories).mockImplementation(async (_env, repositories) => + repositories.map((repository, index) => ({ + ...repository, + repoId: 12345 + index, + baseBranch: repository.baseBranch ?? "main", + })) + ); // Default identity fixture: the slack-bot's asserted actor resolves to an // already-known canonical user with no linked GitHub identity. vi.mocked(UserStore).mockImplementation(function () { @@ -119,10 +133,17 @@ describe("handleCreateSession D1 ordering", () => { ); } - function createEnv(initFetch: ReturnType): Record { + function createEnv( + initFetch: ReturnType, + permissions = ["sessions.create", "repositories.use", "environments.use"] + ): Record { const statement = { bind: vi.fn(() => statement), - first: vi.fn(async () => null), + first: vi + .fn() + .mockResolvedValueOnce({ suspended_at: null, assigned: 1 }) + .mockResolvedValueOnce({ active: 1 }) + .mockResolvedValue(null), all: vi.fn(async () => ({ results: [] })), run: vi.fn(async () => ({ meta: { changes: 0 } })), }; @@ -134,7 +155,33 @@ describe("handleCreateSession D1 ordering", () => { // the env must carry valid key material (the db stub answers "no rows"). TOKEN_ENCRYPTION_KEY: generateEncryptionKey(), DB: { - prepare: vi.fn(() => statement), + prepare: vi.fn((sql: string) => { + if (sql.includes("FROM users u") && sql.includes("user_role_assignments")) { + const authorizationStatement = { + bind: vi.fn(() => authorizationStatement), + first: vi.fn(async () => ({ + user_id: "user-1", + suspended_at: null, + role_id: "role-1", + role_key: null, + role_name: "Test Role", + })), + all: vi.fn(async () => ({ results: [] })), + }; + return authorizationStatement; + } + if (sql.includes("FROM role_permissions")) { + const permissionStatement = { + bind: vi.fn(() => permissionStatement), + first: vi.fn(async () => null), + all: vi.fn(async () => ({ + results: permissions.map((permission_id) => ({ permission_id })), + })), + }; + return permissionStatement; + } + return statement; + }), batch: vi.fn(), exec: vi.fn(), dump: vi.fn(), @@ -146,6 +193,76 @@ describe("handleCreateSession D1 ordering", () => { }; } + it.each([ + { + target: "environment", + body: { environmentId: "env_1" }, + permissions: ["sessions.create", "environments.use"], + status: 201, + deniedPermission: null, + }, + { + target: "environment", + body: { environmentId: "env_1" }, + permissions: ["sessions.create", "repositories.use"], + status: 403, + deniedPermission: "environments.use", + }, + { + target: "scalar repository", + body: { repoOwner: "acme", repoName: "widgets" }, + permissions: ["sessions.create", "repositories.use"], + status: 201, + deniedPermission: null, + }, + { + target: "scalar repository", + body: { repoOwner: "acme", repoName: "widgets" }, + permissions: ["sessions.create", "environments.use"], + status: 403, + deniedPermission: "repositories.use", + }, + { + target: "repository list", + body: { repositories: [{ repoOwner: "acme", repoName: "widgets" }] }, + permissions: ["sessions.create", "repositories.use"], + status: 201, + deniedPermission: null, + }, + { + target: "repository list", + body: { repositories: [{ repoOwner: "acme", repoName: "widgets" }] }, + permissions: ["sessions.create", "environments.use"], + status: 403, + deniedPermission: "repositories.use", + }, + ])( + "enforces the permission matrix for $target targets", + async ({ body, permissions, status, deniedPermission }) => { + const create = vi.fn().mockResolvedValue(undefined); + vi.mocked(SessionIndexStore).mockImplementation(function () { + return { create } as never; + }); + const initFetch = vi.fn(async () => Response.json({ status: "created" })); + + const response = await createSessionRequestWithBody(createEnv(initFetch, permissions), { + ...body, + title: "Permission matrix", + }); + + expect(response.status).toBe(status); + if (deniedPermission) { + await expect(response.json()).resolves.toMatchObject({ + code: "permission_required", + permission: deniedPermission, + }); + expect(create).not.toHaveBeenCalled(); + } else { + expect(create).toHaveBeenCalledOnce(); + } + } + ); + it("does not initialize the SessionDO when D1 session index creation fails", async () => { const create = vi.fn().mockRejectedValue(new Error("D1 unavailable")); vi.mocked(SessionIndexStore).mockImplementation(function () { @@ -452,9 +569,10 @@ describe("handleCreateSession D1 ordering", () => { model: "anthropic/claude-haiku-4-5", }); - expect(response.status).toBe(500); + expect(response.status).toBe(503); await expect(response.json()).resolves.toEqual({ - error: "Failed to resolve session identity", + error: "Authorization unavailable", + code: "authorization_unavailable", }); expect(create).not.toHaveBeenCalled(); expect(initFetch).not.toHaveBeenCalled(); @@ -511,7 +629,22 @@ describe("handleCreateSession D1 ordering", () => { { request_id: "test-request", trace_id: "test-trace", - principal: USER_PRINCIPAL, + principal: { + kind: "service", + service: "linear-bot", + actor: { + provider: "linear", + providerUserId: "linear-user-1", + canonicalUserId: "user-1", + participantUserId: "linear:linear-user-1", + }, + }, + authorization: { + userId: "user-1", + suspendedAt: null, + role: { id: "role-1", key: "member", name: "Member" }, + permissions: ["sessions.create", "repositories.use", "environments.use"], + }, db: testEnv["DB"] as never, executionCtx: TEST_BACKGROUND_TASK_CONTEXT, metrics: { diff --git a/packages/control-plane/src/router.policy.test.ts b/packages/control-plane/src/router.policy.test.ts index 2765af0856..56764d958a 100644 --- a/packages/control-plane/src/router.policy.test.ts +++ b/packages/control-plane/src/router.policy.test.ts @@ -13,11 +13,165 @@ describe("route policy table", () => { routes.every( (route) => route.authentication && + route.authorization && (route.supportedScmProviders === "all" || route.supportedScmProviders.length > 0) ) ).toBe(true); }); + it("has no duplicate method and pattern declarations", () => { + const identities = routes.map((route) => `${route.method}:${route.pattern}`); + expect(new Set(identities).size).toBe(identities.length); + }); + + it("declares authorization compatible with authentication", () => { + for (const route of routes) { + const authentication = route.authentication.kind; + const authorization = route.authorization; + if (authorization.kind === "none") { + expect(["public", "handler-authenticated", "web-service", "sandbox"]).toContain( + authentication + ); + } else if (authorization.kind === "authenticated" || authorization.kind === "active-self") { + expect(authentication).toBe("user"); + } else if (authorization.kind === "service") { + expect(authentication).toBe("user-or-service"); + expect(authorization.services.length).toBeGreaterThan(0); + } else if (authorization.kind === "active-global") { + expect(["user", "user-or-service"]).toContain(authentication); + } else { + expect(["user", "user-or-service", "user-or-service-with-sandbox-fallback"]).toContain( + authentication + ); + expect(authorization.allOf.length).toBeGreaterThan(0); + for (const requirement of authorization.allOf) { + if (requirement.kind === "automation") { + expect(route.pattern.source).toContain(`?<${requirement.automationIdParam}>`); + } + } + if (authorization.service.kind === "actor") { + for (const grant of authorization.service.actorlessGrants ?? []) { + for (const pathParam of Object.keys(grant.pathParams ?? {})) { + expect(route.pattern.source).toContain(`?<${pathParam}>`); + } + } + } + } + } + }); + + it.each([ + ["GET", "/repos", [{ service: "slack-bot" }, { service: "linear-bot" }]], + ["GET", "/repos/acme/widgets/metadata", [{ service: "github-bot" }]], + ["GET", "/environments", [{ service: "slack-bot" }, { service: "linear-bot" }]], + ["GET", "/environments/env-1", [{ service: "github-bot" }]], + ["GET", "/integration-settings/slack", [{ service: "slack-bot", pathParams: { id: "slack" } }]], + [ + "GET", + "/integration-settings/github/resolved/acme/widgets", + [ + { service: "github-bot", pathParams: { id: "github" } }, + { service: "linear-bot", pathParams: { id: "linear" } }, + ], + ], + ["GET", "/integration-settings/slack/watched-channels", [{ service: "slack-bot" }]], + ["GET", "/model-preferences", [{ service: "slack-bot" }]], + ])("declares the exact actorless grants for %s %s", (method, path, expected) => { + const authorization = routeFor(method, path)?.authorization; + expect(["active-user", "active-global"]).toContain(authorization?.kind); + if (authorization?.kind === "active-user" || authorization?.kind === "active-global") { + expect(authorization.service.kind).toBe("actor"); + if (authorization.service.kind === "actor") { + expect(authorization.service.actorlessGrants).toEqual(expected); + } + } + }); + + it("does not declare actorless grants on other routes", () => { + const expected = new Set([ + routeFor("GET", "/repos"), + routeFor("GET", "/repos/acme/widgets/metadata"), + routeFor("GET", "/environments"), + routeFor("GET", "/environments/env-1"), + routeFor("GET", "/integration-settings/slack"), + routeFor("GET", "/integration-settings/github/resolved/acme/widgets"), + routeFor("GET", "/integration-settings/slack/watched-channels"), + routeFor("GET", "/model-preferences"), + routeFor("POST", "/sessions/session-1/stop"), + routeFor("GET", "/sessions/session-1/media/artifact-1"), + ]); + const granted = routes.filter( + (route) => + (route.authorization.kind === "active-user" || + route.authorization.kind === "active-global") && + route.authorization.service.kind === "actor" && + (route.authorization.service.actorlessGrants?.length ?? 0) > 0 + ); + + expect(new Set(granted)).toEqual(expected); + }); + + it("keeps contextual route requirements explicit", () => { + expect(routeFor("GET", "/keyboard-shortcuts")?.authorization).toEqual({ + kind: "active-self", + }); + expect(routeFor("GET", "/model-preferences")?.authorization).toMatchObject({ + kind: "active-global", + service: { kind: "actor", actorlessGrants: [{ service: "slack-bot" }] }, + }); + expect(routeFor("GET", "/sessions")?.authorization).toMatchObject({ + kind: "active-user", + allOf: [{ kind: "permission", permission: "sessions.read" }], + service: { kind: "actor" }, + }); + expect(routeFor("GET", "/sessions/inbox")?.authorization).toMatchObject({ + kind: "active-user", + allOf: [{ kind: "permission", permission: "sessions.read" }], + service: { kind: "deny" }, + }); + expect(routeFor("POST", "/sessions/session-1/stop")?.authorization).toMatchObject({ + service: { kind: "actor", actorlessGrants: [{ service: "linear-bot" }] }, + }); + expect(routeFor("GET", "/sessions/session-1/media/artifact-1")?.authorization).toMatchObject({ + service: { kind: "actor", actorlessGrants: [{ service: "slack-bot" }] }, + }); + expect(routeFor("POST", "/sessions/session-1/participants")?.authorization).toEqual({ + kind: "active-user", + allOf: [{ kind: "permission", permission: "sessions.collaborate" }], + service: { kind: "actor" }, + }); + expect(routeFor("POST", "/sessions/parent/children")?.authorization).toMatchObject({ + kind: "active-user", + allOf: [ + { kind: "permission", permission: "sessions.create" }, + { kind: "permission", permission: "sessions.collaborate" }, + ], + }); + expect(routeFor("GET", "/sessions/parent/children/child")?.authorization).toMatchObject({ + kind: "active-user", + allOf: [{ kind: "permission", permission: "sessions.read" }], + }); + expect(routeFor("POST", "/internal/github-event")?.authorization).toMatchObject({ + kind: "service", + services: ["github-bot"], + }); + }); + + it.each([ + ["PUT", "/automations/automation-1", "manage"], + ["DELETE", "/automations/automation-1", "manage"], + ["POST", "/automations/automation-1/pause", "manage"], + ["POST", "/automations/automation-1/resume", "manage"], + ["POST", "/automations/automation-1/trigger", "trigger"], + ["POST", "/automations/automation-1/regenerate-key", "manage"], + ])("declares typed automation admission for %s %s", (method, path, operation) => { + expect(routeFor(method, path)?.authorization).toMatchObject({ + kind: "active-user", + allOf: [{ kind: "automation", operation, automationIdParam: "id" }], + service: { kind: "deny" }, + }); + }); + it.each([ ["GET", "/health", "public"], ["POST", "/webhooks/sentry/automation-1", "handler-authenticated"], @@ -61,6 +215,7 @@ describe("route policy table", () => { if (route?.authentication.kind === "user-or-service-with-sandbox-fallback") { expect(route.authentication.getSessionId(match)).toBe("session-1"); } + expect(route?.authorization.kind).toBe("active-user"); }); it.each([ @@ -199,6 +354,26 @@ describe("route policy dispatch ordering", () => { }); }); + it("keeps health live and private when the RBAC lookup fails", async () => { + const testEnv = env("github"); + testEnv.DB.prepare = vi.fn(() => { + throw new Error("D1 unavailable"); + }); + + const response = await handleRequest( + new Request("https://test.local/health"), + testEnv as never, + TEST_BACKGROUND_TASK_CONTEXT + ); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ + status: "healthy", + service: "open-inspect-control-plane", + rbac: { ownerAssignment: "unknown" }, + }); + }); + it("applies broker cache policy when sandbox authentication is unavailable", async () => { const testEnv = env("github") as ReturnType & { SESSION: { diff --git a/packages/control-plane/src/router.scm-credentials.test.ts b/packages/control-plane/src/router.scm-credentials.test.ts index 32c3e48fe9..9862a58eac 100644 --- a/packages/control-plane/src/router.scm-credentials.test.ts +++ b/packages/control-plane/src/router.scm-credentials.test.ts @@ -128,7 +128,7 @@ describe("SCM credentials router provider gate", () => { expect(new URL(fetch.mock.calls[1][0].url).pathname).toBe("/internal/scm-credentials"); }); - it("allows GitLab deployments to reach the tunnel URLs endpoint", async () => { + it("requires an actor for service access to tunnel URLs", async () => { const { env, fetch } = createEnv(); const response = await handleRequest( @@ -139,10 +139,9 @@ describe("SCM credentials router provider gate", () => { TEST_BACKGROUND_TASK_CONTEXT ); - expect(response.status).toBe(202); - expect(fetch).toHaveBeenCalledOnce(); - const request = fetch.mock.calls[0][0]; - expect(new URL(request.url).pathname).toBe("/internal/tunnel-urls"); + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); + expect(fetch).not.toHaveBeenCalled(); }); it("treats provider-neutral SCM settings routes as SCM-agnostic", () => { @@ -218,7 +217,7 @@ describe("SCM credentials router provider gate", () => { expect(new URL(fetch.mock.calls[0][0].url).pathname).toBe("/internal/verify-sandbox-token"); }); - it("continues blocking unrelated GitLab session routes", async () => { + it("rejects actorless services before unrelated GitLab session routes", async () => { const { env, fetch } = createEnv(); const response = await handleRequest( @@ -230,10 +229,8 @@ describe("SCM credentials router provider gate", () => { TEST_BACKGROUND_TASK_CONTEXT ); - expect(response.status).toBe(501); - await expect(response.json()).resolves.toEqual({ - error: "SCM provider 'gitlab' is not implemented in this deployment.", - }); + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); expect(fetch).not.toHaveBeenCalled(); }); diff --git a/packages/control-plane/src/router.session-prompt.test.ts b/packages/control-plane/src/router.session-prompt.test.ts index 38074d47a6..aed5096c7a 100644 --- a/packages/control-plane/src/router.session-prompt.test.ts +++ b/packages/control-plane/src/router.session-prompt.test.ts @@ -58,8 +58,17 @@ function userPromptRequest(body: Record): Promise { function createEnv(sessionFetch: ReturnType): Record { const statement = { bind: vi.fn(() => statement), - first: vi.fn(async () => null), - all: vi.fn(async () => ({ results: [] })), + first: vi.fn(async () => ({ + user_id: "user-1", + suspended_at: null, + assigned: 1, + role_id: "role-administrator", + role_key: "administrator", + role_name: "Administrator", + })), + all: vi.fn(async () => ({ + results: [{ permission_id: "sessions.collaborate" }], + })), run: vi.fn(async () => ({ meta: { changes: 0 } })), }; return { diff --git a/packages/control-plane/src/router.spawn-child.test.ts b/packages/control-plane/src/router.spawn-child.test.ts index 40d2ccfd5b..666ea30d6a 100644 --- a/packages/control-plane/src/router.spawn-child.test.ts +++ b/packages/control-plane/src/router.spawn-child.test.ts @@ -23,6 +23,12 @@ vi.mock("./db/model-preferences", () => ({ getEffectiveEnabledModels: vi.fn(), })); +vi.mock("./db/user-store", () => ({ + UserStore: vi.fn().mockImplementation(function () { + return { getIdentity: async () => ({ userId: "canonical-user-123" }) }; + }), +})); + vi.mock("./session/integration-settings-resolution", () => integrationSettingsMocks); describe("handleSpawnChild prompt enqueue handling", () => { @@ -173,6 +179,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { method: "POST", body: JSON.stringify(body), service: "linear-bot", + actor: "linear:U1", }), env as never, TEST_BACKGROUND_TASK_CONTEXT @@ -198,7 +205,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { env: { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -340,7 +347,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -434,7 +441,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -482,7 +489,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -514,7 +521,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -525,6 +532,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { await signedServiceRequest(`https://test.local/sessions/${parentId}/children`, { method: "POST", service: "linear-bot", + actor: "linear:U1", body: JSON.stringify({ title: "Child task", prompt: "Do the thing", @@ -554,7 +562,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -577,7 +585,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: vi.fn(), @@ -588,6 +596,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { await signedServiceRequest(`https://test.local/sessions/${parentId}/children`, { method: "POST", service: "linear-bot", + actor: "linear:U1", body: JSON.stringify({ title: "Child task" }), }), env as never, @@ -612,7 +621,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -640,7 +649,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -666,7 +675,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -699,7 +708,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -740,7 +749,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -768,7 +777,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -779,6 +788,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { await signedServiceRequest(`https://test.local/sessions/${parentId}/children`, { method: "POST", service: "linear-bot", + actor: "linear:U1", body: JSON.stringify({ title: "Child task", prompt: "Do the thing", @@ -809,7 +819,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: () => parentStub, @@ -849,7 +859,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { const env = { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: {}, + DB: authorizedDb(), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -866,3 +876,33 @@ describe("handleSpawnChild prompt enqueue handling", () => { expect(store.updateStatus).toHaveBeenCalledWith(createdChildId, "failed"); }); }); +function authorizedDb() { + return { + prepare: vi.fn((sql: string) => { + const statement = { + bind: vi.fn(() => statement), + first: vi.fn(async () => + sql.includes("FROM users u") + ? { + user_id: "canonical-user-123", + suspended_at: null, + role_id: "role-1", + role_key: "member", + role_name: "Member", + } + : null + ), + all: vi.fn(async () => ({ + results: sql.includes("FROM role_permissions") + ? [ + { permission_id: "sessions.create" }, + { permission_id: "repositories.use" }, + { permission_id: "sessions.collaborate" }, + ] + : [], + })), + }; + return statement; + }), + }; +} diff --git a/packages/control-plane/src/router.ts b/packages/control-plane/src/router.ts index ed694c9db3..428ec9a81b 100644 --- a/packages/control-plane/src/router.ts +++ b/packages/control-plane/src/router.ts @@ -15,15 +15,24 @@ import { SessionInternalPaths } from "./session/contracts"; import { createSessionRuntimeClient } from "./session/runtime-client"; import { createRequestMetrics, instrumentD1 } from "./db/instrumented-d1"; +import { UserStore } from "./db/user-store"; +import { AutomationStore } from "./db/automation-store"; +import { AuthorizationError, AuthorizationService } from "./authorization/service"; +import { serviceAllowsPermission } from "./authorization/service-permissions"; +import { SCOPED_PERMISSION_PAIRS, resolveScopedPermission } from "@open-inspect/shared/rbac"; import { createLogger } from "./logger"; import type { BackgroundTasks } from "./platform-ports"; import { + type ActorlessServiceGrant, type Route, type RouteAuthentication, + type RouteAuthorizationRequirement, type RequestContext, defineRoute, GITHUB_SANDBOX_FALLBACK_ROUTE, + NO_AUTHORIZATION, parsePattern, + requirePermission, json, error, HttpError, @@ -45,6 +54,7 @@ import { analyticsRoutes } from "./routes/analytics"; import { autofixRoutes } from "./routes/autofix"; import { skillRoutes } from "./routes/skills"; import { keyboardShortcutRoutes } from "./routes/keyboard-shortcuts"; +import { rbacRoutes } from "./routes/rbac"; import { sessionRoutes } from "./routes/sessions"; import { modelProviderAccountRoutes } from "./routes/model-provider-accounts"; import { handleSlackNotify } from "./routes/slack-notify"; @@ -295,6 +305,215 @@ export function enforceRoutePrincipal( return null; } +async function enforceActiveUser(route: Route, ctx: RequestContext): Promise { + if ( + route.authorization.kind !== "active-user" && + route.authorization.kind !== "active-self" && + route.authorization.kind !== "active-global" + ) { + return null; + } + let resolvedServiceUserId: string | null = null; + if ( + ctx.principal?.kind === "service" && + ctx.principal.actor && + !ctx.principal.actor.canonicalUserId + ) { + try { + const user = await new UserStore(ctx.db).resolveOrCreateUser({ + provider: ctx.principal.actor.provider, + providerUserId: ctx.principal.actor.providerUserId, + }); + resolvedServiceUserId = user.id; + } catch { + return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); + } + } + const userId = + ctx.principal?.kind === "user" + ? ctx.principal.userId + : ctx.principal?.kind === "service" + ? (ctx.principal.actor?.canonicalUserId ?? resolvedServiceUserId) + : null; + if (!userId) return null; + try { + const authorization = await new AuthorizationService(ctx.db).getEffectiveAuthorization(userId); + ctx.authorization = authorization; + if (authorization.suspendedAt !== null) { + return json({ error: "Forbidden", code: "active_user_required" }, 403); + } + return null; + } catch (cause) { + if (cause instanceof AuthorizationError) { + return json({ error: "Forbidden", code: cause.code }, cause.status); + } + return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); + } +} + +function authorizationUserId(ctx: RequestContext): string | null { + if (ctx.principal?.kind === "user") return ctx.principal.userId; + if (ctx.principal?.kind === "service") { + return ctx.principal.actor?.canonicalUserId ?? ctx.authorization?.userId ?? null; + } + return null; +} + +function actorlessGrantMatches( + grant: ActorlessServiceGrant, + service: string, + match: RegExpMatchArray +): boolean { + if (grant.service !== service) return false; + return Object.entries(grant.pathParams ?? {}).every(([name, expected]) => { + const value = match.groups?.[name]; + if (value === undefined) return false; + try { + return decodeURIComponent(value) === expected; + } catch { + return false; + } + }); +} + +function enforceServiceRouteAuthorization( + route: Route, + match: RegExpMatchArray, + ctx: RequestContext +): Response | null { + const principal = ctx.principal; + if (principal?.kind !== "service") return null; + if (route.authentication.kind === "web-service" && principal.service === "web") return null; + + const authorization = route.authorization; + if (authorization.kind === "service") { + if (!authorization.services.some((service) => service === principal.service)) { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } + if (authorization.actor === "required" && !principal.actor) { + return json({ error: "Forbidden", code: "service_actor_required" }, 403); + } + return null; + } + if ( + (authorization.kind !== "active-user" && authorization.kind !== "active-global") || + authorization.service.kind === "deny" + ) { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } + if (principal.actor) return null; + const granted = authorization.service.actorlessGrants?.some((grant) => + actorlessGrantMatches(grant, principal.service, match) + ); + return granted ? null : json({ error: "Forbidden", code: "service_actor_required" }, 403); +} + +async function enforcePermissionRequirement( + requirement: Extract, + ctx: RequestContext +): Promise { + const userId = authorizationUserId(ctx); + if (!userId) return null; + if ( + ctx.principal?.kind === "service" && + !serviceAllowsPermission(ctx.principal.service, requirement.permission) + ) { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } + if (ctx.authorization?.permissions.includes(requirement.permission)) return null; + return json( + { error: "Forbidden", code: "permission_required", permission: requirement.permission }, + 403 + ); +} + +async function enforceScopedPermissionRequirement( + requirement: Extract, + ctx: RequestContext +): Promise { + const userId = authorizationUserId(ctx); + if (!userId) return null; + const pair = SCOPED_PERMISSION_PAIRS[requirement.stem]; + if ( + ctx.principal?.kind === "service" && + !serviceAllowsPermission(ctx.principal.service, pair.own) + ) { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } + if ( + ctx.authorization && + resolveScopedPermission(requirement.stem, ctx.authorization.permissions) + ) { + return null; + } + return json({ error: "Forbidden", code: "permission_required", permission: pair.own }, 403); +} + +async function enforceAutomationRequirement( + requirement: Extract, + match: RegExpMatchArray, + ctx: RequestContext +): Promise { + if (ctx.principal?.kind !== "user") return null; + const encodedAutomationId = match.groups?.[requirement.automationIdParam]; + if (!encodedAutomationId) return json({ error: "Invalid automation route" }, 400); + let automationId: string; + try { + automationId = decodeURIComponent(encodedAutomationId); + } catch { + return json({ error: "Invalid automation route" }, 400); + } + + try { + const authorization = ctx.authorization; + if (!authorization) throw new Error("Missing request authorization"); + const automation = await new AutomationStore(ctx.db).getById(automationId); + if (!automation) return error("Automation not found", 404); + + const permissionStem = `automations.${requirement.operation}` as const; + const permissionScope = resolveScopedPermission(permissionStem, authorization.permissions); + const ownPermission = SCOPED_PERMISSION_PAIRS[permissionStem].own; + if ( + !permissionScope || + (permissionScope === "own" && automation.user_id !== ctx.principal.userId) + ) { + return json( + { error: "Forbidden", code: "permission_required", permission: ownPermission }, + 403 + ); + } + + ctx.automationAdmission = { automation }; + return null; + } catch { + return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); + } +} + +async function enforceRouteAuthorization( + route: Route, + match: RegExpMatchArray, + ctx: RequestContext +): Promise { + if (route.authorization.kind !== "active-user") return null; + for (const requirement of route.authorization.allOf) { + let authorizationError: Response | null; + switch (requirement.kind) { + case "permission": + authorizationError = await enforcePermissionRequirement(requirement, ctx); + break; + case "scoped-permission": + authorizationError = await enforceScopedPermissionRequirement(requirement, ctx); + break; + case "automation": + authorizationError = await enforceAutomationRequirement(requirement, match, ctx); + break; + } + if (authorizationError) return authorizationError; + } + return null; +} + /** * Routes definition. */ @@ -305,7 +524,29 @@ export const routes: Route[] = [ supportedScmProviders: "all", method: "GET", pattern: parsePattern("/health"), - handler: async () => json({ status: "healthy", service: "open-inspect-control-plane" }), + authorization: NO_AUTHORIZATION, + handler: async (_request, _env, _match, ctx) => { + let ownerAssignment: "present" | "missing" | "unknown"; + try { + const owner = await ctx.db + .prepare( + `SELECT 1 AS complete FROM users u + JOIN user_role_assignments ura ON ura.user_id = u.id + JOIN roles r ON r.id = ura.role_id + WHERE r.key = 'owner' AND u.suspended_at IS NULL + LIMIT 1` + ) + .first(); + ownerAssignment = owner ? "present" : "missing"; + } catch { + ownerAssignment = "unknown"; + } + return json({ + status: "healthy", + service: "open-inspect-control-plane", + rbac: { ownerAssignment }, + }); + }, }, ...browserAuthRoutes, @@ -317,6 +558,7 @@ export const routes: Route[] = [ defineRoute(GITHUB_SANDBOX_FALLBACK_ROUTE, { method: "POST", pattern: parsePattern("/sessions/:id/slack-notify"), + authorization: requirePermission("sessions.collaborate"), handler: handleSlackNotify, }), @@ -366,6 +608,9 @@ export const routes: Route[] = [ // Personal keyboard shortcuts ...keyboardShortcutRoutes, + // Workspace roles, members, and current-user authorization + ...rbacRoutes, + // Webhooks (public routes — auth handled per-route) ...webhookRoutes, ]; @@ -495,6 +740,38 @@ export async function handleRequest( } } + const serviceAccessError = enforceServiceRouteAuthorization( + matchedRoute.route, + matchedRoute.match, + ctx + ); + if (serviceAccessError) { + logRequest(serviceAccessError, ctx, method, path, startTime); + return withCorsAndTraceHeaders( + withRouteCachePolicy(serviceAccessError, matchedRoute.route), + ctx + ); + } + + const userAccessError = await enforceActiveUser(matchedRoute.route, ctx); + if (userAccessError) { + logRequest(userAccessError, ctx, method, path, startTime); + return withCorsAndTraceHeaders(withRouteCachePolicy(userAccessError, matchedRoute.route), ctx); + } + + const authorizationError = await enforceRouteAuthorization( + matchedRoute.route, + matchedRoute.match, + ctx + ); + if (authorizationError) { + logRequest(authorizationError, ctx, method, path, startTime); + return withCorsAndTraceHeaders( + withRouteCachePolicy(authorizationError, matchedRoute.route), + ctx + ); + } + const providerCheck = enforceImplementedScmProvider(matchedRoute.route, path, env, ctx); if (providerCheck) { return withRouteCachePolicy(providerCheck, matchedRoute.route); diff --git a/packages/control-plane/src/routes/analytics.ts b/packages/control-plane/src/routes/analytics.ts index 5bbef8120e..53e17b20be 100644 --- a/packages/control-plane/src/routes/analytics.ts +++ b/packages/control-plane/src/routes/analytics.ts @@ -18,6 +18,7 @@ import { error, json, parsePattern, + requirePermission, } from "./shared"; function parseDaysParam(value: string | null): AnalyticsDays | null { @@ -124,21 +125,25 @@ export const analyticsRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_USER_OR_SERVIC { method: "GET", pattern: parsePattern("/analytics/summary"), + authorization: requirePermission("analytics.read"), handler: handleSummary, }, { method: "GET", pattern: parsePattern("/analytics/timeseries"), + authorization: requirePermission("analytics.read"), handler: handleTimeseries, }, { method: "GET", pattern: parsePattern("/analytics/breakdown"), + authorization: requirePermission("analytics.read"), handler: handleBreakdown, }, { method: "GET", pattern: parsePattern("/analytics/pull-requests"), + authorization: requirePermission("analytics.read"), handler: handlePullRequests, }, ]); diff --git a/packages/control-plane/src/routes/autofix.ts b/packages/control-plane/src/routes/autofix.ts index 723dbb295e..f132d243d1 100644 --- a/packages/control-plane/src/routes/autofix.ts +++ b/packages/control-plane/src/routes/autofix.ts @@ -3,6 +3,7 @@ import { defineRoutes, error, json, + NO_AUTHORIZATION, parsePattern, SCM_AGNOSTIC_WEB_SERVICE_ROUTE, type Route, @@ -35,6 +36,7 @@ export const autofixRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_WEB_SERVICE_ROUT { method: "GET", pattern: parsePattern("/autofix/activity"), + authorization: NO_AUTHORIZATION, handler: handleActivity, }, ]); diff --git a/packages/control-plane/src/routes/automations.test.ts b/packages/control-plane/src/routes/automations.test.ts index c517525777..769ca4953f 100644 --- a/packages/control-plane/src/routes/automations.test.ts +++ b/packages/control-plane/src/routes/automations.test.ts @@ -179,11 +179,20 @@ const SLACK_BOT_PRINCIPAL: Principal = { }; function createCtx(principal: Principal = USER_PRINCIPAL): RequestContext { + const statement = { + bind: vi.fn(), + first: vi.fn(async () => ({ active: 1 })), + }; + statement.bind.mockReturnValue(statement); + return { trace_id: "trace-1", request_id: "req-1", principal, - db: { batch: mockBatch } as unknown as SqlDatabase, + db: { + batch: mockBatch, + prepare: vi.fn(() => statement), + } as unknown as SqlDatabase, executionCtx: TEST_BACKGROUND_TASK_CONTEXT, metrics: { d1Queries: [], diff --git a/packages/control-plane/src/routes/automations.ts b/packages/control-plane/src/routes/automations.ts index 624232123e..fc638ed7fe 100644 --- a/packages/control-plane/src/routes/automations.ts +++ b/packages/control-plane/src/routes/automations.ts @@ -61,6 +61,8 @@ import { error, parseJsonBody, resolveRepoOrError, + requireAutomation, + requirePermission, } from "./shared"; import type { Env } from "../types"; import type { SqlDatabase, SqlStatement } from "../db/sql-database"; @@ -1354,66 +1356,81 @@ export const automationRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ROU { method: "GET", pattern: parsePattern("/integration-settings/slack/watched-channels"), + authorization: requirePermission("automations.read", { + actorlessGrants: [{ service: "slack-bot" }], + }), handler: handleGetWatchedSlackChannels, }, { method: "GET", pattern: parsePattern("/integration-settings/slack/channels"), + authorization: requirePermission("automations.read"), handler: handleGetSlackChannels, }, { method: "GET", pattern: parsePattern("/automations"), + authorization: requirePermission("automations.read"), handler: handleListAutomations, }, { method: "POST", pattern: parsePattern("/automations"), + authorization: requirePermission("automations.create"), handler: handleCreateAutomation, }, { method: "GET", pattern: parsePattern("/automations/:id"), + authorization: requirePermission("automations.read"), handler: handleGetAutomation, }, { method: "PUT", pattern: parsePattern("/automations/:id"), + authorization: requireAutomation("manage"), handler: handleUpdateAutomation, }, { method: "DELETE", pattern: parsePattern("/automations/:id"), + authorization: requireAutomation("manage"), handler: handleDeleteAutomation, }, { method: "POST", pattern: parsePattern("/automations/:id/pause"), + authorization: requireAutomation("manage"), handler: handlePauseAutomation, }, { method: "POST", pattern: parsePattern("/automations/:id/resume"), + authorization: requireAutomation("manage"), handler: handleResumeAutomation, }, { method: "POST", pattern: parsePattern("/automations/:id/trigger"), + authorization: requireAutomation("trigger"), handler: handleTriggerAutomation, }, { method: "GET", pattern: parsePattern("/automations/:id/invocations"), + authorization: requirePermission("automations.read"), handler: handleListInvocations, }, { method: "GET", pattern: parsePattern("/automations/:id/runs/:runId"), + authorization: requirePermission("automations.read"), handler: handleGetRun, }, { method: "POST", pattern: parsePattern("/automations/:id/regenerate-key"), + authorization: requireAutomation("manage"), handler: handleRegenerateKey, }, ]); diff --git a/packages/control-plane/src/routes/browser-auth.ts b/packages/control-plane/src/routes/browser-auth.ts index 7bbc71546f..395fe0eb88 100644 --- a/packages/control-plane/src/routes/browser-auth.ts +++ b/packages/control-plane/src/routes/browser-auth.ts @@ -4,6 +4,7 @@ import { createLogger } from "../logger"; import { defineRoutes, error, + NO_AUTHORIZATION, parsePattern, SCM_AGNOSTIC_WEB_SERVICE_ROUTE, type Route, @@ -54,7 +55,8 @@ const handleBrowserAuth: Route["handler"] = async (request, _env, _match, ctx) = if (!ctx.getUserAuth) { throw new UserAuthConfigurationError("User authentication runtime is unavailable"); } - const response = await forwardBrowserAuthRequest(ctx.getUserAuth(), request); + const auth = ctx.getUserAuth(); + const response = await forwardBrowserAuthRequest(auth, request); const headers = copyBrowserAuthResponseHeaders(response.headers); headers.set("Cache-Control", "no-store"); headers.set("Referrer-Policy", "no-referrer"); @@ -86,6 +88,7 @@ export const browserAuthRoutes: Route[] = defineRoutes( BROWSER_AUTH_PROXY_ROUTES.map(([method, path]) => ({ method, pattern: parsePattern(path), + authorization: NO_AUTHORIZATION, handler: handleBrowserAuth, })) ); diff --git a/packages/control-plane/src/routes/commit-signing.ts b/packages/control-plane/src/routes/commit-signing.ts index a9e851176b..9286faa8ab 100644 --- a/packages/control-plane/src/routes/commit-signing.ts +++ b/packages/control-plane/src/routes/commit-signing.ts @@ -19,6 +19,8 @@ import { defineRoute, GITHUB_USER_OR_SERVICE_ROUTE, SCM_AGNOSTIC_SANDBOX_ROUTE, + NO_AUTHORIZATION, + requirePermission, } from "./shared"; const MAX_SIGNING_PAYLOAD_BYTES = 1024 * 1024; @@ -215,26 +217,31 @@ export const commitSigningRoutes: Route[] = [ defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "GET", pattern: parsePattern("/commit-signing"), + authorization: requirePermission("integrations.read"), handler: handleGetCommitSigning, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "PUT", pattern: parsePattern("/commit-signing"), + authorization: requirePermission("commit_signing.manage"), handler: handlePutCommitSigning, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "DELETE", pattern: parsePattern("/commit-signing"), + authorization: requirePermission("commit_signing.manage"), handler: handleDeleteCommitSigning, }), defineRoute(SCM_AGNOSTIC_SANDBOX_ROUTE, { method: "GET", pattern: parsePattern("/sessions/:id/commit-signing"), + authorization: NO_AUTHORIZATION, handler: handleGetSandboxCommitSigning, }), defineRoute(SCM_AGNOSTIC_SANDBOX_ROUTE, { method: "POST", pattern: parsePattern("/sessions/:id/commit-signing"), + authorization: NO_AUTHORIZATION, handler: handlePostSandboxCommitSigning, }), ]; diff --git a/packages/control-plane/src/routes/environment-secrets.ts b/packages/control-plane/src/routes/environment-secrets.ts index 790c073df7..460d56505b 100644 --- a/packages/control-plane/src/routes/environment-secrets.ts +++ b/packages/control-plane/src/routes/environment-secrets.ts @@ -23,6 +23,7 @@ import { error, parseJsonBody, resolveRepoOrError, + requirePermission, } from "./shared"; import { environmentSecretsImportBodySchema, @@ -304,21 +305,25 @@ export const environmentSecretsRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SER { method: "GET", pattern: parsePattern("/environments/:id/secrets"), + authorization: requirePermission("environments.secrets.manage"), handler: handleListEnvironmentSecrets, }, { method: "PUT", pattern: parsePattern("/environments/:id/secrets"), + authorization: requirePermission("environments.secrets.manage"), handler: handleSetEnvironmentSecrets, }, { method: "POST", pattern: parsePattern("/environments/:id/secrets/import"), + authorization: requirePermission("environments.secrets.manage"), handler: handleImportEnvironmentSecrets, }, { method: "DELETE", pattern: parsePattern("/environments/:id/secrets/:key"), + authorization: requirePermission("environments.secrets.manage"), handler: handleDeleteEnvironmentSecret, }, ]); diff --git a/packages/control-plane/src/routes/environments.ts b/packages/control-plane/src/routes/environments.ts index 80fc8942eb..17201e3e88 100644 --- a/packages/control-plane/src/routes/environments.ts +++ b/packages/control-plane/src/routes/environments.ts @@ -30,6 +30,7 @@ import { error, parseJsonBody, resolveRepoOrError, + requirePermission, } from "./shared"; import type { Env } from "../types"; @@ -263,13 +264,38 @@ async function handleDeleteEnvironment( } export const environmentRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ROUTE, [ - { method: "GET", pattern: parsePattern("/environments"), handler: handleListEnvironments }, - { method: "POST", pattern: parsePattern("/environments"), handler: handleCreateEnvironment }, - { method: "GET", pattern: parsePattern("/environments/:id"), handler: handleGetEnvironment }, - { method: "PUT", pattern: parsePattern("/environments/:id"), handler: handleUpdateEnvironment }, + { + method: "GET", + pattern: parsePattern("/environments"), + authorization: requirePermission("environments.read", { + actorlessGrants: [{ service: "slack-bot" }, { service: "linear-bot" }], + }), + handler: handleListEnvironments, + }, + { + method: "POST", + pattern: parsePattern("/environments"), + authorization: requirePermission("environments.manage"), + handler: handleCreateEnvironment, + }, + { + method: "GET", + pattern: parsePattern("/environments/:id"), + authorization: requirePermission("environments.read", { + actorlessGrants: [{ service: "github-bot" }], + }), + handler: handleGetEnvironment, + }, + { + method: "PUT", + pattern: parsePattern("/environments/:id"), + authorization: requirePermission("environments.manage"), + handler: handleUpdateEnvironment, + }, { method: "DELETE", pattern: parsePattern("/environments/:id"), + authorization: requirePermission("environments.manage"), handler: handleDeleteEnvironment, }, ]); diff --git a/packages/control-plane/src/routes/image-builds.ts b/packages/control-plane/src/routes/image-builds.ts index 6610925c73..d199bf7a1d 100644 --- a/packages/control-plane/src/routes/image-builds.ts +++ b/packages/control-plane/src/routes/image-builds.ts @@ -49,6 +49,8 @@ import { json, parseJsonBody, parsePattern, + NO_AUTHORIZATION, + requirePermission, } from "./shared"; const logger = createLogger("router:image-builds"); @@ -494,41 +496,49 @@ export const imageBuildRoutes: Route[] = [ defineRoute(SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, { method: "POST", pattern: parsePattern("/image-builds/build-complete"), + authorization: NO_AUTHORIZATION, handler: handleBuildComplete, }), defineRoute(SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, { method: "POST", pattern: parsePattern("/image-builds/build-failed"), + authorization: NO_AUTHORIZATION, handler: handleBuildFailed, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "POST", pattern: parsePattern("/image-builds/trigger/environment/:id"), + authorization: requirePermission("environments.images.manage"), handler: handleTriggerEnvironmentBuild, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "POST", pattern: parsePattern("/image-builds/trigger/repo/:owner/:name"), + authorization: requirePermission("repositories.images.manage"), handler: handleTriggerRepoBuild, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "PUT", pattern: parsePattern("/image-builds/toggle/repo/:owner/:name"), + authorization: requirePermission("repositories.images.manage"), handler: handleToggleRepoImageBuilds, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "GET", pattern: parsePattern("/image-builds/status"), + authorization: requirePermission("image_builds.read"), handler: handleGetStatus, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "GET", pattern: parsePattern("/image-builds/enabled"), + authorization: requirePermission("image_builds.read"), handler: handleGetEnabledUnits, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "GET", pattern: parsePattern("/image-builds/enabled-repos"), + authorization: requirePermission("image_builds.read"), handler: handleGetEnabledRepos, }), ]; diff --git a/packages/control-plane/src/routes/integration-settings.ts b/packages/control-plane/src/routes/integration-settings.ts index 1d1ca75485..bc2e81e89c 100644 --- a/packages/control-plane/src/routes/integration-settings.ts +++ b/packages/control-plane/src/routes/integration-settings.ts @@ -34,6 +34,7 @@ import { error, parseJsonBody, extractRepoParams, + requirePermission, } from "./shared"; const logger = createLogger("router:integration-settings"); @@ -492,37 +493,46 @@ export const integrationSettingsRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SE { method: "GET", pattern: parsePattern("/integration-settings/:id"), + authorization: requirePermission("integrations.read", { + actorlessGrants: [{ service: "slack-bot", pathParams: { id: "slack" } }], + }), handler: handleGetIntegrationSettings, }, { method: "PUT", pattern: parsePattern("/integration-settings/:id"), + authorization: requirePermission("integrations.manage"), handler: handleSetIntegrationSettings, }, { method: "DELETE", pattern: parsePattern("/integration-settings/:id"), + authorization: requirePermission("integrations.manage"), handler: handleDeleteIntegrationSettings, }, // Integration settings — per-repo { method: "GET", pattern: parsePattern("/integration-settings/:id/repos"), + authorization: requirePermission("integrations.read"), handler: handleListRepoSettings, }, { method: "GET", pattern: parsePattern("/integration-settings/:id/repos/:owner/:name"), + authorization: requirePermission("integrations.read"), handler: handleGetRepoSettings, }, { method: "PUT", pattern: parsePattern("/integration-settings/:id/repos/:owner/:name"), + authorization: requirePermission("repositories.settings.manage"), handler: handleSetRepoSettings, }, { method: "DELETE", pattern: parsePattern("/integration-settings/:id/repos/:owner/:name"), + authorization: requirePermission("repositories.settings.manage"), handler: handleDeleteRepoSettings, }, // Integration settings — per-environment (design §13.5; sandbox and @@ -530,22 +540,31 @@ export const integrationSettingsRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SE { method: "GET", pattern: parsePattern("/integration-settings/:id/environments/:environmentId"), + authorization: requirePermission("integrations.read"), handler: handleGetEnvironmentSettings, }, { method: "PUT", pattern: parsePattern("/integration-settings/:id/environments/:environmentId"), + authorization: requirePermission("environments.settings.manage"), handler: handleSetEnvironmentSettings, }, { method: "DELETE", pattern: parsePattern("/integration-settings/:id/environments/:environmentId"), + authorization: requirePermission("environments.settings.manage"), handler: handleDeleteEnvironmentSettings, }, // Resolved config — used by bots at runtime { method: "GET", pattern: parsePattern("/integration-settings/:id/resolved/:owner/:name"), + authorization: requirePermission("integrations.read", { + actorlessGrants: [ + { service: "github-bot", pathParams: { id: "github" } }, + { service: "linear-bot", pathParams: { id: "linear" } }, + ], + }), handler: handleGetResolvedConfig, }, ]); diff --git a/packages/control-plane/src/routes/keyboard-shortcuts.ts b/packages/control-plane/src/routes/keyboard-shortcuts.ts index 14ab950531..9bf4a22b6f 100644 --- a/packages/control-plane/src/routes/keyboard-shortcuts.ts +++ b/packages/control-plane/src/routes/keyboard-shortcuts.ts @@ -2,30 +2,23 @@ import { updateKeyboardShortcutPreferencesSchema } from "@open-inspect/shared/ty import { KeyboardShortcutPreferencesStore } from "../db/keyboard-shortcut-preferences"; import type { Env } from "../types"; import { + ACTIVE_SELF, defineRoutes, error, json, parsePattern, - SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, - type RequestContext, + SCM_AGNOSTIC_HUMAN_USER_ROUTE, type Route, + type UserRouteContext, } from "./shared"; -function canonicalUserId(ctx: RequestContext): string | null { - if (ctx.principal?.kind === "user") return ctx.principal.userId; - if (ctx.principal?.kind === "service") return ctx.principal.actor?.canonicalUserId ?? null; - return null; -} - async function getPreferences( _request: Request, _env: Env, _match: RegExpMatchArray, - ctx: RequestContext + ctx: UserRouteContext ): Promise { - const userId = canonicalUserId(ctx); - if (!userId) return error("Canonical user required", 403); - const shortcuts = await new KeyboardShortcutPreferencesStore(ctx.db).get(userId); + const shortcuts = await new KeyboardShortcutPreferencesStore(ctx.db).get(ctx.principal.userId); return json({ shortcuts }); } @@ -33,10 +26,8 @@ async function updatePreferences( request: Request, _env: Env, _match: RegExpMatchArray, - ctx: RequestContext + ctx: UserRouteContext ): Promise { - const userId = canonicalUserId(ctx); - if (!userId) return error("Canonical user required", 403); let body: unknown; try { body = await request.json(); @@ -46,13 +37,23 @@ async function updatePreferences( const parsed = updateKeyboardShortcutPreferencesSchema.safeParse(body); if (!parsed.success) return error("Invalid keyboard shortcuts", 400); const shortcuts = await new KeyboardShortcutPreferencesStore(ctx.db).set( - userId, + ctx.principal.userId, parsed.data.shortcuts ); return json({ shortcuts }); } -export const keyboardShortcutRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, [ - { method: "GET", pattern: parsePattern("/keyboard-shortcuts"), handler: getPreferences }, - { method: "PUT", pattern: parsePattern("/keyboard-shortcuts"), handler: updatePreferences }, +export const keyboardShortcutRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_HUMAN_USER_ROUTE, [ + { + method: "GET", + pattern: parsePattern("/keyboard-shortcuts"), + authorization: ACTIVE_SELF, + handler: getPreferences, + }, + { + method: "PUT", + pattern: parsePattern("/keyboard-shortcuts"), + authorization: ACTIVE_SELF, + handler: updatePreferences, + }, ]); diff --git a/packages/control-plane/src/routes/mcp-servers.ts b/packages/control-plane/src/routes/mcp-servers.ts index 3b6a2ec9a4..311ac3ab53 100644 --- a/packages/control-plane/src/routes/mcp-servers.ts +++ b/packages/control-plane/src/routes/mcp-servers.ts @@ -19,6 +19,7 @@ import { json, error, parseJsonBody, + requirePermission, } from "./shared"; const logger = createLogger("router:mcp-servers"); @@ -167,26 +168,31 @@ export const mcpServerRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ROUT { method: "GET", pattern: parsePattern("/mcp-servers"), + authorization: requirePermission("mcp_servers.read"), handler: handleListMcpServers, }, { method: "POST", pattern: parsePattern("/mcp-servers"), + authorization: requirePermission("mcp_servers.manage"), handler: handleCreateMcpServer, }, { method: "GET", pattern: parsePattern("/mcp-servers/:id"), + authorization: requirePermission("mcp_servers.read"), handler: handleGetMcpServer, }, { method: "PUT", pattern: parsePattern("/mcp-servers/:id"), + authorization: requirePermission("mcp_servers.manage"), handler: handleUpdateMcpServer, }, { method: "DELETE", pattern: parsePattern("/mcp-servers/:id"), + authorization: requirePermission("mcp_servers.manage"), handler: handleDeleteMcpServer, }, ]); diff --git a/packages/control-plane/src/routes/model-preferences.ts b/packages/control-plane/src/routes/model-preferences.ts index 3268b8c8ec..cfcfe38fa9 100644 --- a/packages/control-plane/src/routes/model-preferences.ts +++ b/packages/control-plane/src/routes/model-preferences.ts @@ -15,6 +15,8 @@ import { json, error, parseJsonBody, + activeGlobal, + requirePermission, } from "./shared"; const logger = createLogger("router:model-preferences"); @@ -109,11 +111,15 @@ export const modelPreferencesRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVI { method: "GET", pattern: parsePattern("/model-preferences"), + authorization: activeGlobal({ + actorlessGrants: [{ service: "slack-bot" }], + }), handler: handleGetModelPreferences, }, { method: "PUT", pattern: parsePattern("/model-preferences"), + authorization: requirePermission("models.preferences.manage"), handler: handleSetModelPreferences, }, ]); diff --git a/packages/control-plane/src/routes/model-provider-accounts.ts b/packages/control-plane/src/routes/model-provider-accounts.ts index 5a1725ee84..f854c2344e 100644 --- a/packages/control-plane/src/routes/model-provider-accounts.ts +++ b/packages/control-plane/src/routes/model-provider-accounts.ts @@ -56,6 +56,8 @@ import { type Route, type SandboxRouteContext, type UserRouteContext, + NO_AUTHORIZATION, + requirePermission, } from "./shared"; const PRIVATE_NO_STORE = "private, no-store" as const; @@ -182,6 +184,9 @@ function managementRoute( method, pattern: parsePattern(path), cacheControl: PRIVATE_NO_STORE, + authorization: requirePermission( + method === "GET" ? "provider_accounts.read" : "provider_accounts.manage" + ), handler, }); } @@ -481,6 +486,7 @@ export const modelProviderAccountRoutes: Route[] = [ method: "POST", pattern: parsePattern("/sessions/:id/provider-auth/:provider/access-token"), cacheControl: NO_STORE, + authorization: NO_AUTHORIZATION, handler: handleProviderAccess, }), ]; diff --git a/packages/control-plane/src/routes/rbac.ts b/packages/control-plane/src/routes/rbac.ts new file mode 100644 index 0000000000..01ed454476 --- /dev/null +++ b/packages/control-plane/src/routes/rbac.ts @@ -0,0 +1,114 @@ +import { AuthorizationError, AuthorizationService } from "../authorization/service"; +import type { Env } from "../types"; +import type { Route } from "./shared"; +import { + AUTHENTICATED_USER, + SCM_AGNOSTIC_HUMAN_USER_ROUTE, + defineRoutes, + error, + json, + requirePermission, + type UserRouteContext, +} from "./shared"; + +function rbacErrorResponse(cause: unknown): Response { + if (cause instanceof AuthorizationError) { + return json( + { + error: "Forbidden", + code: cause.code, + ...(cause.permission ? { permission: cause.permission } : {}), + }, + cause.status + ); + } + return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); +} + +async function handleGetCurrentAuthorization( + _request: Request, + _env: Env, + _match: RegExpMatchArray, + ctx: UserRouteContext +): Promise { + const service = new AuthorizationService(ctx.db); + try { + return json(await service.getEffectiveAuthorization(ctx.principal.userId)); + } catch (cause) { + return rbacErrorResponse(cause); + } +} + +async function handleListRoles( + _request: Request, + _env: Env, + _match: RegExpMatchArray, + ctx: UserRouteContext +): Promise { + const service = new AuthorizationService(ctx.db); + try { + return json(await service.listRoles()); + } catch (cause) { + return rbacErrorResponse(cause); + } +} + +async function handleGetRole( + _request: Request, + _env: Env, + match: RegExpMatchArray, + ctx: UserRouteContext +): Promise { + const service = new AuthorizationService(ctx.db); + try { + const role = await service.getRole(decodeURIComponent(match.groups!.id)); + return role ? json(role) : error("Role not found", 404); + } catch (cause) { + return rbacErrorResponse(cause); + } +} + +async function handleListMembers( + _request: Request, + _env: Env, + _match: RegExpMatchArray, + ctx: UserRouteContext +): Promise { + const service = new AuthorizationService(ctx.db); + try { + return json(await service.listMembers()); + } catch (cause) { + return rbacErrorResponse(cause); + } +} + +export const rbacRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_HUMAN_USER_ROUTE, [ + { + method: "GET", + pattern: /^\/me\/authorization$/, + authorization: AUTHENTICATED_USER, + cacheControl: "private, no-store", + handler: handleGetCurrentAuthorization, + }, + { + method: "GET", + pattern: /^\/roles$/, + authorization: requirePermission("workspace.roles.read"), + cacheControl: "private, no-store", + handler: handleListRoles, + }, + { + method: "GET", + pattern: /^\/roles\/(?[^/]+)$/, + authorization: requirePermission("workspace.roles.read"), + cacheControl: "private, no-store", + handler: handleGetRole, + }, + { + method: "GET", + pattern: /^\/members$/, + authorization: requirePermission("workspace.members.read"), + cacheControl: "private, no-store", + handler: handleListMembers, + }, +]); diff --git a/packages/control-plane/src/routes/repos.ts b/packages/control-plane/src/routes/repos.ts index b5fc4ce606..b936ad41e2 100644 --- a/packages/control-plane/src/routes/repos.ts +++ b/packages/control-plane/src/routes/repos.ts @@ -24,6 +24,7 @@ import { error, extractRepoParams, createRouteSourceControlProvider, + requirePermission, } from "./shared"; const logger = createLogger("router:repos"); @@ -329,21 +330,29 @@ export const reposRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ROUTE, [ { method: "GET", pattern: parsePattern("/repos"), + authorization: requirePermission("repositories.read", { + actorlessGrants: [{ service: "slack-bot" }, { service: "linear-bot" }], + }), handler: handleListRepos, }, { method: "PUT", pattern: parsePattern("/repos/:owner/:name/metadata"), + authorization: requirePermission("repositories.settings.manage"), handler: handleUpdateRepoMetadata, }, { method: "GET", pattern: parsePattern("/repos/:owner/:name/metadata"), + authorization: requirePermission("repositories.read", { + actorlessGrants: [{ service: "github-bot" }], + }), handler: handleGetRepoMetadata, }, { method: "GET", pattern: parsePattern("/repos/:owner/:name/branches"), + authorization: requirePermission("repositories.read"), handler: handleListBranches, }, ]); diff --git a/packages/control-plane/src/routes/scm-settings.ts b/packages/control-plane/src/routes/scm-settings.ts index 98e6fd2cf2..df5c3476e2 100644 --- a/packages/control-plane/src/routes/scm-settings.ts +++ b/packages/control-plane/src/routes/scm-settings.ts @@ -25,6 +25,7 @@ import { error, parseJsonBody, extractRepoParams, + requirePermission, } from "./shared"; const logger = createLogger("router:scm-settings"); @@ -222,18 +223,40 @@ async function handleDeleteRepoSettings( } export const scmSettingsRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, [ - { method: "GET", pattern: parsePattern("/scm-settings"), handler: handleGetGlobal }, - { method: "PUT", pattern: parsePattern("/scm-settings"), handler: handleSetGlobal }, - { method: "DELETE", pattern: parsePattern("/scm-settings"), handler: handleDeleteGlobal }, - { method: "GET", pattern: parsePattern("/scm-settings/repos"), handler: handleListRepoSettings }, + { + method: "GET", + pattern: parsePattern("/scm-settings"), + authorization: requirePermission("integrations.read"), + handler: handleGetGlobal, + }, + { + method: "PUT", + pattern: parsePattern("/scm-settings"), + authorization: requirePermission("scm_settings.manage"), + handler: handleSetGlobal, + }, + { + method: "DELETE", + pattern: parsePattern("/scm-settings"), + authorization: requirePermission("scm_settings.manage"), + handler: handleDeleteGlobal, + }, + { + method: "GET", + pattern: parsePattern("/scm-settings/repos"), + authorization: requirePermission("integrations.read"), + handler: handleListRepoSettings, + }, { method: "PUT", pattern: parsePattern("/scm-settings/repos/:owner/:name"), + authorization: requirePermission("scm_settings.manage"), handler: handleSetRepoSettings, }, { method: "DELETE", pattern: parsePattern("/scm-settings/repos/:owner/:name"), + authorization: requirePermission("scm_settings.manage"), handler: handleDeleteRepoSettings, }, ]); diff --git a/packages/control-plane/src/routes/secrets.ts b/packages/control-plane/src/routes/secrets.ts index 25f1fc3ff3..b727a9659e 100644 --- a/packages/control-plane/src/routes/secrets.ts +++ b/packages/control-plane/src/routes/secrets.ts @@ -18,6 +18,7 @@ import { parseJsonBody, extractRepoParams, resolveRepoOrError, + requirePermission, } from "./shared"; import { secretsRequestBodySchema } from "./secret-request-schemas"; @@ -380,31 +381,37 @@ export const secretsRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ROUTE, { method: "PUT", pattern: parsePattern("/repos/:owner/:name/secrets"), + authorization: requirePermission("repositories.secrets.manage"), handler: handleSetRepoSecrets, }, { method: "GET", pattern: parsePattern("/repos/:owner/:name/secrets"), + authorization: requirePermission("repositories.secrets.manage"), handler: handleListRepoSecrets, }, { method: "DELETE", pattern: parsePattern("/repos/:owner/:name/secrets/:key"), + authorization: requirePermission("repositories.secrets.manage"), handler: handleDeleteRepoSecret, }, { method: "PUT", pattern: parsePattern("/secrets"), + authorization: requirePermission("global_secrets.manage"), handler: handleSetGlobalSecrets, }, { method: "GET", pattern: parsePattern("/secrets"), + authorization: requirePermission("global_secrets.manage"), handler: handleListGlobalSecrets, }, { method: "DELETE", pattern: parsePattern("/secrets/:key"), + authorization: requirePermission("global_secrets.manage"), handler: handleDeleteGlobalSecret, }, ]); diff --git a/packages/control-plane/src/routes/session-attachments.ts b/packages/control-plane/src/routes/session-attachments.ts index 519cbacc36..52f1b7e3d1 100644 --- a/packages/control-plane/src/routes/session-attachments.ts +++ b/packages/control-plane/src/routes/session-attachments.ts @@ -51,6 +51,7 @@ import { GITHUB_USER_OR_SERVICE_ROUTE, json, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -243,6 +244,7 @@ export const sessionAttachmentRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/attachments"), + authorization: requirePermission("sessions.collaborate"), handler: handleAttachmentPost, }) ), @@ -251,6 +253,7 @@ export const sessionAttachmentRoutes: Route[] = [ sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/attachments/:attachmentId"), + authorization: requirePermission("sessions.read"), handler: handleAttachmentGet, }) ), diff --git a/packages/control-plane/src/routes/session-child-spawn.ts b/packages/control-plane/src/routes/session-child-spawn.ts index 9d077e9af8..ce0541ebf0 100644 --- a/packages/control-plane/src/routes/session-child-spawn.ts +++ b/packages/control-plane/src/routes/session-child-spawn.ts @@ -33,6 +33,8 @@ import { GITHUB_SANDBOX_FALLBACK_ROUTE, json, parsePattern, + permissionRequirement, + requireAll, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -346,6 +348,10 @@ export const sessionChildSpawnRoutes: Route[] = defineRoutes(GITHUB_SANDBOX_FALL sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/children"), + authorization: requireAll( + permissionRequirement("sessions.create"), + permissionRequirement("sessions.collaborate") + ), handler: handleSpawnChild, }), ]); diff --git a/packages/control-plane/src/routes/session-children.ts b/packages/control-plane/src/routes/session-children.ts index ee1aa2f228..1cfcf250b5 100644 --- a/packages/control-plane/src/routes/session-children.ts +++ b/packages/control-plane/src/routes/session-children.ts @@ -16,7 +16,9 @@ import { error, GITHUB_SANDBOX_FALLBACK_ROUTE, json, + NO_AUTHORIZATION, parsePattern, + requirePermission, SCM_AGNOSTIC_SANDBOX_ROUTE, type RequestContext, type Route, @@ -263,6 +265,7 @@ export const sessionChildRoutes: Route[] = [ defineRoute(GITHUB_SANDBOX_FALLBACK_ROUTE, { method: "GET", pattern: parsePattern("/sessions/:id/children"), + authorization: requirePermission("sessions.read"), handler: handleListChildren, }), defineRoute( @@ -270,6 +273,7 @@ export const sessionChildRoutes: Route[] = [ sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/children/:childId"), + authorization: requirePermission("sessions.read"), handler: handleGetChild, }) ), @@ -278,6 +282,7 @@ export const sessionChildRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/children/:childId/cancel"), + authorization: requirePermission("sessions.lifecycle"), handler: handleCancelChild, }) ), @@ -286,6 +291,7 @@ export const sessionChildRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/children/:childId/prompt"), + authorization: NO_AUTHORIZATION, handler: handlePromptChild, }) ), diff --git a/packages/control-plane/src/routes/session-create.ts b/packages/control-plane/src/routes/session-create.ts index 7c76ab63dc..a9adc0f757 100644 --- a/packages/control-plane/src/routes/session-create.ts +++ b/packages/control-plane/src/routes/session-create.ts @@ -30,6 +30,7 @@ import { type Route, GITHUB_USER_OR_SERVICE_ROUTE, defineRoutes, + requirePermission, } from "./shared"; const logger = createLogger("router:session-create"); @@ -65,6 +66,26 @@ async function handleCreateSession( throw e; } + if (ctx.principal?.kind === "user" || ctx.principal?.kind === "service") { + const authorization = ctx.authorization; + if (!authorization) return json({ error: "Authorization unavailable" }, 503); + if (body.environmentId && !authorization.permissions.includes("environments.use")) { + return json( + { error: "Forbidden", code: "permission_required", permission: "environments.use" }, + 403 + ); + } + if ( + (repositoryContext || body.repositories) && + !authorization.permissions.includes("repositories.use") + ) { + return json( + { error: "Forbidden", code: "permission_required", permission: "repositories.use" }, + 403 + ); + } + } + // Validate branch names if provided (defense in depth) if (body.branch && !BRANCH_NAME_PATTERN.test(body.branch)) { return error("Invalid branch name"); @@ -266,6 +287,7 @@ export const sessionCreateRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ { method: "POST", pattern: parsePattern("/sessions"), + authorization: requirePermission("sessions.create"), handler: handleCreateSession, }, ]); diff --git a/packages/control-plane/src/routes/session-diffs.ts b/packages/control-plane/src/routes/session-diffs.ts index 9c07780f56..3a1fa4603a 100644 --- a/packages/control-plane/src/routes/session-diffs.ts +++ b/packages/control-plane/src/routes/session-diffs.ts @@ -11,6 +11,7 @@ import { error, SCM_AGNOSTIC_SANDBOX_FALLBACK_ROUTE, SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, + requirePermission, parsePattern, type Route, } from "./shared"; @@ -193,6 +194,7 @@ export const sessionDiffRoutes: Route[] = [ sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/diff"), + authorization: requirePermission("sessions.read"), handler: handleDiffState, }) ), @@ -201,6 +203,7 @@ export const sessionDiffRoutes: Route[] = [ sessionRoute({ method: "PUT", pattern: parsePattern("/sessions/:id/diff"), + authorization: requirePermission("sessions.collaborate"), handler: handleDiffUpload, }) ), @@ -209,6 +212,7 @@ export const sessionDiffRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/diff/failure"), + authorization: requirePermission("sessions.collaborate"), handler: handleDiffFailure, }) ), @@ -217,6 +221,7 @@ export const sessionDiffRoutes: Route[] = [ sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/diff/:revisionId/files/:fileId"), + authorization: requirePermission("sessions.read"), handler: handleDiffFile, }) ), @@ -225,6 +230,7 @@ export const sessionDiffRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/diff/retry"), + authorization: requirePermission("sessions.lifecycle"), handler: handleDiffRetry, }) ), diff --git a/packages/control-plane/src/routes/session-index.test.ts b/packages/control-plane/src/routes/session-index.test.ts index c8c23da545..5922306b00 100644 --- a/packages/control-plane/src/routes/session-index.test.ts +++ b/packages/control-plane/src/routes/session-index.test.ts @@ -9,7 +9,6 @@ import { TEST_BACKGROUND_TASK_CONTEXT } from "../router.test-support"; const mockSessionIndexStore = { list: vi.fn(), delete: vi.fn(), - getVisibleForUser: vi.fn(), updateReadState: vi.fn(), }; @@ -20,10 +19,21 @@ vi.mock("../db/session-index", () => ({ })); function createCtx(principal?: Principal): RequestContext { + const statement = { + bind: vi.fn(() => statement), + first: vi.fn(async () => ({ + user_id: "user-1", + suspended_at: null, + role_id: "role_builtin_owner", + role_key: "owner", + role_name: "Owner", + })), + all: vi.fn(async () => ({ results: [] })), + }; return { trace_id: "trace-1", request_id: "req-1", - db: {} as SqlDatabase, + db: { prepare: vi.fn(() => statement) } as unknown as SqlDatabase, executionCtx: TEST_BACKGROUND_TASK_CONTEXT, metrics: { d1Queries: [], @@ -32,6 +42,16 @@ function createCtx(principal?: Principal): RequestContext { summarize: () => ({}), }, principal, + ...(principal?.kind === "user" + ? { + authorization: { + userId: principal.userId, + suspendedAt: null, + role: { id: "role_builtin_owner", key: "owner" as const, name: "Owner" }, + permissions: ["sessions.read", "sessions.delete", "sessions.lifecycle"] as const, + }, + } + : {}), }; } @@ -84,7 +104,6 @@ describe("session index routes", () => { sessions: [], hasMore: false, }); - mockSessionIndexStore.getVisibleForUser.mockResolvedValue({ id: "session-1" }); mockSessionIndexStore.updateReadState.mockResolvedValue({ sessionId: "session-1", outcome: "marked_read", @@ -293,18 +312,6 @@ describe("session index routes", () => { expect(mockSessionIndexStore.updateReadState).not.toHaveBeenCalled(); }); - it("does not expose invisible sessions through read-state mutations", async () => { - mockSessionIndexStore.getVisibleForUser.mockResolvedValue(null); - - const response = await patchReadState(JSON.stringify({ action: "mark_latest_message_read" }), { - kind: "user", - userId: "user-1", - }); - - expect(response.status).toBe(404); - expect(mockSessionIndexStore.updateReadState).not.toHaveBeenCalled(); - }); - it.each([ [ JSON.stringify({ action: "mark_latest_message_read" }), @@ -325,7 +332,6 @@ describe("session index routes", () => { expect(response.status).toBe(200); expect(response.headers.get("Cache-Control")).toBe("private, no-store"); - expect(mockSessionIndexStore.getVisibleForUser).toHaveBeenCalledWith("session-1", "user-1"); expect(mockSessionIndexStore.updateReadState).toHaveBeenCalledWith( "user-1", "session-1", diff --git a/packages/control-plane/src/routes/session-index.ts b/packages/control-plane/src/routes/session-index.ts index 651e3ed21f..e12522ce87 100644 --- a/packages/control-plane/src/routes/session-index.ts +++ b/packages/control-plane/src/routes/session-index.ts @@ -19,6 +19,7 @@ import { parseJsonBody, parsePattern, SCM_AGNOSTIC_HUMAN_USER_ROUTE, + requirePermission, type RequestContext, type Route, type UserRouteContext, @@ -32,18 +33,13 @@ const SESSION_INBOX_LIMIT = 20; function parseCreatedByFilters( values: readonly string[], - principal: RequestContext["principal"] + currentUserId: string | null ): string[] | Response { const userIds: string[] = []; const seen = new Set(); for (const value of values) { - const userId = - value === SESSION_LIST_CURRENT_USER - ? principal?.kind === "user" - ? principal.userId - : null - : value; + const userId = value === SESSION_LIST_CURRENT_USER ? currentUserId : value; if (!isCanonicalUserId(userId)) { return error("Invalid createdBy", 400); @@ -70,7 +66,13 @@ async function handleListSessions( const { createdBy, status, excludeStatus, excludeAutomationLineage, limit, offset } = parsedQuery.data; - const createdByUserIds = parseCreatedByFilters(createdBy, ctx.principal); + const viewerUserId = + ctx.principal?.kind === "user" + ? ctx.principal.userId + : ctx.principal?.kind === "service" + ? (ctx.principal.actor?.canonicalUserId ?? ctx.authorization?.userId) + : undefined; + const createdByUserIds = parseCreatedByFilters(createdBy, viewerUserId ?? null); if (createdByUserIds instanceof Response) { return createdByUserIds; @@ -78,7 +80,6 @@ async function handleListSessions( const store = new SessionIndexStore(ctx.db); const listStartedAt = Date.now(); - const viewerUserId = ctx.principal?.kind === "user" ? ctx.principal.userId : undefined; const result = await store.list({ status, excludeStatus, @@ -86,7 +87,7 @@ async function handleListSessions( createdByUserIds, limit, offset, - viewerUserId, + ...(viewerUserId ? { viewerUserId } : {}), }); if (viewerUserId) { log.info("session_read_state.decorated", { @@ -203,9 +204,6 @@ async function handlePatchReadState( const body = parsedBody.data; const store = new SessionIndexStore(ctx.db); - const visibleSession = await store.getVisibleForUser(sessionId, ctx.principal.userId); - if (!visibleSession) return error("Session not found", 404); - const result = await store.updateReadState(ctx.principal.userId, sessionId, body); if (!result) return error("Session not found", 404); @@ -242,21 +240,25 @@ export const sessionIndexRoutes: Route[] = [ defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "GET", pattern: parsePattern("/sessions"), + authorization: requirePermission("sessions.read"), handler: handleListSessions, }), defineRoute(SCM_AGNOSTIC_HUMAN_USER_ROUTE, { method: "GET", pattern: parsePattern("/sessions/inbox"), + authorization: requirePermission("sessions.read", { service: "deny" }), handler: handleListSessionInbox, }), defineRoute(SCM_AGNOSTIC_HUMAN_USER_ROUTE, { method: "PATCH", pattern: parsePattern("/sessions/:id/read-state"), + authorization: requirePermission("sessions.read"), handler: handlePatchReadState, }), defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "DELETE", pattern: parsePattern("/sessions/:id"), + authorization: requirePermission("sessions.delete"), handler: handleDeleteSession, }), ]; diff --git a/packages/control-plane/src/routes/session-media-stream.ts b/packages/control-plane/src/routes/session-media-stream.ts index 0664e4140d..6204d75b58 100644 --- a/packages/control-plane/src/routes/session-media-stream.ts +++ b/packages/control-plane/src/routes/session-media-stream.ts @@ -15,6 +15,7 @@ import { error, GITHUB_USER_OR_SERVICE_ROUTE, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -145,6 +146,9 @@ export const sessionMediaStreamRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SER sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/media/:artifactId"), + authorization: requirePermission("sessions.read", { + actorlessGrants: [{ service: "slack-bot" }], + }), handler: handleMediaGet, }), ]); diff --git a/packages/control-plane/src/routes/session-media-upload.ts b/packages/control-plane/src/routes/session-media-upload.ts index 44b16acd64..77164f10fd 100644 --- a/packages/control-plane/src/routes/session-media-upload.ts +++ b/packages/control-plane/src/routes/session-media-upload.ts @@ -27,6 +27,7 @@ import { GITHUB_SANDBOX_FALLBACK_ROUTE, json, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -250,6 +251,7 @@ export const sessionMediaUploadRoutes: Route[] = defineRoutes(GITHUB_SANDBOX_FAL sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/media"), + authorization: requirePermission("sessions.collaborate"), handler: handleMediaUpload, }), ]); diff --git a/packages/control-plane/src/routes/session-prompt.ts b/packages/control-plane/src/routes/session-prompt.ts index 39dd03a730..5916dfeea0 100644 --- a/packages/control-plane/src/routes/session-prompt.ts +++ b/packages/control-plane/src/routes/session-prompt.ts @@ -26,6 +26,7 @@ import { error, GITHUB_USER_OR_SERVICE_ROUTE, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -181,6 +182,7 @@ export const sessionPromptRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE_ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/prompt"), + authorization: requirePermission("sessions.collaborate"), handler: handleSessionPrompt, }), ]); diff --git a/packages/control-plane/src/routes/session-pull-requests.ts b/packages/control-plane/src/routes/session-pull-requests.ts index df6a8e4d52..dd56af8c3b 100644 --- a/packages/control-plane/src/routes/session-pull-requests.ts +++ b/packages/control-plane/src/routes/session-pull-requests.ts @@ -5,6 +5,7 @@ import { error, GITHUB_USER_OR_SERVICE_ROUTE, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -33,6 +34,7 @@ export const sessionPullRequestRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SER sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/pull-requests/refresh"), + authorization: requirePermission("sessions.lifecycle"), handler: handleRefreshPullRequests, }), ]); diff --git a/packages/control-plane/src/routes/session-runtime-proxy.ts b/packages/control-plane/src/routes/session-runtime-proxy.ts index 8ccfe5c869..01144fb8b8 100644 --- a/packages/control-plane/src/routes/session-runtime-proxy.ts +++ b/packages/control-plane/src/routes/session-runtime-proxy.ts @@ -15,8 +15,10 @@ import { error, GITHUB_SANDBOX_FALLBACK_ROUTE, GITHUB_USER_OR_SERVICE_ROUTE, + NO_AUTHORIZATION, parseJsonBody, parsePattern, + requirePermission, SCM_AGNOSTIC_SANDBOX_FALLBACK_ROUTE, SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, SCM_AGNOSTIC_SANDBOX_ROUTE, @@ -24,6 +26,7 @@ import { SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, SCM_CREDENTIALS_ROUTE, type Route, + type RouteAuthorization, type RoutePolicy, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -44,6 +47,7 @@ type SimpleProxyRouteConfig = { method: string; routePath: string; internalPath: SessionInternalPath; + authorization: RouteAuthorization; runtimeMethod?: string; forwardSearch?: boolean; notFoundMessage?: string; @@ -64,6 +68,7 @@ function simpleProxyRoute(config: SimpleProxyRouteConfig): Route { sessionRoute({ method: config.method, pattern: parsePattern(config.routePath), + authorization: config.authorization, handler: async (request, _env, match, ctx) => { const sessionId = getSessionId(match); if (sessionId instanceof Response) return sessionId; @@ -95,6 +100,7 @@ function legacyTokenRefreshRoute( sessionRoute({ method: "POST", pattern: parsePattern(routePath), + authorization: NO_AUTHORIZATION, handler: async (_request, _env, match, ctx) => { const sessionId = getSessionId(match); if (sessionId instanceof Response) return sessionId; @@ -252,12 +258,7 @@ async function handleCreatePR( }); } -/** - * Read a lifecycle-route body (title/archive/unarchive) under identity - * enforcement. Lifecycle routes accept bodyless requests — a parse failure - * just yields no fields. The DO participant check runs against the verified - * identity, never a caller-asserted one. - */ +/** Read a lifecycle body under verified identity enforcement. */ async function readEnforcedLifecycleBody( request: Request, ctx: SessionRouteContext @@ -286,6 +287,7 @@ function lifecycleProxyRoute( sessionRoute({ method, pattern: parsePattern(routePath), + authorization: requirePermission("sessions.lifecycle"), handler: async (request, _env, match, ctx) => { const sessionId = getSessionId(match); if (sessionId instanceof Response) return sessionId; @@ -311,12 +313,14 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "GET", routePath: "/sessions/:id/sandbox-access", internalPath: SessionInternalPaths.sandboxAccess, + authorization: requirePermission("sessions.sandbox_access"), }), simpleProxyRoute({ policy: SCM_AGNOSTIC_HUMAN_USER_ROUTE, method: "GET", routePath: "/sessions/:id", internalPath: SessionInternalPaths.snapshot, + authorization: requirePermission("sessions.read"), notFoundMessage: "Session not found", }), simpleProxyRoute({ @@ -324,6 +328,9 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "POST", routePath: "/sessions/:id/stop", internalPath: SessionInternalPaths.stop, + authorization: requirePermission("sessions.lifecycle", { + actorlessGrants: [{ service: "linear-bot" }], + }), runtimeMethod: "POST", }), defineRoute( @@ -331,6 +338,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/sandbox-error"), + authorization: NO_AUTHORIZATION, handler: handleSandboxError, }) ), @@ -339,6 +347,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "GET", routePath: "/sessions/:id/events", internalPath: SessionInternalPaths.events, + authorization: requirePermission("sessions.read"), forwardSearch: true, }), simpleProxyRoute({ @@ -346,18 +355,21 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "GET", routePath: "/sessions/:id/artifacts", internalPath: SessionInternalPaths.artifacts, + authorization: requirePermission("sessions.read"), }), simpleProxyRoute({ policy: GITHUB_USER_OR_SERVICE_ROUTE, method: "GET", routePath: "/sessions/:id/participants", internalPath: SessionInternalPaths.participants, + authorization: requirePermission("sessions.read"), }), defineRoute( SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, sessionRoute({ method: "GET", pattern: parsePattern("/sessions/:id/participant-profiles"), + authorization: requirePermission("sessions.read"), handler: handleParticipantProfiles, }) ), @@ -366,6 +378,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/participants"), + authorization: requirePermission("sessions.collaborate"), handler: handleAddParticipant, }) ), @@ -374,6 +387,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "GET", routePath: "/sessions/:id/messages", internalPath: SessionInternalPaths.messages, + authorization: requirePermission("sessions.read"), forwardSearch: true, }), defineRoute( @@ -381,6 +395,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/pr"), + authorization: requirePermission("sessions.collaborate"), handler: handleCreatePR, }) ), @@ -399,6 +414,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "POST", routePath: "/sessions/:id/scm-credentials", internalPath: SessionInternalPaths.scmCredentials, + authorization: NO_AUTHORIZATION, runtimeMethod: "POST", }), simpleProxyRoute({ @@ -406,6 +422,7 @@ export const sessionRuntimeProxyRoutes: Route[] = [ method: "GET", routePath: "/sessions/:id/tunnel-urls", internalPath: SessionInternalPaths.tunnelUrls, + authorization: requirePermission("sessions.sandbox_access"), runtimeMethod: "GET", }), lifecycleProxyRoute("PATCH", "/sessions/:id/title", SessionInternalPaths.updateTitle), diff --git a/packages/control-plane/src/routes/session-skills.ts b/packages/control-plane/src/routes/session-skills.ts index 37497ff4e7..c36cfb989e 100644 --- a/packages/control-plane/src/routes/session-skills.ts +++ b/packages/control-plane/src/routes/session-skills.ts @@ -8,6 +8,8 @@ import { error, json, parsePattern, + NO_AUTHORIZATION, + requirePermission, SCM_AGNOSTIC_SANDBOX_ROUTE, SCM_AGNOSTIC_HUMAN_USER_ROUTE, type SandboxRouteContext, @@ -27,9 +29,6 @@ async function handleSessionSkillsView( ): Promise { const id = sessionId(match); if (id instanceof Response) return id; - if (!(await new SessionIndexStore(ctx.db).getVisibleForUser(id, ctx.principal.userId))) { - return error("Session not found", 404); - } const view = await new SessionSkillStore(ctx.db).getSessionSkillsView(id); if (!view) return error("Session skill manifest not found", 404); const response = json(view); @@ -96,11 +95,13 @@ export const sessionSkillRoutes: Route[] = [ defineRoute(SCM_AGNOSTIC_HUMAN_USER_ROUTE, { method: "GET", pattern: parsePattern("/sessions/:id/skills"), + authorization: requirePermission("sessions.read"), handler: handleSessionSkillsView, }), defineRoute(SCM_AGNOSTIC_SANDBOX_ROUTE, { method: "GET", pattern: parsePattern("/sessions/:id/sandbox-skills"), + authorization: NO_AUTHORIZATION, handler: handleSandboxInstallation, }), ]; diff --git a/packages/control-plane/src/routes/session-ws-token.test.ts b/packages/control-plane/src/routes/session-ws-token.test.ts index 4699b48ada..608d5f4718 100644 --- a/packages/control-plane/src/routes/session-ws-token.test.ts +++ b/packages/control-plane/src/routes/session-ws-token.test.ts @@ -3,6 +3,7 @@ import { TEST_BACKGROUND_TASK_CONTEXT } from "../router.test-support"; import { sessionWsTokenRoutes } from "./session-ws-token"; import type { RequestContext, Route } from "./shared"; import type { Env } from "../types"; +import type { SqlDatabase } from "../db/sql-database"; function routeFor(path: string): { route: Route; match: RegExpMatchArray } { const route = sessionWsTokenRoutes.find((candidate) => candidate.pattern.test(path)); @@ -12,13 +13,32 @@ function routeFor(path: string): { route: Route; match: RegExpMatchArray } { return { route, match }; } -function createContext(): RequestContext { +function accessDatabase() { + const run = vi.fn(async () => ({ meta: { changes: 1 } })); + const statement = { + bind: vi.fn(() => statement), + run, + }; + return { + db: { prepare: vi.fn(() => statement) } as unknown as SqlDatabase, + statement, + run, + }; +} + +function createContext(db: SqlDatabase = accessDatabase().db): RequestContext { return { request_id: "request-1", trace_id: "trace-1", - db: {} as never, + db, executionCtx: TEST_BACKGROUND_TASK_CONTEXT, principal: { kind: "user", userId: "user-1" }, + authorization: { + userId: "user-1", + suspendedAt: null, + role: { id: "role-1", key: "member", name: "Member" }, + permissions: ["sessions.collaborate"], + }, metrics: { d1Queries: [], spans: {}, @@ -71,6 +91,25 @@ describe("session ws-token route", () => { }); }); + it("forwards a runtime rejection without writing D1", async () => { + const access = accessDatabase(); + const fetch = vi.fn(async () => Response.json({ error: "rejected" }, { status: 409 })); + const { route, match } = routeFor("/sessions/session-1/ws-token"); + + const response = await route.handler( + new Request("https://test.local/sessions/session-1/ws-token", { + method: "POST", + body: JSON.stringify({}), + }), + createEnv(fetch), + match, + createContext(access.db) + ); + + expect(response.status).toBe(409); + expect(access.db.prepare).not.toHaveBeenCalled(); + }); + it("forwards null SCM display fields accepted by the session contract", async () => { const forwarded: Request[] = []; const fetch = vi.fn(async (request: Request) => { diff --git a/packages/control-plane/src/routes/session-ws-token.ts b/packages/control-plane/src/routes/session-ws-token.ts index 4d684b1b76..d1d23bf592 100644 --- a/packages/control-plane/src/routes/session-ws-token.ts +++ b/packages/control-plane/src/routes/session-ws-token.ts @@ -7,6 +7,7 @@ import { GITHUB_USER_OR_SERVICE_ROUTE, parseJsonBody, parsePattern, + requirePermission, type Route, } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; @@ -33,8 +34,10 @@ async function handleSessionWsToken( if (!parsedBody.success) return error("Invalid websocket token body", 400); const body = parsedBody.data; + const authorization = ctx.authorization; + if (!authorization) return error("Authorization unavailable", 503); const userId = enforcement.enforced.participantUserId; - const canonicalUserId = enforcement.enforced.canonicalUserId; + const canonicalUserId = authorization.userId; return ctx.metrics.time("do_fetch", () => ctx.sessionRuntime.fetch(sessionId, SessionInternalPaths.wsToken, { @@ -55,6 +58,7 @@ export const sessionWsTokenRoutes: Route[] = defineRoutes(GITHUB_USER_OR_SERVICE sessionRoute({ method: "POST", pattern: parsePattern("/sessions/:id/ws-token"), + authorization: requirePermission("sessions.collaborate"), handler: handleSessionWsToken, }), ]); diff --git a/packages/control-plane/src/routes/shared.ts b/packages/control-plane/src/routes/shared.ts index cf17736d24..0d095666dc 100644 --- a/packages/control-plane/src/routes/shared.ts +++ b/packages/control-plane/src/routes/shared.ts @@ -11,6 +11,13 @@ import type { Env } from "../types"; import type { Logger } from "../logger"; import type { BackgroundTasks } from "../platform-ports"; import type { BetterAuthRuntime, UserAuthRuntime } from "../auth/user/runtime"; +import type { + EffectiveAuthorization, + PermissionId, + ScopedPermissionStem, +} from "@open-inspect/shared/rbac"; +import type { ServiceName } from "@open-inspect/shared/service-auth"; +import type { AutomationRow } from "../db/automation-store"; import { createSourceControlProviderFromEnv, SourceControlProviderError, @@ -19,9 +26,7 @@ import { type SourceControlProviderName, } from "../source-control"; -/** - * Request context with correlation IDs and per-request metrics. - */ +/** Request-scoped dependencies, identity, and resolved authorization state. */ export type RequestContext = CorrelationContext & { metrics: RequestMetrics; /** @@ -44,18 +49,151 @@ export type RequestContext = CorrelationContext & { principal?: Principal; /** Authentication provenance, separate from the principal being authorized. */ authentication?: AuthenticationContext; + /** Effective human authorization loaded once by the router for this request. */ + authorization?: EffectiveAuthorization; + /** Resource admission populated by the router for automation mutation routes. */ + automationAdmission?: AutomationRouteAdmission; }; -/** - * Route configuration. - */ +/** Automation resource admitted by the router for the current mutation. */ +export interface AutomationRouteAdmission { + automation: AutomationRow; +} + +/** Route matching, authorization, and handler configuration. */ export interface RouteDefinition { method: string; pattern: RegExp; + /** Authorization policy enforced before the handler runs. */ + authorization: RouteAuthorization; cacheControl?: "no-store" | "private, no-store"; handler: (request: Request, env: Env, match: RegExpMatchArray, ctx: Context) => Promise; } +/** One permission or resource-admission requirement for an active user. */ +export type RouteAuthorizationRequirement = + | { kind: "permission"; permission: PermissionId } + | { kind: "scoped-permission"; stem: ScopedPermissionStem } + | { + kind: "automation"; + operation: "manage" | "trigger"; + automationIdParam: string; + }; + +type BotServiceName = Exclude; + +/** Narrow route grant for a trusted service without an acting user. */ +export interface ActorlessServiceGrant { + service: BotServiceName; + pathParams?: Readonly>; +} + +type ServiceAuthorization = + | { kind: "deny" } + | { + kind: "actor"; + actorlessGrants?: readonly ActorlessServiceGrant[]; + }; + +/** Declarative authorization policy enforced by the router. */ +export type RouteAuthorization = + | { kind: "none" } + | { kind: "authenticated" } + | { kind: "active-self" } + | { kind: "active-global"; service: ServiceAuthorization } + | { + kind: "active-user"; + allOf: readonly RouteAuthorizationRequirement[]; + service: ServiceAuthorization; + } + | { + kind: "service"; + services: readonly BotServiceName[]; + actor: "required" | "optional"; + }; + +/** + * Skips router-level permission checks after route authentication. + * + * The route may still require a service signature, a session-bound sandbox token, or credentials + * verified by its handler. Only routes whose authentication policy is `public` are publicly + * accessible. + */ +export const NO_AUTHORIZATION = { kind: "none" } as const satisfies RouteAuthorization; +/** Policy requiring any authenticated principal. */ +export const AUTHENTICATED_USER = { + kind: "authenticated", +} as const satisfies RouteAuthorization; +/** Policy requiring an active user to access their own account resource. */ +export const ACTIVE_SELF = { kind: "active-self" } as const satisfies RouteAuthorization; + +/** Build a global permission requirement for composition with other requirements. */ +export function permissionRequirement(permission: PermissionId): RouteAuthorizationRequirement { + return { kind: "permission", permission }; +} + +/** Require an active user with a global permission, optionally allowing service actors. */ +export function requirePermission( + permission: PermissionId, + options?: { service?: "actor" | "deny"; actorlessGrants?: readonly ActorlessServiceGrant[] } +): RouteAuthorization { + return { + kind: "active-user", + allOf: [permissionRequirement(permission)], + service: + options?.service === "deny" + ? { kind: "deny" } + : { kind: "actor", actorlessGrants: options?.actorlessGrants }, + }; +} + +/** Require an active user with at least one permission under a scoped stem. */ +export function requireScopedPermission( + stem: ScopedPermissionStem, + options?: { service?: "actor" } +): RouteAuthorization { + return { + kind: "active-user", + allOf: [{ kind: "scoped-permission", stem }], + service: options?.service === "actor" ? { kind: "actor" } : { kind: "deny" }, + }; +} + +/** Require admission to manage or trigger the automation identified by a path parameter. */ +export function requireAutomation( + operation: "manage" | "trigger", + automationIdParam = "id" +): RouteAuthorization { + return { + kind: "active-user", + allOf: [{ kind: "automation", operation, automationIdParam }], + service: { kind: "deny" }, + }; +} + +/** Require an active user to satisfy every supplied authorization requirement. */ +export function requireAll(...allOf: readonly RouteAuthorizationRequirement[]): RouteAuthorization { + return { kind: "active-user", allOf, service: { kind: "actor" } }; +} + +/** Require any active user, with optional actorless service grants. */ +export function activeGlobal(options?: { + actorlessGrants?: readonly ActorlessServiceGrant[]; +}): RouteAuthorization { + return { + kind: "active-global", + service: { kind: "actor", actorlessGrants: options?.actorlessGrants }, + }; +} + +/** Restrict a route to one trusted service, with optional actor identity. */ +export function serviceAuthorized( + service: BotServiceName, + actor: "required" | "optional" = "optional" +): RouteAuthorization { + return { kind: "service", services: [service], actor }; +} + type UserPrincipal = Extract; type SandboxPrincipal = Extract; type ServicePrincipal = Extract; diff --git a/packages/control-plane/src/routes/sign-in-providers.ts b/packages/control-plane/src/routes/sign-in-providers.ts index a28828208e..15058e7dd4 100644 --- a/packages/control-plane/src/routes/sign-in-providers.ts +++ b/packages/control-plane/src/routes/sign-in-providers.ts @@ -4,6 +4,7 @@ import { defineRoutes, error, json, + NO_AUTHORIZATION, parsePattern, SCM_AGNOSTIC_WEB_SERVICE_ROUTE, type Route, @@ -39,6 +40,7 @@ export const signInProviderRoutes: Route[] = defineRoutes(SCM_AGNOSTIC_WEB_SERVI { method: "GET", pattern: parsePattern("/internal/auth/sign-in-providers"), + authorization: NO_AUTHORIZATION, handler: handleSignInProviders, }, ]); diff --git a/packages/control-plane/src/routes/skills.ts b/packages/control-plane/src/routes/skills.ts index 942b799feb..84e3c3be3e 100644 --- a/packages/control-plane/src/routes/skills.ts +++ b/packages/control-plane/src/routes/skills.ts @@ -40,6 +40,7 @@ import { SCM_AGNOSTIC_HUMAN_USER_ROUTE, SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, defineRoutes, + requirePermission, } from "./shared"; const log = createLogger("router:skills"); @@ -625,63 +626,103 @@ function profileWriteError(value: unknown): Response { } const skillReadRoutes = defineRoutes(SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE, [ - { method: "GET", pattern: parsePattern("/skills"), handler: handleListSkills }, + { + method: "GET", + pattern: parsePattern("/skills"), + authorization: requirePermission("skills.read"), + handler: handleListSkills, + }, { method: "POST", pattern: parsePattern("/skills/preview"), + authorization: requirePermission("skills.read"), handler: handlePreviewSkill, }, { method: "POST", pattern: parsePattern("/skills/resolve-preview"), + authorization: requirePermission("skills.read"), handler: handleResolvePreview, }, - { method: "GET", pattern: parsePattern("/skills/:id"), handler: handleGetSkill }, + { + method: "GET", + pattern: parsePattern("/skills/:id"), + authorization: requirePermission("skills.read"), + handler: handleGetSkill, + }, ]); const skillAdministrationRoutes = defineRoutes(SCM_AGNOSTIC_HUMAN_USER_ROUTE, [ - { method: "POST", pattern: parsePattern("/skills"), handler: handleCreateSkill }, + { + method: "POST", + pattern: parsePattern("/skills"), + authorization: requirePermission("skills.manage"), + handler: handleCreateSkill, + }, { method: "POST", pattern: parsePattern("/skills/import/preview"), + authorization: requirePermission("skills.manage"), handler: handlePreviewSkillImport, }, - { method: "POST", pattern: parsePattern("/skills/import"), handler: handleImportSkill }, + { + method: "POST", + pattern: parsePattern("/skills/import"), + authorization: requirePermission("skills.manage"), + handler: handleImportSkill, + }, { method: "POST", pattern: parsePattern("/skills/:id/reimport/preview"), + authorization: requirePermission("skills.manage"), handler: handlePreviewSkillReimport, }, { method: "POST", pattern: parsePattern("/skills/:id/reimport"), + authorization: requirePermission("skills.manage"), handler: handleReimportSkill, }, { method: "PATCH", pattern: parsePattern("/skills/:id"), + authorization: requirePermission("skills.manage"), handler: handleSetSkillEnabled, }, { method: "PUT", pattern: parsePattern("/skills/:id"), + authorization: requirePermission("skills.manage"), handler: handleReplaceSkillContentAndAssignments, }, - { method: "DELETE", pattern: parsePattern("/skills/:id"), handler: handleDeleteSkill }, - { method: "GET", pattern: parsePattern("/skill-profiles"), handler: handleListProfiles }, + { + method: "DELETE", + pattern: parsePattern("/skills/:id"), + authorization: requirePermission("skills.manage"), + handler: handleDeleteSkill, + }, + { + method: "GET", + pattern: parsePattern("/skill-profiles"), + authorization: requirePermission("skill_profiles.manage_own"), + handler: handleListProfiles, + }, { method: "POST", pattern: parsePattern("/skill-profiles"), + authorization: requirePermission("skill_profiles.manage_own"), handler: handleCreateProfile, }, { method: "PATCH", pattern: parsePattern("/skill-profiles/:id"), + authorization: requirePermission("skill_profiles.manage_own"), handler: handleUpdateProfile, }, { method: "DELETE", pattern: parsePattern("/skill-profiles/:id"), + authorization: requirePermission("skill_profiles.manage_own"), handler: handleDeleteProfile, }, ]); diff --git a/packages/control-plane/src/webhooks/automation-event.ts b/packages/control-plane/src/webhooks/automation-event.ts index 6d93e46da2..a90b8c6c29 100644 --- a/packages/control-plane/src/webhooks/automation-event.ts +++ b/packages/control-plane/src/webhooks/automation-event.ts @@ -23,6 +23,7 @@ import { GITHUB_USER_OR_SERVICE_ROUTE, json, parsePattern, + serviceAuthorized, } from "../routes/shared"; import type { Env } from "../types"; import { Scheduler } from "../scheduler/scheduler"; @@ -124,6 +125,7 @@ export async function forwardAutomationEventToScheduler( return json({ ok: true, ...result }); } +/** Create an authenticated route for a normalized automation event source. */ export function createAutomationEventRoute(opts: { path: string; source: AutomationEventSource; @@ -157,6 +159,7 @@ export function createAutomationEventRoute(opts: { return defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "POST", pattern: parsePattern(opts.path), + authorization: serviceAuthorized("slack-bot"), handler, }); } diff --git a/packages/control-plane/src/webhooks/automation-webhook.ts b/packages/control-plane/src/webhooks/automation-webhook.ts index b715b69a8d..ebcd1ca6f3 100644 --- a/packages/control-plane/src/webhooks/automation-webhook.ts +++ b/packages/control-plane/src/webhooks/automation-webhook.ts @@ -10,6 +10,7 @@ import { defineRoute, error, json, + NO_AUTHORIZATION, parsePattern, SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, } from "../routes/shared"; @@ -90,5 +91,6 @@ async function handleAutomationWebhook( export const automationWebhookRoute: Route = defineRoute(SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, { method: "POST", pattern: parsePattern("/webhooks/automation/:id"), + authorization: NO_AUTHORIZATION, handler: handleAutomationWebhook, }); diff --git a/packages/control-plane/src/webhooks/github.ts b/packages/control-plane/src/webhooks/github.ts index d2e2c7eef4..48252fef1a 100644 --- a/packages/control-plane/src/webhooks/github.ts +++ b/packages/control-plane/src/webhooks/github.ts @@ -14,7 +14,13 @@ import { SessionInternalPaths } from "../session/contracts"; import { createSessionRuntimeClient } from "../session/runtime-client"; import type { Env } from "../types"; import type { RequestContext, Route } from "../routes/shared"; -import { defineRoute, error, GITHUB_USER_OR_SERVICE_ROUTE, parsePattern } from "../routes/shared"; +import { + defineRoute, + error, + GITHUB_USER_OR_SERVICE_ROUTE, + parsePattern, + serviceAuthorized, +} from "../routes/shared"; import { requireEventPoster } from "../auth/identity-enforcement"; import { forwardAutomationEventToScheduler, @@ -127,5 +133,6 @@ async function handleGitHubAutomationEvent( export const githubAutomationEventRoute: Route = defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { method: "POST", pattern: parsePattern("/internal/github-event"), + authorization: serviceAuthorized("github-bot"), handler: handleGitHubAutomationEvent, }); diff --git a/packages/control-plane/src/webhooks/sentry.ts b/packages/control-plane/src/webhooks/sentry.ts index ebd410341f..484ff1a8d6 100644 --- a/packages/control-plane/src/webhooks/sentry.ts +++ b/packages/control-plane/src/webhooks/sentry.ts @@ -12,6 +12,7 @@ import { defineRoute, error, json, + NO_AUTHORIZATION, parsePattern, SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, } from "../routes/shared"; @@ -122,5 +123,6 @@ async function handleSentryWebhook( export const sentryWebhookRoute: Route = defineRoute(SCM_AGNOSTIC_HANDLER_AUTHENTICATED_ROUTE, { method: "POST", pattern: parsePattern("/webhooks/sentry/:id"), + authorization: NO_AUTHORIZATION, handler: handleSentryWebhook, }); diff --git a/packages/control-plane/test/integration/automations-slack-route.test.ts b/packages/control-plane/test/integration/automations-slack-route.test.ts index 091c4e27fb..88dd08330b 100644 --- a/packages/control-plane/test/integration/automations-slack-route.test.ts +++ b/packages/control-plane/test/integration/automations-slack-route.test.ts @@ -44,13 +44,9 @@ function createBody(overrides: Record) { } async function postAutomation(body: Record): Promise { - // automation-create requires a participant identity: sign as a bot with an - // asserted actor (the userless web service credential is rejected, 403). return serviceFetch("https://test.local/automations", { method: "POST", body: JSON.stringify(body), - service: "slack-bot", - actor: "slack:U0123", }); } diff --git a/packages/control-plane/test/integration/helpers.ts b/packages/control-plane/test/integration/helpers.ts index 32ae6965d1..510c758cbc 100644 --- a/packages/control-plane/test/integration/helpers.ts +++ b/packages/control-plane/test/integration/helpers.ts @@ -2,6 +2,7 @@ import { SELF, env } from "cloudflare:test"; import { runInSessionDO } from "./session-do-access"; import type { SandboxSettings } from "@open-inspect/shared/types/integrations"; import { buildServiceAuthHeaders, type ServiceName } from "@open-inspect/shared/service-auth"; +import { BUILT_IN_ROLE_REGISTRY, type BuiltInRoleKey } from "@open-inspect/shared/rbac"; import type { SandboxStatus } from "@open-inspect/shared/types/sessions"; import type { SessionDO } from "../../src/session/durable-object"; import { hashToken } from "../../src/auth/crypto"; @@ -28,11 +29,22 @@ export function getSetCookies(headers: Headers): string[] { return (headers as Headers & { getSetCookie(): string[] }).getSetCookie(); } +export async function seedActiveUser(userId: string): Promise { + const now = Date.now(); + await env.DB.prepare( + `INSERT INTO users (id, display_name, created_at, updated_at) VALUES (?, ?, ?, ?)` + ) + .bind(userId, "Integration User", now, now) + .run(); +} + const DEFAULT_WAIT_FOR_SANDBOX_STATUS_TIMEOUT_MS = 3000; export const INTEGRATION_WEBSOCKET_TIMEOUT_MS = 2000; const TEST_BROWSER_USER_ID = "11111111111111111111111111111111"; const TEST_BROWSER_ACCOUNT_ID = "test-browser-account"; const TEST_BROWSER_PROVIDER_SUBJECT = "583231"; +type InitialUserRole = Exclude; +const DEFAULT_INITIAL_USER_ROLE = "owner" as const; const TEST_BROWSER_SESSION_ID = "test-browser-session"; const TEST_BROWSER_SESSION_TOKEN = "test-browser-session-token"; const TEST_BROWSER_SESSION_COOKIE = "__Secure-openinspect.session_token"; @@ -69,13 +81,16 @@ async function signCookieValue(value: string, secret: string): Promise { * web request must carry the same compound credential as production. Direct * service-auth tests intentionally build their own bare sig1 requests. */ -async function testBrowserSessionCookie(): Promise { +async function testBrowserSessionCookie(initialRole: InitialUserRole): Promise { const secret = env.BROWSER_AUTH_SECRET; if (!secret) throw new Error("BROWSER_AUTH_SECRET is not configured for integration tests"); const now = new Date(); const expiresAt = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); const applicationTimestamp = now.getTime(); + const existingUser = await env.DB.prepare("SELECT 1 FROM users WHERE id = ?") + .bind(TEST_BROWSER_USER_ID) + .first(); await env.DB.batch([ env.DB.prepare( `INSERT OR IGNORE INTO users @@ -86,7 +101,7 @@ async function testBrowserSessionCookie(): Promise { "Integration Browser User", "browser@test.local", 1, - null, + "browser@test.local", applicationTimestamp, applicationTimestamp ), @@ -121,6 +136,11 @@ async function testBrowserSessionCookie(): Promise { TEST_BROWSER_USER_ID ), ]); + if (initialRole !== "member" && !existingUser) { + await env.DB.prepare(`UPDATE user_role_assignments SET role_id = ? WHERE user_id = ?`) + .bind(BUILT_IN_ROLE_REGISTRY[initialRole].id, TEST_BROWSER_USER_ID) + .run(); + } const signedToken = await signCookieValue(TEST_BROWSER_SESSION_TOKEN, secret); return `${TEST_BROWSER_SESSION_COOKIE}=${signedToken}`; @@ -140,6 +160,7 @@ export async function serviceFetch( headers?: Record; service?: ServiceName; actor?: string; + initialUserRole?: InitialUserRole; } ): Promise { const method = init?.method ?? "GET"; @@ -152,7 +173,10 @@ export async function serviceFetch( body: init?.body, actor: init?.actor, }); - const browserCookie = service === "web" ? await testBrowserSessionCookie() : undefined; + const browserCookie = + service === "web" + ? await testBrowserSessionCookie(init?.initialUserRole ?? DEFAULT_INITIAL_USER_ROLE) + : undefined; return SELF.fetch(url, { method, headers: { diff --git a/packages/control-plane/test/integration/image-builds.test.ts b/packages/control-plane/test/integration/image-builds.test.ts index 85480b084c..ef7d35314e 100644 --- a/packages/control-plane/test/integration/image-builds.test.ts +++ b/packages/control-plane/test/integration/image-builds.test.ts @@ -8,7 +8,6 @@ * deployment, and the SCM-less harness split is the same as PR-4/PR-8. */ -import { buildServiceAuthHeaders } from "@open-inspect/shared/service-auth"; import { describe, it, expect, beforeEach } from "vitest"; import { SELF, env } from "cloudflare:test"; import { ImageBuildStore } from "../../src/db/image-builds"; @@ -27,6 +26,7 @@ import type { DeleteImageInput, ImageBuildAdapter } from "../../src/image-builds import { evaluateImageBuildForSpawn } from "../../src/sandbox/lifecycle/image-selection"; import type { Env } from "../../src/types"; import { cleanD1Tables } from "./cleanup"; +import { serviceFetch } from "./helpers"; import { RUNTIME_VERSION, REPOSITORY_SHAS, @@ -62,22 +62,6 @@ const WIRE_KEYS = [ // only forwards token-shaped bearers to the workflow). const MODAL_BUILD_TOKEN = "ab".repeat(32); -/** Call an internal route with a registered service credential. */ -async function serviceFetch(url: string, init?: { method?: string; body?: string }) { - const method = init?.method ?? "GET"; - const headers = { - ...(await buildServiceAuthHeaders({ - service: "linear-bot", - secret: "test-service-secret-linear-bot", - method, - url, - body: init?.body, - })), - ...(init?.body === undefined ? {} : { "Content-Type": "application/json" }), - }; - return SELF.fetch(url, { method, headers, body: init?.body }); -} - function tokenHeaders(token: string): Record { return { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }; } diff --git a/packages/control-plane/test/integration/service-auth.test.ts b/packages/control-plane/test/integration/service-auth.test.ts index 4a7680eadb..aa299ba17b 100644 --- a/packages/control-plane/test/integration/service-auth.test.ts +++ b/packages/control-plane/test/integration/service-auth.test.ts @@ -46,7 +46,7 @@ async function signedFetch(p: { describe("sig1 service-credential authentication", () => { beforeEach(cleanD1Tables); - it("accepts a signed GET from every non-web service", async () => { + it("rejects actorless service requests on broad routes", async () => { for (const service of Object.keys(SERVICE_SECRET).filter( (candidate): candidate is Exclude => candidate !== "web" )) { @@ -55,12 +55,81 @@ describe("sig1 service-credential authentication", () => { method: "GET", url: "https://test.local/sessions", }); - expect(response.status, service).toBe(200); - const body = await response.json<{ sessions: unknown[] }>(); - expect(body.sessions).toEqual([]); + expect(response.status, service).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); } }); + it.each([ + ["slack-bot", "/repos", 200], + ["linear-bot", "/repos", 200], + ["github-bot", "/repos/acme/widgets/metadata", 200], + ["slack-bot", "/environments", 200], + ["linear-bot", "/environments", 200], + ["github-bot", "/environments/missing", 404], + ["slack-bot", "/integration-settings/slack", 200], + ["slack-bot", "/integration-settings/slack/watched-channels", 200], + ["slack-bot", "/model-preferences", 200], + ] as const)( + "allows actorless %s metadata/config read %s", + async (service, path, expectedStatus) => { + if (path === "/repos") { + await env.REPOS_CACHE.put( + "repos:list:v2", + JSON.stringify({ + repos: [], + cachedAt: new Date().toISOString(), + freshUntil: Date.now() + 60_000, + }) + ); + } + const response = await signedFetch({ + service, + method: "GET", + url: `https://test.local${path}`, + }); + expect(response.status).toBe(expectedStatus); + } + ); + + it("denies an actorless service without the route's exact grant", async () => { + const response = await signedFetch({ + service: "linear-bot", + method: "GET", + url: "https://test.local/integration-settings/slack", + }); + + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); + }); + + it("denies actorless resolved settings for the wrong integration", async () => { + const response = await signedFetch({ + service: "github-bot", + method: "GET", + url: "https://test.local/integration-settings/linear/resolved/acme/widgets", + }); + + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: "service_actor_required" }); + }); + + it.each([ + ["github-bot", "github"], + ["linear-bot", "linear"], + ] as const)( + "authorizes actorless %s only for matching resolved settings", + async (service, id) => { + const response = await signedFetch({ + service, + method: "GET", + url: `https://test.local/integration-settings/${id}/resolved/missing/repository`, + }); + + expect(response.status).not.toBe(403); + } + ); + it("requires a browser session in addition to the web service channel", async () => { const response = await signedFetch({ service: "web", @@ -78,6 +147,7 @@ describe("sig1 service-credential authentication", () => { secret: SERVICE_SECRET["linear-bot"], method: "GET", url: signedUrl, + actor: "linear:query-order", }); const response = await SELF.fetch( `https://test.local/sessions?createdBy=${createdBy}&limit=5`, @@ -88,20 +158,20 @@ describe("sig1 service-credential authentication", () => { expect(response.status).toBe(200); }); - it("delivers the signed body intact to the handler (D1 write lands)", async () => { + it("does not let an actorless service mutate global secrets", async () => { const response = await signedFetch({ service: "linear-bot", method: "PUT", url: "https://test.local/secrets", body: JSON.stringify({ secrets: { SIGNED_BODY_TEST: "intact" } }), }); - expect(response.status).toBe(200); + expect(response.status).toBe(403); const secrets = await new GlobalSecretsStore( env.DB, env.REPO_SECRETS_ENCRYPTION_KEY! ).getDecryptedSecrets(); - expect(secrets.SIGNED_BODY_TEST).toBe("intact"); + expect(secrets.SIGNED_BODY_TEST).toBeUndefined(); }); it("rejects a body tampered after signing", async () => { @@ -113,13 +183,14 @@ describe("sig1 service-credential authentication", () => { method: "PUT", url, body: intactBody, + actor: "linear:tamper-test", }); const intact = await SELF.fetch(url, { method: "PUT", headers: { "Content-Type": "application/json", ...headers }, body: intactBody, }); - expect(intact.status).toBe(200); + expect(intact.status).toBe(403); const tampered = await SELF.fetch(url, { method: "PUT", @@ -190,7 +261,7 @@ describe("sig1 service-credential authentication", () => { expect(response.status).toBe(401); }); - it("persists bot session ownership from the signed actor", async () => { + it("persists bot creator attribution and permits cross-actor collaboration", async () => { const created = await signedFetch({ service: "slack-bot", method: "POST", @@ -202,6 +273,7 @@ describe("sig1 service-credential authentication", () => { }), }); expect(created.status).toBe(201); + const createdBody = await created.json<{ sessionId: string }>(); const identity = await new UserStore(env.DB).getIdentity("slack", "U0001"); expect(identity).not.toBeNull(); @@ -221,6 +293,132 @@ describe("sig1 service-credential authentication", () => { spawnSource: "slack-bot", }) ); + + const collaboratorList = await signedFetch({ + service: "slack-bot", + method: "GET", + url: "https://test.local/sessions", + actor: "slack:U0002", + }); + expect(collaboratorList.status).toBe(200); + await expect(collaboratorList.json()).resolves.toMatchObject({ + sessions: [expect.objectContaining({ title: "Slack-owned session" })], + }); + + const collaborator = await signedFetch({ + service: "slack-bot", + method: "POST", + url: `https://test.local/sessions/${createdBody.sessionId}/prompt`, + actor: "slack:U0002", + body: JSON.stringify({ content: "Cross-session prompt" }), + }); + expect(collaborator.status).toBe(200); + + const deniedByServiceCeiling = await signedFetch({ + service: "slack-bot", + method: "DELETE", + url: `https://test.local/sessions/${createdBody.sessionId}`, + actor: "slack:U0002", + }); + expect(deniedByServiceCeiling.status).toBe(403); + await expect(deniedByServiceCeiling.json()).resolves.toMatchObject({ + code: "service_capability_required", + }); + }); + + it("allows only narrow actorless session callbacks", async () => { + const created = await signedFetch({ + service: "linear-bot", + method: "POST", + url: "https://test.local/sessions", + actor: "linear:U-CREATOR", + body: JSON.stringify({ + title: "Linear callback session", + model: "anthropic/claude-haiku-4-5", + }), + }); + expect(created.status).toBe(201); + const { sessionId } = await created.json<{ sessionId: string }>(); + + const linearStop = await signedFetch({ + service: "linear-bot", + method: "POST", + url: `https://test.local/sessions/${sessionId}/stop`, + }); + expect(linearStop.status).not.toBe(403); + + const slackMedia = await signedFetch({ + service: "slack-bot", + method: "GET", + url: `https://test.local/sessions/${sessionId}/media/missing-artifact`, + }); + expect(slackMedia.status).not.toBe(403); + + const wrongService = await signedFetch({ + service: "github-bot", + method: "POST", + url: `https://test.local/sessions/${sessionId}/stop`, + }); + expect(wrongService.status).toBe(403); + await expect(wrongService.json()).resolves.toMatchObject({ code: "service_actor_required" }); + }); + + it("denies suspended canonical bot actors and actorless broad requests", async () => { + await signedFetch({ + service: "slack-bot", + method: "POST", + url: "https://test.local/sessions", + actor: "slack:U-SUSPENDED", + body: JSON.stringify({ title: "Actor session", model: "anthropic/claude-haiku-4-5" }), + }); + const identity = await new UserStore(env.DB).getIdentity("slack", "U-SUSPENDED"); + await env.DB.prepare("UPDATE users SET suspended_at = 1 WHERE id = ?") + .bind(identity!.userId) + .run(); + + const attributed = await signedFetch({ + service: "slack-bot", + method: "GET", + url: "https://test.local/sessions", + actor: "slack:U-SUSPENDED", + }); + const actorless = await signedFetch({ + service: "slack-bot", + method: "GET", + url: "https://test.local/sessions", + }); + + expect(attributed.status).toBe(403); + await expect(attributed.json()).resolves.toMatchObject({ code: "active_user_required" }); + expect(actorless.status).toBe(403); + await expect(actorless.json()).resolves.toMatchObject({ code: "service_actor_required" }); + }); + + it("intersects an actor role with the service ceiling", async () => { + await signedFetch({ + service: "slack-bot", + method: "GET", + url: "https://test.local/sessions", + actor: "slack:U-VIEWER", + }); + const identity = await new UserStore(env.DB).getIdentity("slack", "U-VIEWER"); + await env.DB.prepare("UPDATE user_role_assignments SET role_id = ? WHERE user_id = ?") + .bind("role_builtin_viewer", identity!.userId) + .run(); + + const response = await signedFetch({ + service: "slack-bot", + method: "POST", + url: "https://test.local/sessions", + actor: "slack:U-VIEWER", + body: JSON.stringify({ title: "Viewer session", model: "anthropic/claude-haiku-4-5" }), + }); + + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ + code: "permission_required", + permission: "sessions.create", + }); }); it("requires a user or signed actor before any service can create a session", async () => { diff --git a/packages/linear-bot/src/webhook-handler.test.ts b/packages/linear-bot/src/webhook-handler.test.ts index 2c792d9059..e3ffb9d660 100644 --- a/packages/linear-bot/src/webhook-handler.test.ts +++ b/packages/linear-bot/src/webhook-handler.test.ts @@ -733,6 +733,9 @@ describe("handleAgentSessionEvent environment targets", () => { const promptCall = controlPlaneFetch.mock.calls.find(([input]) => String(input).endsWith("/prompt") ); + const eventsCall = controlPlaneFetch.mock.calls.find(([input]) => + String(input).includes("/events?") + ); const body = JSON.parse(String(promptCall?.[1]?.body)) as Record; // Identity travels via the signed actor assertion, never the body. expect(body).not.toHaveProperty("authorId"); @@ -750,6 +753,53 @@ describe("handleAgentSessionEvent environment targets", () => { }, }); expect(body.callbackContext).not.toHaveProperty("transitionIssueOnStart"); + expect(new Headers(eventsCall?.[1]?.headers).get("X-OpenInspect-Actor")).toBe( + "linear:follow-up-human-user" + ); + expect(new Headers(promptCall?.[1]?.headers).get("X-OpenInspect-Actor")).toBe( + "linear:follow-up-human-user" + ); + }); + + it("falls back to the session creator when follow-up author fields are absent", async () => { + const { kv } = createFakeKV({ + "oauth:client-credentials:org-1": validToken(), + "issue:issue-1": JSON.stringify({ + sessionId: "session-xyz", + issueId: "issue-1", + issueIdentifier: "ENG-42", + repoOwner: "acme", + repoName: "backend", + model: "anthropic/claude-haiku-4-5", + createdAt: Date.now(), + }), + }); + const env = makeLinearBotEnv(kv); + const controlPlaneFetch = (env.CONTROL_PLANE as unknown as { fetch: ReturnType }) + .fetch; + controlPlaneFetch.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/integration-settings/")) return Response.json({ config: null }); + if (url.endsWith("/events?type=token&limit=20")) return Response.json({ events: [] }); + if (url.endsWith("/prompt")) return Response.json({ ok: true }); + throw new Error(`Unexpected control-plane fetch to ${url}`); + }); + const webhook = makeWebhook(); + webhook.action = "prompted"; + webhook.agentSession.creatorId = "session-creator"; + webhook.agentActivity = { + content: { type: "prompt", body: "Please continue." }, + }; + + await handleAgentSessionEvent(webhook, env, "trace-follow-up-creator-fallback"); + + const sessionCalls = controlPlaneFetch.mock.calls.filter(([input]) => + /\/(events\?|prompt$)/.test(String(input)) + ); + expect(sessionCalls).toHaveLength(2); + for (const [, init] of sessionCalls) { + expect(new Headers(init?.headers).get("X-OpenInspect-Actor")).toBe("linear:session-creator"); + } }); it("adds prior token context from a parsed events response", async () => { @@ -818,6 +868,10 @@ describe("handleAgentSessionEvent environment targets", () => { "https://internal/sessions/session-xyz/stop", expect.objectContaining({ method: "POST" }) ); + const stopInit = controlPlaneFetch.mock.calls[0]?.[1] as RequestInit | undefined; + expect(new Headers(stopInit?.headers).get("X-OpenInspect-Actor")).toBe( + "linear:follow-up-human-user" + ); expect(store.has("issue:issue-1")).toBe(false); }); diff --git a/packages/linear-bot/src/webhook-handler.ts b/packages/linear-bot/src/webhook-handler.ts index 4d5a0b80fb..d8468e81b2 100644 --- a/packages/linear-bot/src/webhook-handler.ts +++ b/packages/linear-bot/src/webhook-handler.ts @@ -224,10 +224,16 @@ async function handleStop(webhook: AgentSessionWebhook, env: Env, traceId: strin const existingSession = await lookupIssueSession(env, issueId); if (existingSession) { const stopUrl = `https://internal/sessions/${existingSession.sessionId}/stop`; + const actorUserId = + webhook.agentActivity?.userId ?? + webhook.agentSession.comment?.userId ?? + webhook.agentSession.creatorId ?? + undefined; try { const stopRes = await signedControlPlaneFetch(env, { method: "POST", url: stopUrl, + actor: actorUserId ? `linear:${actorUserId}` : undefined, traceId, }); if (!stopRes.ok) { @@ -309,12 +315,13 @@ function getFollowUp(webhook: AgentSessionWebhook): { source: "linear_agent_activity" | "linear_comment" | "linear_fallback"; actorUserId?: string; } { + const fallbackActorUserId = webhook.agentSession.creatorId ?? undefined; const activityBody = webhook.agentActivity?.content?.body; if (activityBody) { return { content: activityBody, source: "linear_agent_activity", - actorUserId: webhook.agentActivity?.userId, + actorUserId: webhook.agentActivity?.userId ?? fallbackActorUserId, }; } @@ -323,11 +330,15 @@ function getFollowUp(webhook: AgentSessionWebhook): { return { content: comment.body, source: "linear_comment", - actorUserId: comment.userId, + actorUserId: comment.userId ?? fallbackActorUserId, }; } - return { content: "Follow-up on the issue.", source: "linear_fallback" }; + return { + content: "Follow-up on the issue.", + source: "linear_fallback", + actorUserId: fallbackActorUserId, + }; } function buildLinearCallbackContext(params: { @@ -419,6 +430,7 @@ async function handleFollowUp( const eventsRes = await signedControlPlaneFetch(env, { method: "GET", url: eventsUrl, + actor: followUp.actorUserId ? `linear:${followUp.actorUserId}` : undefined, traceId, }); if (eventsRes.ok) { diff --git a/packages/slack-bot/src/attachments.test.ts b/packages/slack-bot/src/attachments.test.ts index 6ab59fb5bb..207b43df96 100644 --- a/packages/slack-bot/src/attachments.test.ts +++ b/packages/slack-bot/src/attachments.test.ts @@ -56,7 +56,7 @@ function uploadCreatedResponse(attachmentId = "att-1"): Response { /** Download + upload in one step, as the delivery pipeline runs them. */ async function prepareAndUpload(env: Env, sessionId: string, files: SlackMessageFile[]) { const prepared = await prepareImageAttachments(env, toImageAttachments(files)); - return uploadPreparedAttachments(env, sessionId, prepared); + return uploadPreparedAttachments(env, sessionId, prepared, "slack:U1"); } afterEach(() => { @@ -270,7 +270,7 @@ describe("uploadPreparedAttachments", () => { method: "POST", url: uploadUrl, bodySha256Hex: await sha256Hex(uploadInit.body as Uint8Array), - actor: "", + actor: "slack:U1", }); expect(verified).toMatchObject({ ok: true }); }); diff --git a/packages/slack-bot/src/attachments.ts b/packages/slack-bot/src/attachments.ts index 72e82838e6..71c4168fba 100644 --- a/packages/slack-bot/src/attachments.ts +++ b/packages/slack-bot/src/attachments.ts @@ -253,6 +253,7 @@ async function uploadToSession( env: Env, sessionId: string, file: PreparedImageAttachments["files"][number], + authorId: string, traceId?: string ): Promise<{ reference: SessionAttachmentReference } | { sessionMissing: boolean }> { const { attachment, bytes } = file; @@ -275,6 +276,7 @@ async function uploadToSession( method: "POST", url: `https://internal/sessions/${sessionId}/attachments`, body: { bytes: multipartBytes, contentType }, + actor: authorId.startsWith("slack:") ? authorId : undefined, traceId, }, { signal: AbortSignal.timeout(OUTBOUND_REQUEST_TIMEOUT_MS) } @@ -320,10 +322,11 @@ export async function uploadPreparedAttachments( env: Env, sessionId: string, prepared: PreparedImageAttachments, + authorId: string, traceId?: string ): Promise { const outcomes = await Promise.all( - prepared.files.map((file) => uploadToSession(env, sessionId, file, traceId)) + prepared.files.map((file) => uploadToSession(env, sessionId, file, authorId, traceId)) ); const references: SessionAttachmentReference[] = []; const dropped: SlackAttachmentDropReason[] = [...prepared.dropped]; diff --git a/packages/slack-bot/src/sessions/prompt-delivery.ts b/packages/slack-bot/src/sessions/prompt-delivery.ts index edaa5fab14..5086e847b8 100644 --- a/packages/slack-bot/src/sessions/prompt-delivery.ts +++ b/packages/slack-bot/src/sessions/prompt-delivery.ts @@ -60,7 +60,7 @@ export async function deliverPrompt( threadTs, traceId, } = options; - const upload = await uploadPreparedAttachments(env, sessionId, attachments, traceId); + const upload = await uploadPreparedAttachments(env, sessionId, attachments, authorId, traceId); if (imageOnly && upload.references.length === 0) { // The placeholder prompt would launch a meaningless run with nothing From 4866d41a315772efbaf9f503104daf18738a5506 Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 22:34:24 -0700 Subject: [PATCH 3/6] fix(rbac): address foundation review feedback --- .github/workflows/ci.yml | 4 +- package-lock.json | 2 +- package.json | 2 +- .../src/authorization/service.ts | 5 +- .../src/db/authorization-store.test.ts | 29 ++-- .../src/db/authorization-store.ts | 80 ++++++++--- packages/control-plane/src/db/user-merge.ts | 133 +++++++++++++---- .../test/integration/rbac-foundation.test.ts | 118 ++++++++++++++- .../test/integration/user-merge.test.ts | 134 ++++++++++++++++++ packages/shared/src/rbac.test.ts | 20 +++ packages/shared/src/rbac.ts | 57 ++++++-- scripts/bootstrap-workspace-owner.test.ts | 68 ++++++++- scripts/bootstrap-workspace-owner.ts | 38 +++-- scripts/merge-split-users.ts | 55 +++---- .../d1/migrations/0071_rbac_foundation.sql | 14 +- 15 files changed, 644 insertions(+), 115 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 712ab60350..f70ac230d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,7 +65,9 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v6 with: - node-version: "22" + # Minimum supported release: node:sqlite is available without an + # additional flag and --experimental-transform-types is present. + node-version: "22.13.0" cache: "npm" - name: Install dependencies diff --git a/package-lock.json b/package-lock.json index 329515bac3..3c0cb3a554 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,7 +27,7 @@ "wrangler": "^4.103.0" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.13.0" } }, "node_modules/@acemir/cssom": { diff --git a/package.json b/package.json index 35871e3ed3..5c7a63432f 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "wrangler": "^4.103.0" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.13.0" }, "overrides": { "minimatch": "^10.2.5", diff --git a/packages/control-plane/src/authorization/service.ts b/packages/control-plane/src/authorization/service.ts index 36da1c984b..bab14ebae1 100644 --- a/packages/control-plane/src/authorization/service.ts +++ b/packages/control-plane/src/authorization/service.ts @@ -156,9 +156,12 @@ export class AuthorizationService { if (outcome.status === "actor_authorization_changed") { throw new RbacConflictError("Actor authorization changed"); } - if (outcome.status === "not_found") { + if (outcome.status === "role_not_found") { throw new AuthorizationError(404, "role_not_found"); } + if (outcome.status === "member_not_found") { + throw new AuthorizationError(404, "member_not_found"); + } if (outcome.status === "conflict") { throw new RbacConflictError(conflictMessage); } diff --git a/packages/control-plane/src/db/authorization-store.test.ts b/packages/control-plane/src/db/authorization-store.test.ts index 7800455036..8830ccf91f 100644 --- a/packages/control-plane/src/db/authorization-store.test.ts +++ b/packages/control-plane/src/db/authorization-store.test.ts @@ -62,20 +62,23 @@ describe("AuthorizationStore", () => { ]); }); - it.each(["applied", "actor_authorization_changed", "not_found", "conflict"] as const)( - "returns the %s member status replacement batch outcome", - async (status) => { - const store = new AuthorizationStore( - fakeDatabase({ - batchResults: [result(0, [{ status }]), result(1), result(1), result(1)], - }) - ); + it.each([ + "applied", + "actor_authorization_changed", + "role_not_found", + "member_not_found", + "conflict", + ] as const)("returns the %s member status replacement batch outcome", async (status) => { + const store = new AuthorizationStore( + fakeDatabase({ + batchResults: [result(0, [{ status }]), result(1), result(1), result(1)], + }) + ); - await expect(store.replaceMemberStatus(replaceMemberStatusInput)).resolves.toEqual({ - status, - }); - } - ); + await expect(store.replaceMemberStatus(replaceMemberStatusInput)).resolves.toEqual({ + status, + }); + }); it("does not classify an unexpected database failure as a conflict", async () => { const failure = new Error("database unavailable"); diff --git a/packages/control-plane/src/db/authorization-store.ts b/packages/control-plane/src/db/authorization-store.ts index f03b546055..1bd2491214 100644 --- a/packages/control-plane/src/db/authorization-store.ts +++ b/packages/control-plane/src/db/authorization-store.ts @@ -1,7 +1,9 @@ import { BUILT_IN_ROLE_REGISTRY, + roleReferenceSchema, type BuiltInRoleKey, type PermissionId, + type RoleReference, type WorkspaceMember, } from "@open-inspect/shared/rbac"; import { rolePermissionPredicate } from "../authorization/permission-sql"; @@ -39,17 +41,14 @@ interface MemberRow { export interface EffectiveAuthorizationRecord { userId: string; suspendedAt: number | null; - role: { id: string; key: BuiltInRoleKey | null; name: string } | null; + role: RoleReference | null; } /** Persistence view of a role and the number of users currently assigned to it. */ -export interface AuthorizationRoleRecord { - id: string; - key: BuiltInRoleKey | null; - name: string; +export type AuthorizationRoleRecord = RoleReference & { description: string | null; assignmentCount: number; -} +}; interface AuditInput { requestId: string; @@ -93,25 +92,33 @@ function anotherUnsuspendedOwner(targetUserId: string): SqlCondition { export type AuthorizationMutationOutcome = | { status: "applied" } | { status: "actor_authorization_changed" } - | { status: "not_found" } + | { status: "role_not_found" } + | { status: "member_not_found" } | { status: "conflict" }; +type NotFoundStatus = Extract< + AuthorizationMutationOutcome["status"], + "role_not_found" | "member_not_found" +>; + +function toRoleReference(id: string, key: BuiltInRoleKey | null, name: string): RoleReference { + return roleReferenceSchema.parse({ id, key, name }); +} + function toEffectiveAuthorizationRecord(row: EffectiveRow): EffectiveAuthorizationRecord { return { userId: row.user_id, suspendedAt: row.suspended_at, role: row.role_id && row.role_name - ? { id: row.role_id, key: row.role_key, name: row.role_name } + ? toRoleReference(row.role_id, row.role_key, row.role_name) : null, }; } function toRoleRecord(row: RoleRow): AuthorizationRoleRecord { return { - id: row.id, - key: row.key, - name: row.name, + ...toRoleReference(row.id, row.key, row.name), description: row.description, assignmentCount: Number(row.assignment_count), }; @@ -123,7 +130,7 @@ function toMember(row: MemberRow): WorkspaceMember { displayName: row.display_name, email: row.email, suspendedAt: row.suspended_at, - role: { id: row.role_id, key: row.role_key, name: row.role_name }, + role: toRoleReference(row.role_id, row.role_key, row.role_name), }; } @@ -240,6 +247,22 @@ export class AuthorizationStore { sql: `(? <> ? AND NOT (${targetIsOwner.sql})) OR ${transferGuard.sql}`, values: [input.roleId, OWNER_ROLE_ID, ...targetIsOwner.values, ...transferGuard.values], }, + notFound: [ + { + status: "role_not_found", + condition: { + sql: "NOT EXISTS (SELECT 1 FROM roles WHERE id = ?)", + values: [input.roleId], + }, + }, + { + status: "member_not_found", + condition: { + sql: "NOT EXISTS (SELECT 1 FROM user_role_assignments WHERE user_id = ?)", + values: [input.targetUserId], + }, + }, + ], } ); const results = await this.db.batch([ @@ -308,6 +331,19 @@ export class AuthorizationStore { sql: `NOT (${targetIsOwner.sql}) OR ${transferGuard.sql}`, values: [...targetIsOwner.values, ...transferGuard.values], }, + notFound: [ + { + status: "member_not_found", + condition: { + sql: `NOT EXISTS ( + SELECT 1 FROM users + JOIN user_role_assignments ON user_role_assignments.user_id = users.id + WHERE users.id = ? + )`, + values: [input.targetUserId], + }, + }, + ], } ); const statements: SqlStatement[] = [ @@ -355,7 +391,10 @@ export class AuthorizationStore { actorUserId: string, permissions: PermissionId[], resourceCondition: SqlCondition, - options?: { actor?: SqlCondition; notFound?: SqlCondition } + options?: { + actor?: SqlCondition; + notFound?: Array<{ status: NotFoundStatus; condition: SqlCondition }>; + } ): { outcome: SqlStatement; applied: SqlCondition; @@ -383,17 +422,25 @@ export class AuthorizationStore { values: [...actor.values, ...resourceCondition.values], }; const auditId = crypto.randomUUID(); + const notFoundCases = + options?.notFound + ?.map(({ status, condition }) => `WHEN (${condition.sql}) THEN '${status}'`) + .join("\n ") ?? ""; return { outcome: this.db .prepare( `SELECT CASE WHEN NOT (${actor.sql}) THEN 'actor_authorization_changed' - ${options?.notFound ? `WHEN (${options.notFound.sql}) THEN 'not_found'` : ""} + ${notFoundCases} WHEN NOT (${resourceCondition.sql}) THEN 'conflict' ELSE 'applied' END AS status` ) - .bind(...actor.values, ...(options?.notFound?.values ?? []), ...resourceCondition.values), + .bind( + ...actor.values, + ...(options?.notFound?.flatMap(({ condition }) => condition.values) ?? []), + ...resourceCondition.values + ), applied, writes: { sql: "EXISTS (SELECT 1 FROM authorization_audit_events WHERE id = ?)", @@ -408,7 +455,8 @@ export class AuthorizationStore { if ( status !== "applied" && status !== "actor_authorization_changed" && - status !== "not_found" && + status !== "role_not_found" && + status !== "member_not_found" && status !== "conflict" ) { throw new Error("Invalid authorization mutation outcome"); diff --git a/packages/control-plane/src/db/user-merge.ts b/packages/control-plane/src/db/user-merge.ts index e098a2815a..95e3d190cc 100644 --- a/packages/control-plane/src/db/user-merge.ts +++ b/packages/control-plane/src/db/user-merge.ts @@ -20,12 +20,9 @@ import type { SqlDatabase, SqlResult, SqlStatement } from "./sql-database"; * `idx_user_identities_provider`). * - `automations.created_by` is re-pointed value-conditionally: legacy rows * store GitHub numeric ids, which must never be rewritten. - * - Idempotent: re-running a completed merge is a zero-count no-op, and a - * partially-applied run is repaired by running the script again — with one - * exception: the final email backfill's input (the loser row) is deleted by - * the preceding statement, so a stop exactly between those two statements - * is not re-derivable from the database. The CLI prints a recovery record - * before executing to cover that residual case. + * - Idempotent: re-running a completed merge is a zero-count no-op. The + * execute path requires an atomic SqlDatabase batch so no partial graph can + * become externally visible. * - Browser sessions (`auth_sessions`) issued to the loser are deleted. An * issued bearer credential is never rewritten to authenticate as another * canonical user. @@ -74,6 +71,15 @@ const USER_MERGE_COUNT_KEYS = [ "roleAssignmentsRemoved", "providerAccountAuthorizationsRepointed", "providerAccountAuthorizationAttemptsRepointed", + "providerAccountsCreatedRepointed", + "providerAccountsUpdatedRepointed", + "providerAccountDefaultsCreatedRepointed", + "providerAccountDefaultsUpdatedRepointed", + "skillsCreatedRepointed", + "skillsUpdatedRepointed", + "skillRevisionsCreatedRepointed", + "skillAssignmentsCreatedRepointed", + "skillCatalogGenerationsAdvanced", "keyboardShortcutPreferencesDeduped", "keyboardShortcutPreferencesRepointed", "auditEventsCreated", @@ -84,6 +90,12 @@ const USER_MERGE_COUNT_KEYS = [ type UserMergeCountKey = (typeof USER_MERGE_COUNT_KEYS)[number]; type UserMergeCounts = Record; +const RESULT_CHANGE_DIVISORS: Partial> = { + // The assignment UPDATE trigger also advances skills_catalog_state once per + // changed assignment, and D1 includes both rows in meta.changes. + skillAssignmentsCreatedRepointed: 2, +}; + interface MergeOperation { readonly key: UserMergeCountKey; readonly execute: (db: SqlDatabase, survivorId: string, loserId: string) => SqlStatement; @@ -178,12 +190,48 @@ const SKILL_PROFILE_OPERATIONS = dedupeThenRepoint({ )`, }); +const SKILL_CATALOG_GENERATION_OPERATION: MergeOperation = { + key: "skillCatalogGenerationsAdvanced", + execute: (db, _survivorId, loserId) => + db + .prepare( + `UPDATE skills_catalog_state SET generation = generation + 1 + WHERE singleton = 1 + AND EXISTS (SELECT 1 FROM skill_profiles WHERE user_id = ?)` + ) + .bind(loserId), + preview: (db, _survivorId, loserId) => + db + .prepare( + `SELECT COUNT(*) AS count FROM skills_catalog_state + WHERE singleton = 1 + AND EXISTS (SELECT 1 FROM skill_profiles WHERE user_id = ?)` + ) + .bind(loserId), +}; + const FINAL_REPOINT_OPERATIONS = [ regularRepoint("providerAccountAuthorizationsRepointed", "model_provider_account_authorizations"), regularRepoint( "providerAccountAuthorizationAttemptsRepointed", "model_provider_account_authorization_attempts" ), + regularRepoint("providerAccountsCreatedRepointed", "model_provider_accounts", "created_by"), + regularRepoint("providerAccountsUpdatedRepointed", "model_provider_accounts", "updated_by"), + regularRepoint( + "providerAccountDefaultsCreatedRepointed", + "model_provider_account_defaults", + "created_by" + ), + regularRepoint( + "providerAccountDefaultsUpdatedRepointed", + "model_provider_account_defaults", + "updated_by" + ), + regularRepoint("skillsCreatedRepointed", "skills", "created_by"), + regularRepoint("skillsUpdatedRepointed", "skills", "updated_by"), + regularRepoint("skillRevisionsCreatedRepointed", "skill_revisions", "created_by"), + regularRepoint("skillAssignmentsCreatedRepointed", "skill_assignments", "created_by"), ...dedupeThenRepoint({ dedupeKey: "keyboardShortcutPreferencesDeduped", repointKey: "keyboardShortcutPreferencesRepointed", @@ -194,6 +242,7 @@ const FINAL_REPOINT_OPERATIONS = [ const TABLE_OPERATIONS = [ ...BEFORE_SKILL_PROFILE_OPERATIONS, + SKILL_CATALOG_GENERATION_OPERATION, ...SKILL_PROFILE_OPERATIONS, ...FINAL_REPOINT_OPERATIONS, ] as const; @@ -229,14 +278,15 @@ export async function mergeUsers( throw new UserMergeError(`Survivor user ${survivorId} not found`); } // A missing loser row is not an error: re-running a completed merge must - // be a no-op, and a partially-applied merge must be resumable. + // be a no-op after an already-completed atomic merge. const loser = await db - .prepare(`SELECT id, email, email_verified FROM users WHERE id = ?`) + .prepare(`SELECT id, email, email_verified, suspended_at FROM users WHERE id = ?`) .bind(loserId) .first<{ id: string; email: string | null; email_verified: number; + suspended_at: number | null; }>(); if (!loser) { return { survivorId, loserId, dryRun: options.dryRun === true, counts: emptyCounts() }; @@ -269,6 +319,9 @@ export async function mergeUsers( if (survivorRole && loserRole && survivorRole.role_id !== loserRole.role_id) { throw new UserMergeError("Resolve conflicting user roles before merging"); } + if (survivor.suspended_at !== loser.suspended_at) { + throw new UserMergeError("Resolve conflicting user suspension states before merging"); + } if (loserRole?.role_key === "owner" && survivor.suspended_at !== null) { throw new UserMergeError("The surviving Owner must be active before merging"); } @@ -298,11 +351,54 @@ export async function mergeUsers( } }; + const auditId = crypto.randomUUID(); + const occurredAt = Date.now(); + // The NOT NULL occurred_at column turns a failed revalidation into a batch + // error, rolling back every merge write. This closes the preflight/write + // window for role, suspension, and last-active-Owner invariants. + add( + "auditEventsCreated", + db + .prepare( + `INSERT INTO authorization_audit_events + (id, occurred_at, request_id, principal_kind, + actor_service_snapshot, action, resource_type, resource_id, + target_user_id_snapshot, reason_code) + VALUES ( + ?, + CASE WHEN EXISTS ( + SELECT 1 + FROM users survivor + JOIN user_role_assignments survivor_assignment + ON survivor_assignment.user_id = survivor.id + JOIN users loser ON loser.id = ? + JOIN user_role_assignments loser_assignment + ON loser_assignment.user_id = loser.id + JOIN roles role ON role.id = loser_assignment.role_id + WHERE survivor.id = ? + AND survivor_assignment.role_id = loser_assignment.role_id + AND survivor.suspended_at IS loser.suspended_at + AND (role.key IS NULL OR role.key <> 'owner' OR survivor.suspended_at IS NULL) + ) THEN ? ELSE NULL END, + 'user-merge', 'service', 'control-plane', + 'workspace.user_merged', 'user', ?, ?, 'operator_merge' + )` + ) + .bind(auditId, loserId, survivorId, occurredAt, survivorId, loserId) + ); + // Dedup before re-pointing: drop loser rows whose target slot the survivor // already occupies (identities under idx_user_identities_provider; read // states routinely, where both split rows read the same session). addOperations(BEFORE_SKILL_PROFILE_OPERATIONS); + // Profile resolution uses this generation as a consistency fence. Advance + // it before any profile membership or ownership rows are changed. + add( + SKILL_CATALOG_GENERATION_OPERATION.key, + SKILL_CATALOG_GENERATION_OPERATION.execute(db, survivorId, loserId) + ); + // Merge items before deleting colliding skill profiles. add( "skillProfileItemsMerged", @@ -327,21 +423,6 @@ export async function mergeUsers( ); addOperations(FINAL_REPOINT_OPERATIONS); - // Record the merge before deleting the user so the snapshots remain explicit. - add( - "auditEventsCreated", - db - .prepare( - `INSERT INTO authorization_audit_events - (id, occurred_at, request_id, principal_kind, - actor_service_snapshot, action, resource_type, resource_id, - target_user_id_snapshot, reason_code) - VALUES (?, ?, 'user-merge', 'service', 'control-plane', - 'workspace.user_merged', 'user', ?, ?, 'operator_merge')` - ) - .bind(crypto.randomUUID(), Date.now(), survivorId, loserId) - ); - add("usersDeleted", db.prepare(`DELETE FROM users WHERE id = ?`).bind(loserId)); if (backfillEmail) { // A blank-or-NULL-email survivor acquires the email freed by the loser's @@ -367,7 +448,7 @@ export async function mergeUsers( const counts = emptyCounts(); for (const [key, index] of Object.entries(track) as [UserMergeCountKey, number][]) { - counts[key] = results[index]?.meta.changes ?? 0; + counts[key] = (results[index]?.meta.changes ?? 0) / (RESULT_CHANGE_DIVISORS[key] ?? 1); } if (loser) { // The users delete's reported `changes` includes any FK-cascaded rows; @@ -438,7 +519,9 @@ async function previewCounts( ...operationCounts, skillProfileItemsMerged: count(skillProfileItemsMerged), roleAssignmentsRemoved: count(roleAssignments), - auditEventsCreated: count(users), + // mergeUsers returns before previewing when the loser is absent, so an + // executed merge always writes exactly one audit event. + auditEventsCreated: 1, canonicalEmailBackfilled, usersDeleted: count(users), }; diff --git a/packages/control-plane/test/integration/rbac-foundation.test.ts b/packages/control-plane/test/integration/rbac-foundation.test.ts index bb73a61d85..a73bdb9ba6 100644 --- a/packages/control-plane/test/integration/rbac-foundation.test.ts +++ b/packages/control-plane/test/integration/rbac-foundation.test.ts @@ -4,7 +4,16 @@ import { PERMISSION_IDS, permissionsForBuiltInRole, } from "@open-inspect/shared/rbac"; -import { describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it } from "vitest"; +import { AuthorizationStore } from "../../src/db/authorization-store"; +import { AuthorizationService } from "../../src/authorization/service"; +import { cleanD1Tables } from "./cleanup"; +import { insertCanonicalUser } from "./identity-seed-helpers"; + +const ACTOR_ID = "11111111111111111111111111111111"; +const TARGET_ID = "22222222222222222222222222222222"; + +beforeEach(cleanD1Tables); describe("RBAC foundation migration", () => { it("seeds built-in roles without persisting their code-owned permissions", async () => { @@ -24,4 +33,111 @@ describe("RBAC foundation migration", () => { ).toEqual({ count: 0 }); expect(permissionsForBuiltInRole("owner")).toHaveLength(PERMISSION_IDS.length); }); + + it("rejects non-canonical system role identities and reserved IDs used as custom roles", async () => { + await expect( + env.DB.prepare( + `INSERT INTO roles (id, key, name, normalized_name, is_system) + VALUES ('role_system_alias', NULL, 'Alias', 'alias', 1)` + ).run() + ).rejects.toThrow(); + + await expect( + env.DB.prepare( + `UPDATE roles SET key = NULL, is_system = 0 + WHERE id = 'role_builtin_owner'` + ).run() + ).rejects.toThrow(); + + await expect( + env.DB.prepare( + `UPDATE roles SET key = NULL + WHERE id = 'role_builtin_owner'` + ).run() + ).rejects.toThrow(); + }); + + it("classifies missing roles and members through real D1 mutation SQL", async () => { + await insertCanonicalUser({ id: ACTOR_ID, email: "owner@example.com" }); + await insertCanonicalUser({ id: TARGET_ID, email: "member@example.com" }); + await env.DB.prepare("UPDATE user_role_assignments SET role_id = ? WHERE user_id = ?") + .bind(BUILT_IN_ROLE_REGISTRY.owner.id, ACTOR_ID) + .run(); + const store = new AuthorizationStore(env.DB); + + await expect( + store.replaceMemberRole({ + actorUserId: ACTOR_ID, + targetUserId: TARGET_ID, + roleId: "role_missing", + requestId: "missing-role", + now: 100, + }) + ).resolves.toEqual({ status: "role_not_found" }); + await expect( + store.replaceMemberRole({ + actorUserId: ACTOR_ID, + targetUserId: "33333333333333333333333333333333", + roleId: BUILT_IN_ROLE_REGISTRY.viewer.id, + requestId: "missing-role-target", + now: 101, + }) + ).resolves.toEqual({ status: "member_not_found" }); + await expect( + store.replaceMemberStatus({ + actorUserId: ACTOR_ID, + targetUserId: "33333333333333333333333333333333", + suspended: true, + requestId: "missing-status-target", + now: 102, + }) + ).resolves.toEqual({ status: "member_not_found" }); + + const service = new AuthorizationService(env.DB); + await expect( + service.replaceMemberRole({ + actorUserId: ACTOR_ID, + targetUserId: TARGET_ID, + roleId: "role_missing", + requestId: "missing-role-service", + }) + ).rejects.toMatchObject({ status: 404, code: "role_not_found" }); + await expect( + service.replaceMemberStatus({ + actorUserId: ACTOR_ID, + targetUserId: "33333333333333333333333333333333", + suspended: true, + requestId: "missing-member-service", + }) + ).rejects.toMatchObject({ status: 404, code: "member_not_found" }); + }); + + it("applies and audits a member mutation through real D1 SQL", async () => { + await insertCanonicalUser({ id: ACTOR_ID, email: "owner@example.com" }); + await insertCanonicalUser({ id: TARGET_ID, email: "member@example.com" }); + await env.DB.prepare("UPDATE user_role_assignments SET role_id = ? WHERE user_id = ?") + .bind(BUILT_IN_ROLE_REGISTRY.owner.id, ACTOR_ID) + .run(); + const store = new AuthorizationStore(env.DB); + + await expect( + store.replaceMemberRole({ + actorUserId: ACTOR_ID, + targetUserId: TARGET_ID, + roleId: BUILT_IN_ROLE_REGISTRY.viewer.id, + requestId: "apply-role", + now: 200, + }) + ).resolves.toEqual({ status: "applied" }); + await expect( + env.DB.prepare( + `SELECT action, request_id, target_user_id_snapshot + FROM authorization_audit_events WHERE request_id = 'apply-role'` + ).first() + ).resolves.toEqual({ + action: "workspace.member_role_updated", + request_id: "apply-role", + target_user_id_snapshot: TARGET_ID, + }); + }); }); diff --git a/packages/control-plane/test/integration/user-merge.test.ts b/packages/control-plane/test/integration/user-merge.test.ts index 43d6272c1e..75e8d66eeb 100644 --- a/packages/control-plane/test/integration/user-merge.test.ts +++ b/packages/control-plane/test/integration/user-merge.test.ts @@ -1,6 +1,7 @@ import { env } from "cloudflare:test"; import { beforeEach, describe, expect, it } from "vitest"; import { mergeUsers, UserMergeError } from "../../src/db/user-merge"; +import type { SqlDatabase, SqlResult, SqlStatement } from "../../src/db/sql-database"; import { cleanD1Tables } from "./cleanup"; import { SEED_NOW_MS, @@ -115,6 +116,7 @@ describe("mergeUsers", () => { automationsCreatedRepointed: 1, scmTokensRepointed: 1, skillProfilesRepointed: 1, + skillCatalogGenerationsAdvanced: 1, readStatesDeduped: 1, readStatesRepointed: 1, usersDeleted: 1, @@ -158,6 +160,11 @@ describe("mergeUsers", () => { ).toEqual({ last_read_message_id: "msg-survivor" }); expect(await getUserRow(LOSER)).toBeNull(); expect(await countTableRows("users")).toBe(1); + expect( + await env.DB.prepare( + "SELECT generation FROM skills_catalog_state WHERE singleton = 1" + ).first() + ).toEqual({ generation: 1 }); expect( await env.DB.prepare( `SELECT principal_kind, actor_user_id_snapshot, actor_service_snapshot, @@ -308,6 +315,88 @@ describe("mergeUsers", () => { ).toEqual({ shortcuts: "{}" }); }); + it("preserves canonical attribution across provider accounts and managed skills", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + await env.DB.batch([ + env.DB.prepare( + `INSERT INTO model_provider_accounts + (id, provider, display_name, status, created_by, updated_by, created_at, updated_at) + VALUES ('provider-account', 'openai', 'Personal', 'active', ?, ?, 1, 1)` + ).bind(LOSER, LOSER), + env.DB.prepare( + `INSERT INTO model_provider_account_defaults + (provider, provider_account_id, created_by, updated_by, created_at, updated_at) + VALUES ('openai', 'provider-account', ?, ?, 1, 1)` + ).bind(LOSER, LOSER), + env.DB.prepare( + `INSERT INTO skills + (id, name, enabled, created_by, updated_by, created_at, updated_at) + VALUES ('skill-1', 'Skill One', 1, ?, ?, 1, 1)` + ).bind(LOSER, LOSER), + env.DB.prepare( + `INSERT INTO skill_revisions + (id, skill_id, revision_number, revision_sha256, description, body, + metadata_json, total_bytes, created_by, created_at) + VALUES ('revision-1', 'skill-1', 1, ?, 'Description', 'Body', '{}', 4, ?, 1)` + ).bind("a".repeat(64), LOSER), + ]); + await env.DB.batch([ + env.DB.prepare("UPDATE skills SET current_revision_id = 'revision-1' WHERE id = 'skill-1'"), + env.DB.prepare( + `INSERT INTO skill_assignments + (id, skill_id, scope_type, created_by, created_at) + VALUES ('assignment-1', 'skill-1', 'global', ?, 1)` + ).bind(LOSER), + ]); + + const preview = await mergeUsers(env.DB, { + survivorId: SURVIVOR, + loserId: LOSER, + dryRun: true, + }); + const result = await mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER }); + + expect(preview.counts).toMatchObject({ + providerAccountsCreatedRepointed: 1, + providerAccountsUpdatedRepointed: 1, + providerAccountDefaultsCreatedRepointed: 1, + providerAccountDefaultsUpdatedRepointed: 1, + skillsCreatedRepointed: 1, + skillsUpdatedRepointed: 1, + skillRevisionsCreatedRepointed: 1, + skillAssignmentsCreatedRepointed: 1, + }); + expect(result.counts).toEqual(preview.counts); + expect( + await env.DB.prepare( + `SELECT created_by, updated_by FROM model_provider_accounts + WHERE id = 'provider-account'` + ).first() + ).toEqual({ created_by: SURVIVOR, updated_by: SURVIVOR }); + expect( + await env.DB.prepare( + `SELECT created_by, updated_by FROM model_provider_account_defaults + WHERE provider = 'openai'` + ).first() + ).toEqual({ created_by: SURVIVOR, updated_by: SURVIVOR }); + expect( + await env.DB.prepare( + `SELECT s.created_by, s.updated_by, r.created_by AS revision_created_by, + a.created_by AS assignment_created_by + FROM skills s + JOIN skill_revisions r ON r.id = 'revision-1' + JOIN skill_assignments a ON a.id = 'assignment-1' + WHERE s.id = 'skill-1'` + ).first() + ).toEqual({ + created_by: SURVIVOR, + updated_by: SURVIVOR, + revision_created_by: SURVIVOR, + assignment_created_by: SURVIVOR, + }); + }); + it("keeps keyboard preference collision preview and execution counts aligned", async () => { await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); await insertCanonicalUser({ id: LOSER, email: null }); @@ -355,6 +444,51 @@ describe("mergeUsers", () => { expect(await countTableRows("users")).toBe(1); }); + it("rejects a suspended loser merging into an active survivor", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + await env.DB.prepare("UPDATE users SET suspended_at = 123 WHERE id = ?").bind(LOSER).run(); + + await expect(mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER })).rejects.toThrow( + /suspension states/ + ); + expect(await getUserRow(LOSER)).not.toBeNull(); + }); + + it("rolls back when role invariants change after preflight", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + let batchCount = 0; + const racingDatabase: SqlDatabase = { + prepare(query: string): SqlStatement { + return env.DB.prepare(query) as unknown as SqlStatement; + }, + async batch(statements: SqlStatement[]): Promise[]> { + batchCount += 1; + if (batchCount === 2) { + await env.DB.prepare( + "UPDATE user_role_assignments SET role_id = 'role_builtin_viewer' WHERE user_id = ?" + ) + .bind(SURVIVOR) + .run(); + } + return env.DB.batch(statements as unknown as D1PreparedStatement[]) as Promise< + SqlResult[] + >; + }, + }; + + await expect( + mergeUsers(racingDatabase, { survivorId: SURVIVOR, loserId: LOSER }) + ).rejects.toThrow(); + expect(await getUserRow(LOSER)).not.toBeNull(); + expect( + await env.DB.prepare( + "SELECT COUNT(*) AS count FROM authorization_audit_events WHERE action = 'workspace.user_merged'" + ).first() + ).toEqual({ count: 0 }); + }); + it("rejects a missing survivor and a self-merge", async () => { await insertCanonicalUser({ id: LOSER, email: null }); diff --git a/packages/shared/src/rbac.test.ts b/packages/shared/src/rbac.test.ts index 7e3853a9cb..3520985231 100644 --- a/packages/shared/src/rbac.test.ts +++ b/packages/shared/src/rbac.test.ts @@ -9,6 +9,7 @@ import { resolveScopedPermission, replaceMemberRoleInputSchema, replaceMemberStatusInputSchema, + roleReferenceSchema, } from "./rbac"; describe("RBAC registry", () => { @@ -39,6 +40,25 @@ describe("RBAC registry", () => { ); }); + it("binds built-in role IDs and keys into one canonical identity", () => { + expect( + roleReferenceSchema.parse({ id: "role_builtin_owner", key: "owner", name: "Owner" }) + ).toEqual({ id: "role_builtin_owner", key: "owner", name: "Owner" }); + expect( + roleReferenceSchema.parse({ id: "role_custom_reviewer", key: null, name: "Reviewer" }) + ).toEqual({ id: "role_custom_reviewer", key: null, name: "Reviewer" }); + + expect(() => + roleReferenceSchema.parse({ id: "role_other", key: "owner", name: "Owner" }) + ).toThrow(); + expect(() => + roleReferenceSchema.parse({ id: "role_builtin_owner", key: null, name: "Custom" }) + ).toThrow(); + expect(() => + roleReferenceSchema.parse({ id: "role_builtin_member", key: "viewer", name: "Viewer" }) + ).toThrow(); + }); + it("contains unique, sorted permission identifiers", () => { expect(PERMISSION_IDS).toHaveLength(42); expect(new Set(PERMISSION_IDS).size).toBe(PERMISSION_IDS.length); diff --git a/packages/shared/src/rbac.ts b/packages/shared/src/rbac.ts index 5ebf1af74e..caad280481 100644 --- a/packages/shared/src/rbac.ts +++ b/packages/shared/src/rbac.ts @@ -25,6 +25,8 @@ export const BUILT_IN_ROLE_REGISTRY = { export type BuiltInRoleKey = keyof typeof BUILT_IN_ROLE_REGISTRY; /** Built-in role keys in canonical registry order. */ export const BUILT_IN_ROLE_KEYS = Object.keys(BUILT_IN_ROLE_REGISTRY) as BuiltInRoleKey[]; +/** Stable IDs reserved for system-defined roles. */ +export const BUILT_IN_ROLE_IDS = Object.values(BUILT_IN_ROLE_REGISTRY).map((role) => role.id); /** Canonical permission identifiers accepted by the RBAC policy and persistence layers. */ export const PERMISSION_IDS = [ @@ -155,21 +157,52 @@ export function isCustomRolePermission(permission: PermissionId): boolean { return permission !== "workspace.transfer_ownership"; } +const roleNameSchema = z.string().min(1); +const roleReferenceShape = { + id: z.string().min(1), + key: builtInRoleKeySchema.nullable(), + name: roleNameSchema, +}; + +function validateRoleIdentity( + role: { id: string; key: BuiltInRoleKey | null }, + context: z.RefinementCtx +): void { + if (role.key === null) { + if ((BUILT_IN_ROLE_IDS as readonly string[]).includes(role.id)) { + context.addIssue({ + code: "custom", + path: ["id"], + message: "Built-in role IDs require their canonical key", + }); + } + return; + } + if (role.id !== BUILT_IN_ROLE_REGISTRY[role.key].id) { + context.addIssue({ + code: "custom", + path: ["id"], + message: "Built-in role keys require their canonical ID", + }); + } +} + /** Validates the role identity embedded in authorization responses. */ export const roleReferenceSchema = z - .object({ - id: z.string().min(1), - key: builtInRoleKeySchema.nullable(), - name: z.string().min(1), - }) - .strict(); + .object(roleReferenceShape) + .strict() + .superRefine(validateRoleIdentity); /** Validates an administrative role view with effective grants and assignment count. */ -export const roleSummarySchema = roleReferenceSchema.extend({ - description: z.string().nullable(), - permissions: z.array(permissionIdSchema), - assignmentCount: z.number().int().nonnegative(), -}); +export const roleSummarySchema = z + .object({ + ...roleReferenceShape, + description: z.string().nullable(), + permissions: z.array(permissionIdSchema), + assignmentCount: z.number().int().nonnegative(), + }) + .strict() + .superRefine(validateRoleIdentity); /** Validates a user's role, suspension state, and currently effective permissions. */ export const effectiveAuthorizationSchema = z @@ -213,6 +246,8 @@ export const replaceMemberStatusInputSchema = z /** Administrative role data with effective grants and current assignment count. */ export type RoleSummary = z.infer; +/** A built-in or custom role identity with canonical ID/key pairing. */ +export type RoleReference = z.infer; /** The authorization state used to make permission decisions for a user. */ export type EffectiveAuthorization = z.infer; /** A workspace member and their current RBAC assignment state. */ diff --git a/scripts/bootstrap-workspace-owner.test.ts b/scripts/bootstrap-workspace-owner.test.ts index 58eefd90bc..5f9f9eeb30 100644 --- a/scripts/bootstrap-workspace-owner.test.ts +++ b/scripts/bootstrap-workspace-owner.test.ts @@ -1,7 +1,8 @@ import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; import { describe, it } from "node:test"; import { DatabaseSync } from "node:sqlite"; -import { buildBootstrapSql, parseArgs } from "./bootstrap-workspace-owner.ts"; +import { buildBootstrapSql, parseArgs, run } from "./bootstrap-workspace-owner.ts"; const USER_ID = "11111111111111111111111111111111"; const OTHER_USER_ID = "22222222222222222222222222222222"; @@ -308,3 +309,68 @@ describe("Owner bootstrap SQL", () => { assert.match(generated, /SELECT 1 FROM authorization_audit_events WHERE id = 'audit-exact'/); }); }); + +describe("Owner bootstrap orchestration", () => { + it("accepts only the execution response bound to this invocation's audit", async () => { + let calls = 0; + await run( + { database: "workspace", userId: USER_ID, execute: true }, + { + randomUUID: () => "audit-exact", + now: () => 123, + runWrangler: (_database, operation) => { + calls += 1; + if (operation[0] === "--command") { + return JSON.stringify([ + { success: true, results: [{ report: "preflight", status: "ready" }] }, + ]); + } + assert.equal(operation[0], "--file"); + const sqlPath = operation[1]; + assert.ok(sqlPath); + const generated = readFileSync(sqlPath, "utf8"); + assert.match(generated, /audit-exact/); + assert.match(generated, /123/); + return JSON.stringify([ + { + success: true, + results: [ + { + report: "postcondition", + status: "executed", + audit_written: 1, + }, + ], + }, + ]); + }, + } + ); + + assert.equal(calls, 2); + }); + + it("reports a concurrent winner instead of claiming this invocation completed", async () => { + await assert.rejects( + run( + { database: "workspace", userId: USER_ID, execute: true }, + { + randomUUID: () => "audit-loser", + now: () => 123, + runWrangler: (_database, operation) => + JSON.stringify([ + { + success: true, + results: [ + operation[0] === "--command" + ? { report: "preflight", status: "ready" } + : { report: "postcondition", status: "no-op", audit_written: 0 }, + ], + }, + ]), + } + ), + /ownership changed concurrently/ + ); + }); +}); diff --git a/scripts/bootstrap-workspace-owner.ts b/scripts/bootstrap-workspace-owner.ts index e0a1ac66b1..50976d0a6f 100644 --- a/scripts/bootstrap-workspace-owner.ts +++ b/scripts/bootstrap-workspace-owner.ts @@ -207,6 +207,15 @@ interface WranglerResult { success?: boolean; } +type WranglerRunner = (database: string, operation: readonly string[]) => string; + +/** Injectable side effects for deterministic bootstrap orchestration tests. */ +export interface BootstrapRunDependencies { + runWrangler?: WranglerRunner; + randomUUID?: () => string; + now?: () => number; +} + function reportRows(stdout: string): Array> { const parsed = JSON.parse(stdout) as WranglerResult[]; const rows = parsed.flatMap((result) => result.results ?? []).filter((row) => row.report); @@ -226,18 +235,22 @@ function runWrangler(database: string, operation: readonly string[]): string { return child.stdout; } -function preflight(database: string, userId: string): string { +function preflight(database: string, userId: string, runner: WranglerRunner): string { const sql = buildBootstrapSql({ userId, execute: false, auditId: "unused", now: 0 }); - const rows = reportRows(runWrangler(database, ["--command", sql])); + const rows = reportRows(runner(database, ["--command", sql])); const status = rows.find((row) => row.report === "preflight")?.status; if (typeof status !== "string") throw new Error("Wrangler returned no Owner bootstrap preflight"); return status; } /** Run the remote Owner bootstrap workflow and verify its postcondition. */ -export async function run(options: BootstrapCliOptions): Promise { +export async function run( + options: BootstrapCliOptions, + dependencies: BootstrapRunDependencies = {} +): Promise { + const runner = dependencies.runWrangler ?? runWrangler; console.error(`${options.execute ? "Executing" : "Dry-running"} Owner bootstrap on remote D1...`); - const status = preflight(options.database, options.userId); + const status = preflight(options.database, options.userId, runner); if (status === "refused") throw new Error("Owner bootstrap preflight was refused"); if (status === "no-op") return; if (!options.execute) { @@ -247,24 +260,31 @@ export async function run(options: BootstrapCliOptions): Promise { const directory = await mkdtemp(join(tmpdir(), "open-inspect-owner-bootstrap-")); const sqlPath = join(directory, "bootstrap.sql"); + let executionRows: Array>; try { + const auditId = dependencies.randomUUID?.() ?? crypto.randomUUID(); + const now = dependencies.now?.() ?? Date.now(); await writeFile( sqlPath, buildBootstrapSql({ userId: options.userId, execute: true, - auditId: crypto.randomUUID(), - now: Date.now(), + auditId, + now, }), { encoding: "utf8", mode: 0o600 } ); - runWrangler(options.database, ["--file", sqlPath]); + executionRows = reportRows(runner(options.database, ["--file", sqlPath])); } finally { await rm(directory, { recursive: true, force: true }); } - if (preflight(options.database, options.userId) !== "no-op") { - throw new Error("Owner bootstrap postcondition verification failed"); + const postcondition = executionRows.find((row) => row.report === "postcondition"); + if (postcondition?.status === "no-op") { + throw new Error("Owner bootstrap did not execute because ownership changed concurrently"); + } + if (postcondition?.status !== "executed" || Number(postcondition.audit_written) !== 1) { + throw new Error("Owner bootstrap execution did not prove its exact audit and assignment"); } console.error( "Owner bootstrap command completed; verify /health reports ownerAssignment=present." diff --git a/scripts/merge-split-users.ts b/scripts/merge-split-users.ts index fe1fcee8c6..aad4ce82d7 100644 --- a/scripts/merge-split-users.ts +++ b/scripts/merge-split-users.ts @@ -11,9 +11,8 @@ * * Dry-run is the default — it prints exact per-table counts and writes * nothing. Pass --execute to apply. The merge is idempotent: re-running a - * completed merge is a zero-count no-op, so a partially-applied run (the - * wrangler transport executes statements sequentially, not atomically) is - * repaired by running the script again. + * completed merge is a zero-count no-op. Execute mode submits the complete + * graph mutation as one atomic D1 SQL file. * * Usage: * node --experimental-transform-types scripts/merge-split-users.ts \ @@ -26,6 +25,9 @@ */ import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import type { SqlDatabase, SqlResult, @@ -109,17 +111,20 @@ class WranglerD1Database implements SqlDatabase { return statement; } - // Deviation from the SqlDatabase.batch contract: all statements go to D1 - // in one wrangler submission, but cross-statement atomicity is not - // guaranteed by this transport (scripts/d1-migrate.sh documents D1 - // multi-statement submissions as atomic; we deliberately do not rely on - // it). The merge tolerates this for every statement except the final email - // backfill, whose input row is deleted earlier in the batch: re-running - // repairs any other partial application, and the CLI prints a recovery - // record before executing to cover that one residual case. + // D1 executes one --file submission atomically. Keep this adapter aligned + // with SqlDatabase.batch rather than emulating a batch through independent + // or non-transactional command calls. async batch(statements: SqlStatement[]): Promise[]> { + if (statements.length === 0) return []; const rendered = statements.map((entry) => (entry as { render(): string }).render()); - return this.execute(rendered).map((result) => toSqlResult(result)); + const directory = mkdtempSync(join(tmpdir(), "open-inspect-user-merge-")); + const sqlPath = join(directory, "merge.sql"); + try { + writeFileSync(sqlPath, `${rendered.join(";\n")};\n`, { encoding: "utf8", mode: 0o600 }); + return this.executeOperation(["--file", sqlPath]).map((result) => toSqlResult(result)); + } finally { + rmSync(directory, { recursive: true, force: true }); + } } private execute(statements: string[]): WranglerQueryResult[] { @@ -127,6 +132,10 @@ class WranglerD1Database implements SqlDatabase { if (this.verbose) { for (const statement of statements) console.error(`[sql] ${statement}`); } + return this.executeOperation(["--command", statements.join(";\n")]); + } + + private executeOperation(operation: string[]): WranglerQueryResult[] { const args = [ "wrangler", "d1", @@ -134,8 +143,7 @@ class WranglerD1Database implements SqlDatabase { this.databaseName, this.remote ? "--remote" : "--local", "--json", - "--command", - statements.join(";\n"), + ...operation, ]; const child = spawnSync("npx", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); if (child.status !== 0) { @@ -211,25 +219,6 @@ async function main(): Promise { const options = parseArgs(process.argv.slice(2)); const db = new WranglerD1Database(options.database, !options.local, options.verbose); - if (options.execute) { - // Durable recovery record: the final email backfill is the one statement - // a re-run cannot repair, because its input (the loser row) is deleted by - // the statement before it. Everything needed to restore that step by hand - // is printed here, before anything executes. - const loserRecord = await db - .prepare(`SELECT id, email, email_verified FROM users WHERE id = ?`) - .bind(options.loserId) - .first<{ id: string; email: string | null; email_verified: number }>(); - console.error(`Recovery record (loser row): ${JSON.stringify(loserRecord)}`); - console.error( - "Retain this until the merge is verified. If a run fails partway, re-run it — " + - "that repairs every step except the final email backfill. If the survivor is " + - "left without the loser's email, restore it manually:\n" + - ` UPDATE users SET email = , email_verified = ` + - `WHERE id = '${options.survivorId}' AND email IS NULL;\n` - ); - } - const result = await mergeUsers(db, { survivorId: options.survivorId, loserId: options.loserId, diff --git a/terraform/d1/migrations/0071_rbac_foundation.sql b/terraform/d1/migrations/0071_rbac_foundation.sql index 4297c3da2e..5c093b8dcb 100644 --- a/terraform/d1/migrations/0071_rbac_foundation.sql +++ b/terraform/d1/migrations/0071_rbac_foundation.sql @@ -8,8 +8,18 @@ CREATE TABLE roles ( description TEXT, is_system INTEGER NOT NULL DEFAULT 0 CHECK (is_system IN (0, 1)), CHECK ( - (is_system = 1 AND key IN ('owner', 'administrator', 'member', 'viewer')) - OR (is_system = 0 AND key IS NULL) + (is_system = 1 AND key IS NOT NULL AND ( + (id = 'role_builtin_owner' AND key = 'owner') + OR (id = 'role_builtin_administrator' AND key = 'administrator') + OR (id = 'role_builtin_member' AND key = 'member') + OR (id = 'role_builtin_viewer' AND key = 'viewer') + )) + OR (is_system = 0 AND key IS NULL AND id NOT IN ( + 'role_builtin_owner', + 'role_builtin_administrator', + 'role_builtin_member', + 'role_builtin_viewer' + )) ) ); From 675a55449cd45760d2e5c74d3315e021b85eddd0 Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 23:02:57 -0700 Subject: [PATCH 4/6] fix(rbac): preserve merge batch result contract --- .github/workflows/ci.yml | 3 + package.json | 1 + packages/control-plane/src/db/user-merge.ts | 4 +- .../test/integration/user-merge.test.ts | 17 ++++++ scripts/merge-split-users.test.ts | 51 ++++++++++++++++ scripts/merge-split-users.ts | 60 ++++++++++++------- 6 files changed, 111 insertions(+), 25 deletions(-) create mode 100644 scripts/merge-split-users.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f70ac230d1..e629527663 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,9 @@ jobs: - name: Test Owner bootstrap CLI run: npm run test:rbac-bootstrap-owner + - name: Test user merge CLI + run: npm run test:user-merge-cli + - name: Check Prettier formatting run: npm run format:check diff --git a/package.json b/package.json index 5c7a63432f..5e6c2bbeec 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "test": "npm run test --workspaces --if-present", "test:lint-complexity": "node --test scripts/lint-complexity-message.test.mjs", "test:rbac-bootstrap-owner": "node --experimental-transform-types --test scripts/bootstrap-workspace-owner.test.ts", + "test:user-merge-cli": "node --experimental-transform-types --test scripts/merge-split-users.test.ts", "test:coverage": "npm run test:coverage --workspaces --if-present", "test:integration": "npm run test:integration --workspaces --if-present", "typecheck": "npm run build -w @open-inspect/shared && npm run typecheck --workspaces --if-present", diff --git a/packages/control-plane/src/db/user-merge.ts b/packages/control-plane/src/db/user-merge.ts index 95e3d190cc..da626a47d5 100644 --- a/packages/control-plane/src/db/user-merge.ts +++ b/packages/control-plane/src/db/user-merge.ts @@ -319,7 +319,7 @@ export async function mergeUsers( if (survivorRole && loserRole && survivorRole.role_id !== loserRole.role_id) { throw new UserMergeError("Resolve conflicting user roles before merging"); } - if (survivor.suspended_at !== loser.suspended_at) { + if ((survivor.suspended_at === null) !== (loser.suspended_at === null)) { throw new UserMergeError("Resolve conflicting user suspension states before merging"); } if (loserRole?.role_key === "owner" && survivor.suspended_at !== null) { @@ -377,7 +377,7 @@ export async function mergeUsers( JOIN roles role ON role.id = loser_assignment.role_id WHERE survivor.id = ? AND survivor_assignment.role_id = loser_assignment.role_id - AND survivor.suspended_at IS loser.suspended_at + AND (survivor.suspended_at IS NULL) = (loser.suspended_at IS NULL) AND (role.key IS NULL OR role.key <> 'owner' OR survivor.suspended_at IS NULL) ) THEN ? ELSE NULL END, 'user-merge', 'service', 'control-plane', diff --git a/packages/control-plane/test/integration/user-merge.test.ts b/packages/control-plane/test/integration/user-merge.test.ts index 75e8d66eeb..1821b115f0 100644 --- a/packages/control-plane/test/integration/user-merge.test.ts +++ b/packages/control-plane/test/integration/user-merge.test.ts @@ -455,6 +455,23 @@ describe("mergeUsers", () => { expect(await getUserRow(LOSER)).not.toBeNull(); }); + it("merges two suspended users even when their suspension timestamps differ", async () => { + await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); + await insertCanonicalUser({ id: LOSER, email: null }); + await env.DB.prepare("UPDATE users SET suspended_at = 123 WHERE id = ?").bind(SURVIVOR).run(); + await env.DB.prepare("UPDATE users SET suspended_at = 456 WHERE id = ?").bind(LOSER).run(); + + await expect( + mergeUsers(env.DB, { survivorId: SURVIVOR, loserId: LOSER }) + ).resolves.toMatchObject({ + counts: { usersDeleted: 1 }, + }); + expect(await getUserRow(LOSER)).toBeNull(); + expect( + await env.DB.prepare("SELECT suspended_at FROM users WHERE id = ?").bind(SURVIVOR).first() + ).toEqual({ suspended_at: 123 }); + }); + it("rolls back when role invariants change after preflight", async () => { await insertCanonicalUser({ id: SURVIVOR, email: "person@example.com" }); await insertCanonicalUser({ id: LOSER, email: null }); diff --git a/scripts/merge-split-users.test.ts b/scripts/merge-split-users.test.ts new file mode 100644 index 0000000000..e5e4c1f3a7 --- /dev/null +++ b/scripts/merge-split-users.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { WranglerD1Database, type WranglerRunner } from "./merge-split-users.ts"; + +function result(results: Record[], changes = 0): string { + return JSON.stringify([{ success: true, results, meta: { changes } }]); +} + +describe("Wrangler user-merge database adapter", () => { + it("uses the result-bearing command batch and preserves positional results", async () => { + let invokedArgs: string[] = []; + const runner: WranglerRunner = (args) => { + invokedArgs = args; + return { + status: 0, + stderr: "", + stdout: JSON.stringify([ + { success: true, results: [{ role_id: "survivor-role" }], meta: { changes: 0 } }, + { success: true, results: [{ role_id: "loser-role" }], meta: { changes: 0 } }, + ]), + }; + }; + const database = new WranglerD1Database("workspace", true, false, runner); + + const results = await database.batch([ + database.prepare("SELECT role_id FROM assignments WHERE user_id = ?").bind("survivor"), + database.prepare("SELECT role_id FROM assignments WHERE user_id = ?").bind("loser"), + ]); + + assert.deepEqual( + results.map((entry) => entry.results[0]), + [{ role_id: "survivor-role" }, { role_id: "loser-role" }] + ); + assert.ok(invokedArgs.includes("--command")); + assert.ok(!invokedArgs.includes("--file")); + }); + + it("fails loudly if Wrangler collapses a batch into one aggregate result", async () => { + const runner: WranglerRunner = () => ({ + status: 0, + stderr: "", + stdout: result([{ "Total queries executed": 2 }]), + }); + const database = new WranglerD1Database("workspace", true, false, runner); + + await assert.rejects( + database.batch([database.prepare("SELECT 1"), database.prepare("SELECT 2")]), + /returned 1 results for 2 batched statements/ + ); + }); +}); diff --git a/scripts/merge-split-users.ts b/scripts/merge-split-users.ts index aad4ce82d7..63306815fc 100644 --- a/scripts/merge-split-users.ts +++ b/scripts/merge-split-users.ts @@ -12,7 +12,7 @@ * Dry-run is the default — it prints exact per-table counts and writes * nothing. Pass --execute to apply. The merge is idempotent: re-running a * completed merge is a zero-count no-op. Execute mode submits the complete - * graph mutation as one atomic D1 SQL file. + * graph mutation as one result-bearing D1 batch. * * Usage: * node --experimental-transform-types scripts/merge-split-users.ts \ @@ -25,9 +25,8 @@ */ import { spawnSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; import type { SqlDatabase, SqlResult, @@ -45,6 +44,19 @@ interface WranglerQueryResult { meta?: { changes?: number }; } +/** Minimal process result used to test Wrangler orchestration without spawning. */ +export interface WranglerProcessResult { + status: number | null; + stdout: string; + stderr: string; +} + +/** Injectable runner for Wrangler CLI orchestration tests. */ +export type WranglerRunner = (args: string[]) => WranglerProcessResult; + +const runWrangler: WranglerRunner = (args) => + spawnSync("npx", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + function sqlLiteral(value: unknown): string { if (value === null || value === undefined) return "NULL"; if (typeof value === "number") { @@ -76,11 +88,12 @@ function inlineParams(sql: string, params: unknown[]): string { return rendered; } -class WranglerD1Database implements SqlDatabase { +export class WranglerD1Database implements SqlDatabase { constructor( private readonly databaseName: string, private readonly remote: boolean, - private readonly verbose: boolean + private readonly verbose: boolean, + private readonly runner: WranglerRunner = runWrangler ) {} prepare(query: string): SqlStatement { @@ -111,20 +124,18 @@ class WranglerD1Database implements SqlDatabase { return statement; } - // D1 executes one --file submission atomically. Keep this adapter aligned - // with SqlDatabase.batch rather than emulating a batch through independent - // or non-transactional command calls. + // Remote --command sends semicolon-separated statements to D1's /query + // batch API. D1 executes the batch transactionally and Wrangler preserves + // one positional result (including meta.changes) per statement. async batch(statements: SqlStatement[]): Promise[]> { - if (statements.length === 0) return []; const rendered = statements.map((entry) => (entry as { render(): string }).render()); - const directory = mkdtempSync(join(tmpdir(), "open-inspect-user-merge-")); - const sqlPath = join(directory, "merge.sql"); - try { - writeFileSync(sqlPath, `${rendered.join(";\n")};\n`, { encoding: "utf8", mode: 0o600 }); - return this.executeOperation(["--file", sqlPath]).map((result) => toSqlResult(result)); - } finally { - rmSync(directory, { recursive: true, force: true }); + const results = this.execute(rendered); + if (results.length !== statements.length) { + throw new Error( + `Wrangler returned ${results.length} results for ${statements.length} batched statements` + ); } + return results.map((result) => toSqlResult(result)); } private execute(statements: string[]): WranglerQueryResult[] { @@ -145,7 +156,7 @@ class WranglerD1Database implements SqlDatabase { "--json", ...operation, ]; - const child = spawnSync("npx", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + const child = this.runner(args); if (child.status !== 0) { throw new Error(`wrangler d1 execute failed:\n${child.stderr || child.stdout}`); } @@ -247,8 +258,11 @@ async function main(): Promise { } } -main().catch((error: unknown) => { - const message = error instanceof UserMergeError ? error.message : String(error); - console.error(message); - process.exitCode = 1; -}); +const invokedPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : null; +if (invokedPath === import.meta.url) { + main().catch((error: unknown) => { + const message = error instanceof UserMergeError ? error.message : String(error); + console.error(message); + process.exitCode = 1; + }); +} From d41141d3fe6acaf4c861f2b195b5932195151fdf Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 23:38:58 -0700 Subject: [PATCH 5/6] fix: address RBAC review feedback --- .../src/auth/identity-enforcement.test.ts | 73 ++++++++++--------- .../src/auth/identity-enforcement.ts | 53 +++++--------- .../src/router.create-session.test.ts | 19 +++-- .../control-plane/src/router.policy.test.ts | 39 +++++++++- .../src/router.scm-credentials.test.ts | 59 ++++++++++++++- .../src/router.session-prompt.test.ts | 2 +- .../src/router.spawn-child.test.ts | 63 ++++++++++++---- packages/control-plane/src/router.ts | 40 ++++------ packages/control-plane/src/routes/rbac.ts | 1 + .../src/routes/session-child-spawn.ts | 7 ++ .../src/routes/session-create.ts | 25 ++----- .../routes/session-target-authorization.ts | 37 ++++++++++ packages/control-plane/src/routes/shared.ts | 26 +++---- .../src/webhooks/automation-event.ts | 8 +- packages/control-plane/src/webhooks/github.ts | 8 +- .../test/integration/service-auth.test.ts | 49 +++++++++++++ .../linear-bot/src/webhook-handler.test.ts | 14 ++-- packages/linear-bot/src/webhook-handler.ts | 49 ++++++++++--- 18 files changed, 383 insertions(+), 189 deletions(-) create mode 100644 packages/control-plane/src/routes/session-target-authorization.ts diff --git a/packages/control-plane/src/auth/identity-enforcement.test.ts b/packages/control-plane/src/auth/identity-enforcement.test.ts index e33bec55b7..466f4d19e6 100644 --- a/packages/control-plane/src/auth/identity-enforcement.test.ts +++ b/packages/control-plane/src/auth/identity-enforcement.test.ts @@ -4,7 +4,6 @@ import { applyIdentityEnforcement, deriveIdentity, mayAttachCallbackContext, - requireEventPoster, resolveCanonicalUserId, } from "./identity-enforcement"; import type { Principal, ResolvedIdentity } from "./principal"; @@ -225,6 +224,43 @@ describe("resolveCanonicalUserId", () => { ); }); + it("rejects when actor enrichment relinks to a different authorized user", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const ctx = createCtx(SLACK_BOT_PRINCIPAL); + ctx.authorization = { + userId: "canon-provisional", + suspendedAt: null, + permissions: ["sessions.create"], + role: { id: "role-member", key: "member", name: "Member" }, + }; + const result = await resolveCanonicalUserId( + { + resolveOrCreateUser: vi.fn(async () => ({ id: "canon-existing" })), + } as unknown as UserStore, + ctx, + { + participantUserId: "slack:U0123", + canonicalUserId: null, + actor: SLACK_ACTOR, + spawnSource: "slack-bot", + }, + display + ); + + expect(result).toBeInstanceOf(Response); + expect((result as Response).status).toBe(409); + await expect((result as Response).json()).resolves.toMatchObject({ + code: "actor_identity_changed", + }); + expect(loggedEvents(warn)).toContainEqual( + expect.objectContaining({ + event: "identity.mismatch_rejected", + expected: "canon-provisional", + actual: "canon-existing", + }) + ); + }); + it("rejects a canonical identity whose workspace access is suspended", async () => { const ctx = createCtx(USER_PRINCIPAL); const statement = { @@ -304,38 +340,3 @@ describe("mayAttachCallbackContext", () => { expect(mayAttachCallbackContext(createCtx(undefined))).toBe(false); }); }); - -describe("requireEventPoster", () => { - const GITHUB_BOT: Principal = { - kind: "service", - service: "github-bot", - actor: null, - }; - - it("logs and 401s a mismatched poster", () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); - const rejection = requireEventPoster(createCtx(GITHUB_BOT), "slack"); - expect(rejection?.status).toBe(401); - const mismatch = loggedEvents(warn).find((e) => e.event === "identity.mismatch_rejected"); - expect(mismatch).toMatchObject({ - route: "internal-slack-event", - field: "service", - expected: "slack-bot", - actual: "github-bot", - }); - }); - - it("401s non-service principals — the gate never falls open", () => { - expect(requireEventPoster(createCtx(USER_PRINCIPAL), "slack")?.status).toBe(401); - expect(requireEventPoster(createCtx(undefined), "slack")?.status).toBe(401); - expect( - requireEventPoster(createCtx({ kind: "sandbox", sessionId: "s1" }), "sentry")?.status - ).toBe(401); - }); - - it("passes the matching bot and exempt sources", () => { - expect(requireEventPoster(createCtx(SLACK_BOT_PRINCIPAL), "slack")).toBeNull(); - // Sentry events are not bot-posted: explicit exemption for any service. - expect(requireEventPoster(createCtx(GITHUB_BOT), "sentry")).toBeNull(); - }); -}); diff --git a/packages/control-plane/src/auth/identity-enforcement.ts b/packages/control-plane/src/auth/identity-enforcement.ts index 29db52541c..ee0a945528 100644 --- a/packages/control-plane/src/auth/identity-enforcement.ts +++ b/packages/control-plane/src/auth/identity-enforcement.ts @@ -9,14 +9,13 @@ * can run the steps out of order or skip one. */ -import type { AutomationEventSource } from "@open-inspect/shared/triggers"; import type { SpawnSource } from "@open-inspect/shared/types/sessions"; import type { ServiceName } from "@open-inspect/shared/service-auth"; import { createLogger } from "./../logger"; import { CALLBACK_DESTINATIONS } from "./service/callback-signing"; import type { Principal, ResolvedIdentity } from "./principal"; import type { UserStore } from "../db/user-store"; -import { error, type RequestContext } from "../routes/shared"; +import { error, json, type RequestContext } from "../routes/shared"; const logger = createLogger("identity-enforcement"); @@ -235,6 +234,22 @@ export async function resolveCanonicalUserId( providerEmail: display.email, avatarUrl: display.avatarUrl, }); + if (ctx.authorization && user.id !== ctx.authorization.userId) { + logMismatchRejected( + "actor-resolution", + "canonicalUserId", + ctx.authorization.userId, + user.id, + ctx + ); + return json( + { + error: "Actor identity changed; retry the request", + code: "actor_identity_changed", + }, + 409 + ); + } return requireActive(user.id); } catch (e) { logger.error("Failed to resolve verified actor identity", { @@ -277,37 +292,3 @@ function logMismatchRejected( trace_id: ctx.trace_id, }); } - -/** - * The bot service allowed to post each normalized automation event source. - * `null` marks sources that are not bot-posted (sentry/webhook arrive on the - * CP's own public webhook surface; linear posts no normalized events today) - * — an explicit exemption, not a missing row. - */ -const EVENT_SOURCE_SERVICE: Record = { - slack: "slack-bot", - github: "github-bot", - linear: null, - sentry: null, - webhook: null, -}; - -/** - * Gate for the internal normalized automation-event endpoints: the poster - * must be a service principal (401 otherwise), and per-service sources - * accept only the source's own bot. Sources with a null row arrive via the - * CP's own public webhook surface, so any service may forward them. - */ -export function requireEventPoster( - ctx: RequestContext, - source: AutomationEventSource -): Response | null { - const principal = ctx.principal; - if (principal?.kind !== "service") { - return error("Unauthorized", 401); - } - const expected = EVENT_SOURCE_SERVICE[source]; - if (expected === null || principal.service === expected) return null; - logMismatchRejected(`internal-${source}-event`, "service", expected, principal.service, ctx); - return error("Unauthorized", 401); -} diff --git a/packages/control-plane/src/router.create-session.test.ts b/packages/control-plane/src/router.create-session.test.ts index 908eff8bb5..1e27d75a6a 100644 --- a/packages/control-plane/src/router.create-session.test.ts +++ b/packages/control-plane/src/router.create-session.test.ts @@ -139,11 +139,7 @@ describe("handleCreateSession D1 ordering", () => { ): Record { const statement = { bind: vi.fn(() => statement), - first: vi - .fn() - .mockResolvedValueOnce({ suspended_at: null, assigned: 1 }) - .mockResolvedValueOnce({ active: 1 }) - .mockResolvedValue(null), + first: vi.fn(async () => null), all: vi.fn(async () => ({ results: [] })), run: vi.fn(async () => ({ meta: { changes: 0 } })), }; @@ -180,6 +176,15 @@ describe("handleCreateSession D1 ordering", () => { }; return permissionStatement; } + if (sql.includes("suspended_at IS NULL")) { + const activeStatement = { + bind: vi.fn(() => activeStatement), + first: vi.fn(async () => ({ active: 1 })), + all: vi.fn(async () => ({ results: [] })), + run: vi.fn(async () => ({ meta: { changes: 0 } })), + }; + return activeStatement; + } return statement; }), batch: vi.fn(), @@ -519,7 +524,7 @@ describe("handleCreateSession D1 ordering", () => { vi.mocked(SessionIndexStore).mockImplementation(function () { return { create } as never; }); - const resolveOrCreateUser = vi.fn(async () => ({ id: "user-9" })); + const resolveOrCreateUser = vi.fn(async () => ({ id: "user-1" })); vi.mocked(UserStore).mockImplementation(function () { return { getIdentity: async () => null, @@ -545,7 +550,7 @@ describe("handleCreateSession D1 ordering", () => { providerEmail: "ada@example.com", avatarUrl: "https://avatars.example.com/ada.png", }); - expect(create).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-9" })); + expect(create).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-1" })); expect(initFetch).toHaveBeenCalledOnce(); }); diff --git a/packages/control-plane/src/router.policy.test.ts b/packages/control-plane/src/router.policy.test.ts index 56764d958a..934e7e5721 100644 --- a/packages/control-plane/src/router.policy.test.ts +++ b/packages/control-plane/src/router.policy.test.ts @@ -35,7 +35,7 @@ describe("route policy table", () => { } else if (authorization.kind === "authenticated" || authorization.kind === "active-self") { expect(authentication).toBe("user"); } else if (authorization.kind === "service") { - expect(authentication).toBe("user-or-service"); + expect(authentication).toBe("service"); expect(authorization.services.length).toBeGreaterThan(0); } else if (authorization.kind === "active-global") { expect(["user", "user-or-service"]).toContain(authentication); @@ -155,6 +155,33 @@ describe("route policy table", () => { kind: "service", services: ["github-bot"], }); + expect(routeFor("POST", "/internal/github-event")?.authentication).toEqual({ + kind: "service", + }); + expect(routeFor("POST", "/internal/slack-event")?.authentication).toEqual({ + kind: "service", + }); + }); + + it("returns 400 for a malformed percent-encoded role ID before querying D1", async () => { + const path = "/roles/%E0%A4%A"; + const route = routeFor("GET", path); + const match = path.match(route!.pattern)!; + const prepare = vi.fn(); + + const response = await route!.handler( + new Request(`https://test.local${path}`), + {} as never, + match, + { + principal: { kind: "user", userId: "user-1" }, + db: { prepare }, + } as never + ); + + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ error: "Invalid role ID" }); + expect(prepare).not.toHaveBeenCalled(); }); it.each([ @@ -164,7 +191,7 @@ describe("route policy table", () => { ["POST", "/automations/automation-1/resume", "manage"], ["POST", "/automations/automation-1/trigger", "trigger"], ["POST", "/automations/automation-1/regenerate-key", "manage"], - ])("declares typed automation admission for %s %s", (method, path, operation) => { + ])("declares automation ownership authorization for %s %s", (method, path, operation) => { expect(routeFor(method, path)?.authorization).toMatchObject({ kind: "active-user", allOf: [{ kind: "automation", operation, automationIdParam: "id" }], @@ -354,7 +381,7 @@ describe("route policy dispatch ordering", () => { }); }); - it("keeps health live and private when the RBAC lookup fails", async () => { + it("keeps health dependency-free when D1 is unavailable", async () => { const testEnv = env("github"); testEnv.DB.prepare = vi.fn(() => { throw new Error("D1 unavailable"); @@ -370,7 +397,6 @@ describe("route policy dispatch ordering", () => { await expect(response.json()).resolves.toEqual({ status: "healthy", service: "open-inspect-control-plane", - rbac: { ownerAssignment: "unknown" }, }); }); @@ -404,6 +430,10 @@ describe("route principal policy", () => { it.each([ [{ kind: "web-service" } as const, { kind: "service", service: "web", actor: null } as const], [{ kind: "user" } as const, { kind: "user", userId: "user-1" } as const], + [ + { kind: "service" } as const, + { kind: "service", service: "github-bot", actor: null } as const, + ], [ { kind: "user-or-service" } as const, { kind: "service", service: "linear-bot", actor: null } as const, @@ -424,6 +454,7 @@ describe("route principal policy", () => { { kind: "service", service: "linear-bot", actor: null } as const, 403, ], + [{ kind: "service" } as const, { kind: "user", userId: "user-1" } as const, 403], ])("rejects mismatched principals for %o", (authentication, principal, status) => { expect(enforceRoutePrincipal(authentication, principal)?.status).toBe(status); }); diff --git a/packages/control-plane/src/router.scm-credentials.test.ts b/packages/control-plane/src/router.scm-credentials.test.ts index 9862a58eac..85e8ddde33 100644 --- a/packages/control-plane/src/router.scm-credentials.test.ts +++ b/packages/control-plane/src/router.scm-credentials.test.ts @@ -10,7 +10,7 @@ function routeFor(method: string, path: string) { return routes.find((route) => route.method === method && route.pattern.test(path)); } -function createEnv() { +function createEnv(options?: { actorAuthorized?: boolean }) { const fetch = vi.fn(async (request: Request) => { if (new URL(request.url).pathname === "/internal/verify-sandbox-token") { const body = (await request.json()) as { token?: string }; @@ -35,7 +35,42 @@ function createEnv() { SCM_PROVIDER: "gitlab", GITLAB_ACCESS_TOKEN: "glpat-test", DB: { - prepare: vi.fn(() => statement), + prepare: vi.fn((sql: string) => { + if (options?.actorAuthorized && sql.includes("FROM user_identities")) { + const identityStatement = { + bind: vi.fn(() => identityStatement), + first: vi.fn(async () => ({ + id: "identity-linear-u1", + user_id: "user-1", + provider: "linear", + provider_user_id: "U1", + provider_login: null, + provider_email: null, + provider_issuer: null, + created_at: 1, + })), + }; + return identityStatement; + } + if ( + options?.actorAuthorized && + sql.includes("FROM users u") && + sql.includes("user_role_assignments") + ) { + const authorizationStatement = { + bind: vi.fn(() => authorizationStatement), + first: vi.fn(async () => ({ + user_id: "user-1", + suspended_at: null, + role_id: "role_builtin_member", + role_key: "member", + role_name: "Member", + })), + }; + return authorizationStatement; + } + return statement; + }), batch: vi.fn(), exec: vi.fn(), dump: vi.fn(), @@ -234,6 +269,26 @@ describe("SCM credentials router provider gate", () => { expect(fetch).not.toHaveBeenCalled(); }); + it("returns the provider gate after authorizing an actor on a GitHub-only route", async () => { + const { env, fetch } = createEnv({ actorAuthorized: true }); + + const response = await handleRequest( + await signedServiceRequest("https://test.local/sessions/session-1/pr", { + method: "POST", + service: "linear-bot", + actor: "linear:U1", + }), + env as never, + TEST_BACKGROUND_TASK_CONTEXT + ); + + expect(response.status).toBe(501); + await expect(response.json()).resolves.toEqual({ + error: "SCM provider 'gitlab' is not implemented in this deployment.", + }); + expect(fetch).not.toHaveBeenCalled(); + }); + it("allows GitLab deployments to reach the SCM-independent read-state route", async () => { expect(routeFor("PATCH", "/sessions/session-1/read-state")?.supportedScmProviders).toBe("all"); }); diff --git a/packages/control-plane/src/router.session-prompt.test.ts b/packages/control-plane/src/router.session-prompt.test.ts index aed5096c7a..88fffb4996 100644 --- a/packages/control-plane/src/router.session-prompt.test.ts +++ b/packages/control-plane/src/router.session-prompt.test.ts @@ -62,7 +62,7 @@ function createEnv(sessionFetch: ReturnType): Record { const makeStore = ( parentUserId: string | null = null, - context: typeof spawnContext = spawnContext + context: typeof spawnContext = spawnContext, + environmentId: string | null = "env_parent" ) => ({ get: vi.fn().mockResolvedValue({ userId: parentUserId, repoOwner: context.repoOwner, repoName: context.repoName, - environmentId: "env_parent", + environmentId, }), getSpawnDepth: vi.fn().mockResolvedValue(0), getCompleteProviderAuth: vi.fn().mockResolvedValue(parentProviderAuth), @@ -186,7 +187,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { ); } - function makeSuccessfulEnv(context: TestSpawnContext) { + function makeSuccessfulEnv(context: TestSpawnContext, permissions?: string[]) { const parentStub: DurableObjectStub = { fetch: vi.fn(async () => Response.json(context)), } as never; @@ -205,7 +206,7 @@ describe("handleSpawnChild prompt enqueue handling", () => { env: { ...TEST_SERVICE_SECRETS, SCM_PROVIDER: "github", - DB: authorizedDb(), + DB: authorizedDb(permissions), SESSION: { idFromName: (name: string) => name, get: (id: string) => (id === parentId ? parentStub : childStub), @@ -214,6 +215,44 @@ describe("handleSpawnChild prompt enqueue handling", () => { }; } + it("rejects a repository-backed child when the actor cannot use repositories", async () => { + const store = makeStore(null, spawnContext, null); + vi.mocked(SessionIndexStore).mockImplementation(function () { + return store as never; + }); + const { env } = makeSuccessfulEnv(spawnContext, ["sessions.create", "sessions.collaborate"]); + + const response = await makeRequest(env); + + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ + code: "permission_required", + permission: "repositories.use", + }); + expect(store.create).not.toHaveBeenCalled(); + }); + + it("rejects an environment-backed child when the actor cannot use environments", async () => { + const store = makeStore(); + vi.mocked(SessionIndexStore).mockImplementation(function () { + return store as never; + }); + const { env } = makeSuccessfulEnv(spawnContext, [ + "sessions.create", + "sessions.collaborate", + "repositories.use", + ]); + + const response = await makeRequest(env); + + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ + code: "permission_required", + permission: "environments.use", + }); + expect(store.create).not.toHaveBeenCalled(); + }); + async function getInitBody(childStub: DurableObjectStub) { const initRequest = vi.mocked(childStub.fetch).mock.calls.find((call) => { const request = call[0] as Request; @@ -876,7 +915,9 @@ describe("handleSpawnChild prompt enqueue handling", () => { expect(store.updateStatus).toHaveBeenCalledWith(createdChildId, "failed"); }); }); -function authorizedDb() { +function authorizedDb( + permissions = ["sessions.create", "repositories.use", "environments.use", "sessions.collaborate"] +) { return { prepare: vi.fn((sql: string) => { const statement = { @@ -886,19 +927,15 @@ function authorizedDb() { ? { user_id: "canonical-user-123", suspended_at: null, - role_id: "role-1", - role_key: "member", - role_name: "Member", + role_id: "role_custom_spawn_test", + role_key: null, + role_name: "Spawn Test", } : null ), all: vi.fn(async () => ({ results: sql.includes("FROM role_permissions") - ? [ - { permission_id: "sessions.create" }, - { permission_id: "repositories.use" }, - { permission_id: "sessions.collaborate" }, - ] + ? permissions.map((permission_id) => ({ permission_id })) : [], })), }; diff --git a/packages/control-plane/src/router.ts b/packages/control-plane/src/router.ts index 428ec9a81b..5435777417 100644 --- a/packages/control-plane/src/router.ts +++ b/packages/control-plane/src/router.ts @@ -302,6 +302,9 @@ export function enforceRoutePrincipal( if (authentication.kind === "user" && principal.kind !== "user") { return error("Human user authentication required", 403); } + if (authentication.kind === "service" && principal.kind !== "service") { + return error("Service authentication required", 403); + } return null; } @@ -382,11 +385,11 @@ function enforceServiceRouteAuthorization( ctx: RequestContext ): Response | null { const principal = ctx.principal; - if (principal?.kind !== "service") return null; - if (route.authentication.kind === "web-service" && principal.service === "web") return null; - const authorization = route.authorization; if (authorization.kind === "service") { + if (principal?.kind !== "service") { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } if (!authorization.services.some((service) => service === principal.service)) { return json({ error: "Forbidden", code: "service_capability_required" }, 403); } @@ -395,6 +398,8 @@ function enforceServiceRouteAuthorization( } return null; } + if (principal?.kind !== "service") return null; + if (route.authentication.kind === "web-service" && principal.service === "web") return null; if ( (authorization.kind !== "active-user" && authorization.kind !== "active-global") || authorization.service.kind === "deny" @@ -483,7 +488,6 @@ async function enforceAutomationRequirement( ); } - ctx.automationAdmission = { automation }; return null; } catch { return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); @@ -525,28 +529,11 @@ export const routes: Route[] = [ method: "GET", pattern: parsePattern("/health"), authorization: NO_AUTHORIZATION, - handler: async (_request, _env, _match, ctx) => { - let ownerAssignment: "present" | "missing" | "unknown"; - try { - const owner = await ctx.db - .prepare( - `SELECT 1 AS complete FROM users u - JOIN user_role_assignments ura ON ura.user_id = u.id - JOIN roles r ON r.id = ura.role_id - WHERE r.key = 'owner' AND u.suspended_at IS NULL - LIMIT 1` - ) - .first(); - ownerAssignment = owner ? "present" : "missing"; - } catch { - ownerAssignment = "unknown"; - } - return json({ + handler: async () => + json({ status: "healthy", service: "open-inspect-control-plane", - rbac: { ownerAssignment }, - }); - }, + }), }, ...browserAuthRoutes, @@ -702,7 +689,10 @@ export async function handleRequest( : error("Unauthorized: Invalid session path", 401); } else { const authResult = await authenticate(request, env, ctx, { - webService: authentication.kind === "web-service" ? "service" : "user", + webService: + authentication.kind === "web-service" || authentication.kind === "service" + ? "service" + : "user", }); if (isAuthError(authResult)) { diff --git a/packages/control-plane/src/routes/rbac.ts b/packages/control-plane/src/routes/rbac.ts index 01ed454476..33a2fcb3ea 100644 --- a/packages/control-plane/src/routes/rbac.ts +++ b/packages/control-plane/src/routes/rbac.ts @@ -64,6 +64,7 @@ async function handleGetRole( const role = await service.getRole(decodeURIComponent(match.groups!.id)); return role ? json(role) : error("Role not found", 404); } catch (cause) { + if (cause instanceof URIError) return error("Invalid role ID", 400); return rbacErrorResponse(cause); } } diff --git a/packages/control-plane/src/routes/session-child-spawn.ts b/packages/control-plane/src/routes/session-child-spawn.ts index ce0541ebf0..1258edc527 100644 --- a/packages/control-plane/src/routes/session-child-spawn.ts +++ b/packages/control-plane/src/routes/session-child-spawn.ts @@ -39,6 +39,7 @@ import { } from "./shared"; import { sessionRoute, type SessionRouteContext } from "./session-route"; import { DEFAULT_BASE_BRANCH } from "../repos/default-branch"; +import { authorizeSessionTarget } from "./session-target-authorization"; const logger = createLogger("router:session-child-spawn"); const MAX_SPAWN_DEPTH = 2; @@ -145,6 +146,12 @@ async function handleSpawnChild( } } + const targetAuthorizationError = authorizeSessionTarget(ctx, { + environmentId: parentEnvironmentId, + hasRepository: Boolean(parentRepoOwner && parentRepoName), + }); + if (targetAuthorizationError) return targetAuthorizationError; + let enabledModels: ValidModel[]; try { enabledModels = await getEffectiveEnabledModels(ctx.db); diff --git a/packages/control-plane/src/routes/session-create.ts b/packages/control-plane/src/routes/session-create.ts index a9adc0f757..550f885d04 100644 --- a/packages/control-plane/src/routes/session-create.ts +++ b/packages/control-plane/src/routes/session-create.ts @@ -17,6 +17,7 @@ import { resolveManagedSkills, SkillResolutionError } from "../session/skill-res import type { Env } from "../types"; import { resolveSessionProviderAuth } from "../session/provider-account-resolution"; import { ProviderAccountSelectionPolicyError } from "../model-provider-accounts/selection-policy"; +import { authorizeSessionTarget } from "./session-target-authorization"; import { normalizeOptionalRepositoryPair, RepositoryPairValidationError, @@ -66,25 +67,11 @@ async function handleCreateSession( throw e; } - if (ctx.principal?.kind === "user" || ctx.principal?.kind === "service") { - const authorization = ctx.authorization; - if (!authorization) return json({ error: "Authorization unavailable" }, 503); - if (body.environmentId && !authorization.permissions.includes("environments.use")) { - return json( - { error: "Forbidden", code: "permission_required", permission: "environments.use" }, - 403 - ); - } - if ( - (repositoryContext || body.repositories) && - !authorization.permissions.includes("repositories.use") - ) { - return json( - { error: "Forbidden", code: "permission_required", permission: "repositories.use" }, - 403 - ); - } - } + const targetAuthorizationError = authorizeSessionTarget(ctx, { + environmentId: body.environmentId, + hasRepository: Boolean(repositoryContext || body.repositories), + }); + if (targetAuthorizationError) return targetAuthorizationError; // Validate branch names if provided (defense in depth) if (body.branch && !BRANCH_NAME_PATTERN.test(body.branch)) { diff --git a/packages/control-plane/src/routes/session-target-authorization.ts b/packages/control-plane/src/routes/session-target-authorization.ts new file mode 100644 index 0000000000..db1923185f --- /dev/null +++ b/packages/control-plane/src/routes/session-target-authorization.ts @@ -0,0 +1,37 @@ +import type { PermissionId } from "@open-inspect/shared/rbac"; +import { serviceAllowsPermission } from "../authorization/service-permissions"; +import { json, type RequestContext } from "./shared"; + +export interface SessionTarget { + environmentId?: string | null; + hasRepository: boolean; +} + +/** Enforce use of the environment or repository inherited by a new session. */ +export function authorizeSessionTarget( + ctx: RequestContext, + target: SessionTarget +): Response | null { + if (ctx.principal?.kind !== "user" && ctx.principal?.kind !== "service") return null; + + const permission: PermissionId | null = target.environmentId + ? "environments.use" + : target.hasRepository + ? "repositories.use" + : null; + if (!permission) return null; + + if ( + ctx.principal.kind === "service" && + !serviceAllowsPermission(ctx.principal.service, permission) + ) { + return json({ error: "Forbidden", code: "service_capability_required" }, 403); + } + if (!ctx.authorization) { + return json({ error: "Authorization unavailable", code: "authorization_unavailable" }, 503); + } + if (!ctx.authorization.permissions.includes(permission)) { + return json({ error: "Forbidden", code: "permission_required", permission }, 403); + } + return null; +} diff --git a/packages/control-plane/src/routes/shared.ts b/packages/control-plane/src/routes/shared.ts index 0d095666dc..1696f07b60 100644 --- a/packages/control-plane/src/routes/shared.ts +++ b/packages/control-plane/src/routes/shared.ts @@ -17,7 +17,6 @@ import type { ScopedPermissionStem, } from "@open-inspect/shared/rbac"; import type { ServiceName } from "@open-inspect/shared/service-auth"; -import type { AutomationRow } from "../db/automation-store"; import { createSourceControlProviderFromEnv, SourceControlProviderError, @@ -51,15 +50,8 @@ export type RequestContext = CorrelationContext & { authentication?: AuthenticationContext; /** Effective human authorization loaded once by the router for this request. */ authorization?: EffectiveAuthorization; - /** Resource admission populated by the router for automation mutation routes. */ - automationAdmission?: AutomationRouteAdmission; }; -/** Automation resource admitted by the router for the current mutation. */ -export interface AutomationRouteAdmission { - automation: AutomationRow; -} - /** Route matching, authorization, and handler configuration. */ export interface RouteDefinition { method: string; @@ -208,6 +200,7 @@ export type RouteAuthentication = | { kind: "public" } | { kind: "handler-authenticated" } | { kind: "web-service" } + | { kind: "service" } | { kind: "user" } | { kind: "user-or-service" } | ({ kind: "sandbox" } & SandboxSessionBinding) @@ -220,11 +213,13 @@ export type RouteContext = RequestCo ? SandboxPrincipal : Authentication extends { kind: "web-service" } ? WebServicePrincipal - : Authentication extends { kind: "user-or-service" } - ? UserOrServicePrincipal - : Authentication extends { kind: "user-or-service-with-sandbox-fallback" } - ? Principal - : Principal | undefined; + : Authentication extends { kind: "service" } + ? ServicePrincipal + : Authentication extends { kind: "user-or-service" } + ? UserOrServicePrincipal + : Authentication extends { kind: "user-or-service-with-sandbox-fallback" } + ? Principal + : Principal | undefined; }; export type UserRouteContext = RouteContext<{ kind: "user" }>; @@ -246,6 +241,11 @@ export const GITHUB_USER_OR_SERVICE_ROUTE = { supportedScmProviders: ["github"], } as const satisfies RoutePolicy; +export const GITHUB_SERVICE_ROUTE = { + authentication: { kind: "service" }, + supportedScmProviders: ["github"], +} as const satisfies RoutePolicy; + export const SCM_AGNOSTIC_USER_OR_SERVICE_ROUTE = { authentication: { kind: "user-or-service" }, supportedScmProviders: "all", diff --git a/packages/control-plane/src/webhooks/automation-event.ts b/packages/control-plane/src/webhooks/automation-event.ts index a90b8c6c29..558361b579 100644 --- a/packages/control-plane/src/webhooks/automation-event.ts +++ b/packages/control-plane/src/webhooks/automation-event.ts @@ -14,13 +14,12 @@ import { type AutomationEvent, type AutomationEventSource, } from "@open-inspect/shared/triggers"; -import { requireEventPoster } from "../auth/identity-enforcement"; import { createLogger } from "../logger"; import type { Route, RequestContext } from "../routes/shared"; import { defineRoute, error, - GITHUB_USER_OR_SERVICE_ROUTE, + GITHUB_SERVICE_ROUTE, json, parsePattern, serviceAuthorized, @@ -136,9 +135,6 @@ export function createAutomationEventRoute(opts: { _match: RegExpMatchArray, ctx: RequestContext ): Promise { - const authFailure = requireEventPoster(ctx, opts.source); - if (authFailure) return authFailure; - let body: unknown; try { body = await request.json(); @@ -156,7 +152,7 @@ export function createAutomationEventRoute(opts: { return forwardAutomationEventToScheduler(env, validated.event, ctx); } - return defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { + return defineRoute(GITHUB_SERVICE_ROUTE, { method: "POST", pattern: parsePattern(opts.path), authorization: serviceAuthorized("slack-bot"), diff --git a/packages/control-plane/src/webhooks/github.ts b/packages/control-plane/src/webhooks/github.ts index 48252fef1a..96987b721d 100644 --- a/packages/control-plane/src/webhooks/github.ts +++ b/packages/control-plane/src/webhooks/github.ts @@ -17,11 +17,10 @@ import type { RequestContext, Route } from "../routes/shared"; import { defineRoute, error, - GITHUB_USER_OR_SERVICE_ROUTE, + GITHUB_SERVICE_ROUTE, parsePattern, serviceAuthorized, } from "../routes/shared"; -import { requireEventPoster } from "../auth/identity-enforcement"; import { forwardAutomationEventToScheduler, logAutomationEventRejection, @@ -106,9 +105,6 @@ async function handleGitHubAutomationEvent( _match: RegExpMatchArray, ctx: RequestContext ): Promise { - const authFailure = requireEventPoster(ctx, "github"); - if (authFailure) return authFailure; - let body: unknown; try { body = await request.json(); @@ -130,7 +126,7 @@ async function handleGitHubAutomationEvent( return forwardAutomationEventToScheduler(env, validated.event, ctx); } -export const githubAutomationEventRoute: Route = defineRoute(GITHUB_USER_OR_SERVICE_ROUTE, { +export const githubAutomationEventRoute: Route = defineRoute(GITHUB_SERVICE_ROUTE, { method: "POST", pattern: parsePattern("/internal/github-event"), authorization: serviceAuthorized("github-bot"), diff --git a/packages/control-plane/test/integration/service-auth.test.ts b/packages/control-plane/test/integration/service-auth.test.ts index aa299ba17b..c3fd07e26a 100644 --- a/packages/control-plane/test/integration/service-auth.test.ts +++ b/packages/control-plane/test/integration/service-auth.test.ts @@ -11,6 +11,7 @@ import { generateInternalToken } from "@open-inspect/shared/auth"; import { GlobalSecretsStore } from "../../src/db/global-secrets"; import { UserStore } from "../../src/db/user-store"; import { cleanD1Tables } from "./cleanup"; +import { insertCanonicalUser } from "./identity-seed-helpers"; const SERVICE_SECRET: Record = { web: "test-service-secret-web", @@ -421,6 +422,54 @@ describe("sig1 service-credential authentication", () => { }); }); + it("does not authorize a first-contact actor as one user and attribute it to a Viewer", async () => { + await insertCanonicalUser({ + id: "existing-viewer", + email: "viewer@example.com", + emailVerified: 1, + displayName: "Existing Viewer", + }); + await env.DB.prepare("UPDATE user_role_assignments SET role_id = ? WHERE user_id = ?") + .bind("role_builtin_viewer", "existing-viewer") + .run(); + + const body = JSON.stringify({ + title: "First-contact actor", + model: "anthropic/claude-haiku-4-5", + actorEmail: "viewer@example.com", + }); + const first = await signedFetch({ + service: "slack-bot", + method: "POST", + url: "https://test.local/sessions", + actor: "slack:U-EMAIL-VIEWER", + body, + }); + + expect(first.status).toBe(409); + await expect(first.json()).resolves.toMatchObject({ code: "actor_identity_changed" }); + const identity = await new UserStore(env.DB).getIdentity("slack", "U-EMAIL-VIEWER"); + expect(identity?.userId).toBe("existing-viewer"); + + const retry = await signedFetch({ + service: "slack-bot", + method: "POST", + url: "https://test.local/sessions", + actor: "slack:U-EMAIL-VIEWER", + body, + }); + expect(retry.status).toBe(403); + await expect(retry.json()).resolves.toMatchObject({ + code: "permission_required", + permission: "sessions.create", + }); + + const sessions = await env.DB.prepare("SELECT COUNT(*) AS count FROM sessions").first<{ + count: number; + }>(); + expect(sessions?.count).toBe(0); + }); + it("requires a user or signed actor before any service can create a session", async () => { for (const service of Object.keys(SERVICE_SECRET) as ServiceName[]) { const response = await signedFetch({ diff --git a/packages/linear-bot/src/webhook-handler.test.ts b/packages/linear-bot/src/webhook-handler.test.ts index e3ffb9d660..09850c3eae 100644 --- a/packages/linear-bot/src/webhook-handler.test.ts +++ b/packages/linear-bot/src/webhook-handler.test.ts @@ -761,7 +761,7 @@ describe("handleAgentSessionEvent environment targets", () => { ); }); - it("falls back to the session creator when follow-up author fields are absent", async () => { + it("fails closed instead of signing as the session creator when follow-up author fields are absent", async () => { const { kv } = createFakeKV({ "oauth:client-credentials:org-1": validToken(), "issue:issue-1": JSON.stringify({ @@ -796,10 +796,7 @@ describe("handleAgentSessionEvent environment targets", () => { const sessionCalls = controlPlaneFetch.mock.calls.filter(([input]) => /\/(events\?|prompt$)/.test(String(input)) ); - expect(sessionCalls).toHaveLength(2); - for (const [, init] of sessionCalls) { - expect(new Headers(init?.headers).get("X-OpenInspect-Actor")).toBe("linear:session-creator"); - } + expect(sessionCalls).toHaveLength(0); }); it("adds prior token context from a parsed events response", async () => { @@ -875,7 +872,7 @@ describe("handleAgentSessionEvent environment targets", () => { expect(store.has("issue:issue-1")).toBe(false); }); - it("retains the session mapping when stopping the session fails", async () => { + it("fails closed and retains the session mapping when a stop author is missing", async () => { const { kv, store } = createFakeKV({ "issue:issue-1": JSON.stringify({ sessionId: "session-xyz", @@ -888,7 +885,6 @@ describe("handleAgentSessionEvent environment targets", () => { const env = makeLinearBotEnv(kv); const controlPlaneFetch = (env.CONTROL_PLANE as unknown as { fetch: ReturnType }) .fetch; - controlPlaneFetch.mockResolvedValue(new Response(null, { status: 500 })); const webhook = makeWebhook(); webhook.action = "prompted"; webhook.agentActivity = { @@ -898,7 +894,7 @@ describe("handleAgentSessionEvent environment targets", () => { await handleAgentSessionEvent(webhook, env, "trace-stop-failed"); - expect(controlPlaneFetch).toHaveBeenCalledOnce(); + expect(controlPlaneFetch).not.toHaveBeenCalled(); expect(store.has("issue:issue-1")).toBe(true); }); @@ -991,7 +987,7 @@ describe("handleAgentSessionEvent environment targets", () => { const promptCall = controlPlaneFetch.mock.calls.find(([input]) => String(input).endsWith("/prompt") ); - expect(JSON.parse(String(promptCall?.[1]?.body))).not.toHaveProperty("authorId"); + expect(promptCall).toBeUndefined(); }); }); diff --git a/packages/linear-bot/src/webhook-handler.ts b/packages/linear-bot/src/webhook-handler.ts index d8468e81b2..8067343447 100644 --- a/packages/linear-bot/src/webhook-handler.ts +++ b/packages/linear-bot/src/webhook-handler.ts @@ -225,15 +225,21 @@ async function handleStop(webhook: AgentSessionWebhook, env: Env, traceId: strin if (existingSession) { const stopUrl = `https://internal/sessions/${existingSession.sessionId}/stop`; const actorUserId = - webhook.agentActivity?.userId ?? - webhook.agentSession.comment?.userId ?? - webhook.agentSession.creatorId ?? - undefined; + webhook.agentActivity?.userId ?? webhook.agentSession.comment?.userId ?? undefined; + if (!actorUserId) { + log.warn("Linear stop rejected because its author is missing", { + event: "agent_session.stop_author_missing", + agent_session_id: agentSessionId, + issue_id: issueId, + trace_id: traceId, + }); + return; + } try { const stopRes = await signedControlPlaneFetch(env, { method: "POST", url: stopUrl, - actor: actorUserId ? `linear:${actorUserId}` : undefined, + actor: `linear:${actorUserId}`, traceId, }); if (!stopRes.ok) { @@ -315,13 +321,12 @@ function getFollowUp(webhook: AgentSessionWebhook): { source: "linear_agent_activity" | "linear_comment" | "linear_fallback"; actorUserId?: string; } { - const fallbackActorUserId = webhook.agentSession.creatorId ?? undefined; const activityBody = webhook.agentActivity?.content?.body; if (activityBody) { return { content: activityBody, source: "linear_agent_activity", - actorUserId: webhook.agentActivity?.userId ?? fallbackActorUserId, + actorUserId: webhook.agentActivity?.userId ?? undefined, }; } @@ -330,14 +335,14 @@ function getFollowUp(webhook: AgentSessionWebhook): { return { content: comment.body, source: "linear_comment", - actorUserId: comment.userId ?? fallbackActorUserId, + actorUserId: comment.userId ?? undefined, }; } return { content: "Follow-up on the issue.", source: "linear_fallback", - actorUserId: fallbackActorUserId, + actorUserId: undefined, }; } @@ -400,6 +405,26 @@ async function handleFollowUp( }); if (!client) return; + if (!followUp.actorUserId) { + log.warn("Linear follow-up rejected because its author is missing", { + event: "agent_session.follow_up_author_missing", + agent_session_id: agentSessionId, + issue_id: issue.id, + organization_id: orgId, + trace_id: traceId, + }); + await emitAgentActivity( + client, + agentSessionId, + { + type: "error", + body: "Cannot process this follow-up because Linear did not identify its author.", + }, + true + ); + return; + } + const existingSession = await lookupIssueSession(env, issue.id); if (!existingSession) return; const existingTarget = await resolveStoredSessionTarget(env, existingSession, traceId); @@ -430,7 +455,7 @@ async function handleFollowUp( const eventsRes = await signedControlPlaneFetch(env, { method: "GET", url: eventsUrl, - actor: followUp.actorUserId ? `linear:${followUp.actorUserId}` : undefined, + actor: `linear:${followUp.actorUserId}`, traceId, }); if (eventsRes.ok) { @@ -452,7 +477,7 @@ async function handleFollowUp( issueIdentifier: issue.identifier, followUpContent: followUp.content, followUpSource: followUp.source, - followUpAuthor: followUp.actorUserId ? "linear" : "unknown", + followUpAuthor: "linear", sessionContextSummary, }), source: "linear", @@ -462,7 +487,7 @@ async function handleFollowUp( method: "POST", url: promptUrl, body: promptBody, - actor: followUp.actorUserId ? `linear:${followUp.actorUserId}` : undefined, + actor: `linear:${followUp.actorUserId}`, traceId, }); From 42980493741b8d24241a7a0a73e6a40febab4b2e Mon Sep 17 00:00:00 2001 From: Cole Murray Date: Sun, 30 Aug 2026 23:43:36 -0700 Subject: [PATCH 6/6] fix: enforce actorless service ceilings --- .../authorization/service-permissions.test.ts | 1 + .../src/authorization/service-permissions.ts | 4 ++++ .../control-plane/src/router.policy.test.ts | 23 +++++++++++++++++++ packages/control-plane/src/router.ts | 8 +++---- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/packages/control-plane/src/authorization/service-permissions.test.ts b/packages/control-plane/src/authorization/service-permissions.test.ts index 5b20f99fd2..b1208e1cd2 100644 --- a/packages/control-plane/src/authorization/service-permissions.test.ts +++ b/packages/control-plane/src/authorization/service-permissions.test.ts @@ -4,6 +4,7 @@ import { serviceAllowsPermission } from "./service-permissions"; describe("serviceAllowsPermission", () => { it("allows launch capabilities but denies management capabilities", () => { expect(serviceAllowsPermission("slack-bot", "sessions.create")).toBe(true); + expect(serviceAllowsPermission("linear-bot", "integrations.read")).toBe(true); expect(serviceAllowsPermission("slack-bot", "global_secrets.manage")).toBe(false); expect(serviceAllowsPermission("github-bot", "sessions.sandbox_access")).toBe(false); }); diff --git a/packages/control-plane/src/authorization/service-permissions.ts b/packages/control-plane/src/authorization/service-permissions.ts index 1eb964df0f..1867923e7c 100644 --- a/packages/control-plane/src/authorization/service-permissions.ts +++ b/packages/control-plane/src/authorization/service-permissions.ts @@ -8,6 +8,7 @@ const SERVICE_PERMISSION_CEILINGS: Record "repositories.use", "environments.read", "environments.use", + "integrations.read", "sessions.create", "sessions.read", "sessions.collaborate", @@ -15,10 +16,12 @@ const SERVICE_PERMISSION_CEILINGS: Record "skills.read", ], "slack-bot": [ + "automations.read", "repositories.read", "repositories.use", "environments.read", "environments.use", + "integrations.read", "sessions.create", "sessions.read", "sessions.collaborate", @@ -31,6 +34,7 @@ const SERVICE_PERMISSION_CEILINGS: Record "repositories.use", "environments.read", "environments.use", + "integrations.read", "sessions.create", "sessions.read", "sessions.collaborate", diff --git a/packages/control-plane/src/router.policy.test.ts b/packages/control-plane/src/router.policy.test.ts index 934e7e5721..d4b4a4fa8e 100644 --- a/packages/control-plane/src/router.policy.test.ts +++ b/packages/control-plane/src/router.policy.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it, vi } from "vitest"; import { enforceRoutePrincipal, handleRequest, routes } from "./router"; import { TEST_BACKGROUND_TASK_CONTEXT } from "./router.test-support"; +import { serviceAllowsPermission } from "./authorization/service-permissions"; +import { SCOPED_PERMISSION_PAIRS } from "@open-inspect/shared/rbac"; function routeFor(method: string, path: string) { return routes.find((route) => route.method === method && route.pattern.test(path)); @@ -111,6 +113,27 @@ describe("route policy table", () => { expect(new Set(granted)).toEqual(expected); }); + it("keeps every actorless route grant within its service permission ceiling", () => { + for (const route of routes) { + if (route.authorization.kind !== "active-user") continue; + if (route.authorization.service.kind !== "actor") continue; + for (const grant of route.authorization.service.actorlessGrants ?? []) { + for (const requirement of route.authorization.allOf) { + if (requirement.kind === "permission") { + expect( + serviceAllowsPermission(grant.service, requirement.permission), + `${grant.service} must allow ${requirement.permission} for ${route.method} ${route.pattern}` + ).toBe(true); + } else if (requirement.kind === "scoped-permission") { + expect( + serviceAllowsPermission(grant.service, SCOPED_PERMISSION_PAIRS[requirement.stem].own) + ).toBe(true); + } + } + } + } + }); + it("keeps contextual route requirements explicit", () => { expect(routeFor("GET", "/keyboard-shortcuts")?.authorization).toEqual({ kind: "active-self", diff --git a/packages/control-plane/src/router.ts b/packages/control-plane/src/router.ts index 5435777417..5b406dca05 100644 --- a/packages/control-plane/src/router.ts +++ b/packages/control-plane/src/router.ts @@ -417,14 +417,14 @@ async function enforcePermissionRequirement( requirement: Extract, ctx: RequestContext ): Promise { - const userId = authorizationUserId(ctx); - if (!userId) return null; if ( ctx.principal?.kind === "service" && !serviceAllowsPermission(ctx.principal.service, requirement.permission) ) { return json({ error: "Forbidden", code: "service_capability_required" }, 403); } + const userId = authorizationUserId(ctx); + if (!userId) return null; if (ctx.authorization?.permissions.includes(requirement.permission)) return null; return json( { error: "Forbidden", code: "permission_required", permission: requirement.permission }, @@ -436,8 +436,6 @@ async function enforceScopedPermissionRequirement( requirement: Extract, ctx: RequestContext ): Promise { - const userId = authorizationUserId(ctx); - if (!userId) return null; const pair = SCOPED_PERMISSION_PAIRS[requirement.stem]; if ( ctx.principal?.kind === "service" && @@ -445,6 +443,8 @@ async function enforceScopedPermissionRequirement( ) { return json({ error: "Forbidden", code: "service_capability_required" }, 403); } + const userId = authorizationUserId(ctx); + if (!userId) return null; if ( ctx.authorization && resolveScopedPermission(requirement.stem, ctx.authorization.permissions)