Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

fix: allow admins to edit/delete environments and schedules (#1120)

Heer Ambavi90c7b1cc112b
diff --git a/.changeset/sandbox-env-schedule-admin-rbac.md b/.changeset/sandbox-env-schedule-admin-rbac.md
new file mode 100644
index 000000000..d7002e00a
--- /dev/null
+++ b/.changeset/sandbox-env-schedule-admin-rbac.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge': patch
+---
+
+Unify admin checks with `hasAdminRole` (tenant-admin in TrueFoundry) and gate sandbox environment create to admins while allowing the creator or an admin to update or delete. Schedule mutate and run-now stay creator-or-admin; settings access remains disabled in TrueFoundry via `canAccessSettings`.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 6ac1913e5..5826fcaf2 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -8024,6 +8024,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"409": {
"content": {
"application/json": {
@@ -8107,6 +8117,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"404": {
"content": {
"application/json": {
@@ -8200,6 +8220,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"404": {
"content": {
"application/json": {
diff --git a/docs/openapi.json b/docs/openapi.json
index 6ac1913e5..5826fcaf2 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -8024,6 +8024,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"409": {
"content": {
"application/json": {
@@ -8107,6 +8117,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"404": {
"content": {
"application/json": {
@@ -8200,6 +8220,16 @@
},
"description": "Unauthenticated."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "User does not have permission to edit Sandbox environment"
+ },
"404": {
"content": {
"application/json": {
diff --git a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts
index bb69f8758..55a1d6464 100644
--- a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts
@@ -149,6 +149,7 @@ export class SandboxEnvironmentsClient {
*
* @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.ConflictError}
* @throws {@link TrueForge.UnprocessableEntityError}
* @throws {@link TrueForge.BadGatewayError}
@@ -242,6 +243,17 @@ export class SandboxEnvironmentsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 409:
throw new TrueForge.ConflictError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -295,6 +307,7 @@ export class SandboxEnvironmentsClient {
*
* @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.ConflictError}
* @throws {@link TrueForge.UnprocessableEntityError}
@@ -389,6 +402,17 @@ export class SandboxEnvironmentsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -550,6 +574,7 @@ export class SandboxEnvironmentsClient {
* @param {SandboxEnvironmentsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.ConflictError}
* @throws {@link TrueForge.UnprocessableEntityError}
@@ -618,6 +643,17 @@ export class SandboxEnvironmentsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
diff --git a/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts b/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts
index 46a75554c..6b3c582de 100644
--- a/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts
+++ b/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts
@@ -242,6 +242,30 @@ describe("SandboxEnvironmentsClient", () => {
const rawRequestBody = { manifest: { name: "xy" } };
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .post("/api/v1/sandbox-environments")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sandboxEnvironments.create({
+ manifest: {
+ name: "xy",
+ },
+ });
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("create (5)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { name: "xy" } };
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.post("/api/v1/sandbox-environments")
@@ -260,7 +284,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.ConflictError);
});
- test("create (5)", async () => {
+ test("create (6)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
const rawRequestBody = { manifest: { name: "xy" } };
@@ -284,7 +308,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
});
- test("create (6)", async () => {
+ test("create (7)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
const rawRequestBody = { manifest: { name: "xy" } };
@@ -434,6 +458,30 @@ describe("SandboxEnvironmentsClient", () => {
const rawRequestBody = { manifest: { name: "xy" } };
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .put("/api/v1/sandbox-environments")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sandboxEnvironments.createOrUpdate({
+ manifest: {
+ name: "xy",
+ },
+ });
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("create_or_update (5)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { name: "xy" } };
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.put("/api/v1/sandbox-environments")
@@ -452,7 +500,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("create_or_update (5)", async () => {
+ test("create_or_update (6)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
const rawRequestBody = { manifest: { name: "xy" } };
@@ -476,7 +524,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.ConflictError);
});
- test("create_or_update (6)", async () => {
+ test("create_or_update (7)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
const rawRequestBody = { manifest: { name: "xy" } };
@@ -500,7 +548,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
});
- test("create_or_update (7)", async () => {
+ test("create_or_update (8)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
const rawRequestBody = { manifest: { name: "xy" } };
@@ -672,6 +720,25 @@ describe("SandboxEnvironmentsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .delete("/api/v1/sandbox-environments/name")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sandboxEnvironments.delete("name");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("delete (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.delete("/api/v1/sandbox-environments/name")
@@ -685,7 +752,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("delete (4)", async () => {
+ test("delete (5)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
@@ -704,7 +771,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.ConflictError);
});
- test("delete (5)", async () => {
+ test("delete (6)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
@@ -723,7 +790,7 @@ describe("SandboxEnvironmentsClient", () => {
}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
});
- test("delete (6)", async () => {
+ test("delete (7)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
diff --git a/packages/trueforge/src/apis/capabilities.ts b/packages/trueforge/src/apis/capabilities.ts
index 70fbb05dc..3126127da 100644
--- a/packages/trueforge/src/apis/capabilities.ts
+++ b/packages/trueforge/src/apis/capabilities.ts
@@ -1,7 +1,7 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import type { Context } from 'hono';
import type { Logger } from 'winston';
-import { hasAdminRole, type ResolveRequestContext } from '../auth/identity';
+import { canAccessSettings, type ResolveRequestContext } from '../auth/identity';
import type { ISandboxEnvironmentStore } from '../db/sandboxEnvironmentStore';
import type { WithTransaction } from '../db/transaction';
import type { IWebSearchProviderStore } from '../db/webSearchProviderStore';
@@ -43,7 +43,7 @@ export function createCapabilitiesRouter<TTransaction>(deps: {
hasTrueFoundrySandboxProviderConfig() ||
status === 'ready' ||
(defaultEnv === undefined && isLocalSandboxFallbackEnabled());
- const settingsEnabled = hasAdminRole(requestContext);
+ const settingsEnabled = canAccessSettings(requestContext);
const webSearchEnabled = await hasConfiguredWebSearchProvider({
tenant_id: requestContext.tenant_id,
store: deps.resolveWebSearchProviderStore(c),
diff --git a/packages/trueforge/src/apis/sandboxEnvironments.ts b/packages/trueforge/src/apis/sandboxEnvironments.ts
index fd7f20e85..6a0f25589 100644
--- a/packages/trueforge/src/apis/sandboxEnvironments.ts
+++ b/packages/trueforge/src/apis/sandboxEnvironments.ts
@@ -9,7 +9,7 @@ import { InvalidPageTokenError } from '@truefoundry/trueforge-core/agent-session
import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import type { Logger } from 'winston';
-import { createdBySubjectFromRequestContext, type ResolveRequestContext } from '../auth/identity';
+import { canEditEnvironment, createdBySubjectFromRequestContext, type ResolveRequestContext } from '../auth/identity';
import type { IAgentStore } from '../db/agentStore';
import {
SandboxEnvironmentNameConflictError,
@@ -41,6 +41,8 @@ import {
} from '../schemas/sandboxEnvironment';
import { MissingStoredSecretError } from '../utils/secretRedaction';
+const FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE = 'User does not have permission to edit Sandbox environment';
+
export interface SandboxEnvironmentsRouterDeps<TTransaction> {
sandboxEnvironmentStore: ISandboxEnvironmentStore<TTransaction>;
resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
@@ -143,7 +145,10 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
}): Promise<WriteSandboxEnvironmentOutcome> {
const requestContext = resolveRequestContext(c);
const { manifest } = body;
- const created_by_subject = createdBySubjectFromRequestContext(requestContext);
+ // Persist under the existing owner so store owner filters still match when a
+ // TrueFoundry tenant-admin updates another subject's environment.
+ const created_by_subject =
+ existing?.environment.created_by_subject ?? createdBySubjectFromRequestContext(requestContext);
try {
const provider = await resolveSandboxProviderRecord(
@@ -213,9 +218,12 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
}
const createHandler: RouteHandler<typeof createSandboxEnvironmentRoute> = async c => {
+ const requestContext = resolveRequestContext(c);
+ if (!canEditEnvironment(requestContext)) {
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
+ }
const body = c.req.valid('json');
- const { tenant_id } = resolveRequestContext(c);
- const existing = await store.getEnvironment({ tenant_id, name: body.manifest.name });
+ const existing = await store.getEnvironment({ tenant_id: requestContext.tenant_id, name: body.manifest.name });
if (existing) {
return c.json({ error: { message: `Sandbox environment with name ${body.manifest.name} already exists` } }, 409);
}
@@ -229,10 +237,13 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
// Create-or-update keyed by manifest.name.
const putHandler: RouteHandler<typeof putSandboxEnvironmentRoute> = async c => {
const body = c.req.valid('json');
- const { tenant_id, subject } = resolveRequestContext(c);
- const existing = await store.getEnvironment({ tenant_id, name: body.manifest.name });
- if (existing && existing.environment.created_by_subject.subject_id !== subject.id) {
- return c.json({ error: { message: `Sandbox environment not found: ${body.manifest.name}` } }, 404);
+ const requestContext = resolveRequestContext(c);
+ const existing = await store.getEnvironment({
+ tenant_id: requestContext.tenant_id,
+ name: body.manifest.name,
+ });
+ if (!canEditEnvironment(requestContext, existing?.environment.created_by_subject.subject_id)) {
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
}
const outcome = await writeSandboxEnvironment({ c, body, mode: 'upsert', existing });
if (outcome.kind === 'error') {
@@ -242,7 +253,8 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
};
const deleteHandler: RouteHandler<typeof deleteSandboxEnvironmentRoute> = async c => {
- const { tenant_id, subject } = resolveRequestContext(c);
+ const requestContext = resolveRequestContext(c);
+ const { tenant_id } = requestContext;
const { name } = c.req.valid('param');
if (name === DEFAULT_SANDBOX_ENVIRONMENT_NAME) {
return c.json({ error: { message: 'Sandbox environment "default" cannot be deleted' } }, 409);
@@ -254,8 +266,8 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
if (!existing) {
return c.json({ error: { message: `Sandbox environment not found: ${name}` } }, 404);
}
- if (existing.environment.created_by_subject.subject_id !== subject.id) {
- return c.json({ error: { message: `Sandbox environment not found: ${name}` } }, 404);
+ if (!canEditEnvironment(requestContext, existing.environment.created_by_subject.subject_id)) {
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
}
const agentNames = await resolveAgentStore(c).listAgentNamesUsingSandboxEnvironment({
tenant_id,
@@ -286,7 +298,6 @@ export function createSandboxEnvironmentsRouter<TTransaction>(
await store.deleteEnvironment({
tenant_id,
name,
- created_by_subject_id: subject.id,
});
return c.json({}, 200);
} catch (error) {
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index ab255f7a8..f7978e01a 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -13,9 +13,10 @@ import type { Logger } from 'winston';
import type { ResolveTurnSkillsStoreInput } from '../app';
import type { Authorizer } from '../auth/authorizer';
import {
+ canEditSchedule,
createdBySubjectFromRequestContext,
+ hasAdminRole,
requestContextFromCreatedBySubject,
- type RequestContext,
type ResolveRequestContext,
} from '../auth/identity';
import {
@@ -189,12 +190,7 @@ export function validateManifest(manifest: Pick<ScheduleManifest, 'cron' | 'time
}
}
-const FORBIDDEN_SCHEDULE_ACCESS = 'Only the schedule creator can access this schedule';
-
-/** Schedule mutations remain creator-only in every auth mode. */
-function isScheduleOwner(requestContext: Pick<RequestContext, 'subject'>, created_by_subject_id: string): boolean {
- return requestContext.subject.id === created_by_subject_id;
-}
+const FORBIDDEN_SCHEDULE_ACCESS = 'Only the schedule creator or an admin can access this schedule';
export function createScheduleExecutionRouter<TTransaction>(deps: ScheduleTurnExecutionDeps<TTransaction>) {
const handler: RouteHandler<typeof executeScheduleRunRoute> = async c => {
@@ -236,22 +232,26 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const { agent_names: agentNames, limit, page_token: pageToken, created_by_me: createdByMe } = c.req.valid('query');
const requestContext = deps.resolveRequestContext(c);
try {
- const managedAgentIds = createdByMe
- ? []
- : await resolveManagedAgentIds({
- store: deps.resolveAgentStore(c),
- context: requestContext,
- authorizer: deps.authorizer,
- });
+ // Admins see the full tenant list (unless created_by_me). Everyone else: own + managed-agent.
+ const created_by_or_agent_ids =
+ !createdByMe && hasAdminRole(requestContext)
+ ? undefined
+ : {
+ created_by_subject_id: requestContext.subject.id,
+ agent_ids: createdByMe
+ ? []
+ : await resolveManagedAgentIds({
+ store: deps.resolveAgentStore(c),
+ context: requestContext,
+ authorizer: deps.authorizer,
+ }),
+ };
const { data, pagination } = await deps.scheduleStore.listSchedules({
tenant_id: requestContext.tenant_id,
limit,
page_token: pageToken,
agent_names: agentNames,
- created_by_or_agent_ids: {
- created_by_subject_id: requestContext.subject.id,
- agent_ids: managedAgentIds,
- },
+ created_by_or_agent_ids,
});
return c.json({ data: data.map(toWireSchedule), pagination }, 200);
} catch (error) {
@@ -274,6 +274,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
if (
+ !canEditSchedule(requestContext, schedule.created_by_subject.subject_id) &&
!(await canReadAgentBoundResource({
store: deps.resolveAgentStore(c),
context: requestContext,
@@ -311,7 +312,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
if (schedule === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!isScheduleOwner(requestContext, schedule.created_by_subject.subject_id)) {
+ if (!canEditSchedule(requestContext, schedule.created_by_subject.subject_id)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
@@ -436,6 +437,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
if (
+ !canEditSchedule(requestContext, record.created_by_subject.subject_id) &&
!(await canReadAgentBoundResource({
store: deps.resolveAgentStore(c),
context: requestContext,
@@ -473,7 +475,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
if (existing === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!isScheduleOwner(requestContext, existing.created_by_subject.subject_id)) {
+ if (!canEditSchedule(requestContext, existing.created_by_subject.subject_id)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
@@ -518,7 +520,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
if (record === undefined) {
return c.json({}, 200);
}
- if (!isScheduleOwner(requestContext, record.created_by_subject.subject_id)) {
+ if (!canEditSchedule(requestContext, record.created_by_subject.subject_id)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
await deps.scheduleStore.deleteSchedule({
diff --git a/packages/trueforge/src/auth/identity.ts b/packages/trueforge/src/auth/identity.ts
index 3ff6d9745..326ea5888 100644
--- a/packages/trueforge/src/auth/identity.ts
+++ b/packages/trueforge/src/auth/identity.ts
@@ -12,6 +12,8 @@ import { createTrueFoundryRequestContext } from '../truefoundry/accessToken';
/** Standalone / default TrueForge admin role string. */
export const STANDALONE_ADMIN_ROLE = 'admin';
+export const TRUEFOUNDRY_TENANT_ADMIN_ROLE = 'tenant-admin';
+
export interface RequestSubject {
id: string;
type: string;
@@ -54,17 +56,15 @@ export function resolveRequestContext(c: Context): RequestContext {
}
/**
- * Whether the caller is treated as admin for settings, capabilities, and schedule bypass.
- * Mode and OIDC admin claim value come from process config ({@link getTrueForgeAuthMode}).
+ * Whether the caller is a TrueForge admin.
* - Standalone: `roles` includes `admin`
* - OIDC: `roles` includes configured `OIDC_ADMIN_ROLE_VALUE`
- * - TrueFoundry: no tenant-wide TrueForge admin
+ * - TrueFoundry: `roles` includes `tenant-admin`
*/
-// TODO (chiragjn): hasAdminRole will be renamed to canAccessSettings once all authorizer changes are done
export function hasAdminRole(requestContext: Pick<RequestContext, 'roles'>): boolean {
switch (getTrueForgeAuthMode()) {
case TrueForgeAuthMode.TrueFoundry:
- return false;
+ return requestContext.roles.includes(TRUEFOUNDRY_TENANT_ADMIN_ROLE);
case TrueForgeAuthMode.Oidc: {
if (!isOidcConfigured(configuration)) {
// this is technically unreachable since case TrueForgeAuthMode.Oidc already ensures OIDC is configured
@@ -77,6 +77,40 @@ export function hasAdminRole(requestContext: Pick<RequestContext, 'roles'>): boo
}
}
+/**
+ * Whether the caller may use `/api/v1/settings` and see settings in capabilities.
+ * Always false in TrueFoundry (catalogs are platform-managed); otherwise same as {@link hasAdminRole}.
+ */
+export function canAccessSettings(requestContext: Pick<RequestContext, 'roles'>): boolean {
+ if (getTrueForgeAuthMode() === TrueForgeAuthMode.TrueFoundry) {
+ return false;
+ }
+ return hasAdminRole(requestContext);
+}
+
+/**
+ * Create / update / delete sandbox environments (list/get stay open to all callers).
+ * - Create (no `created_by_subject_id`): admin only
+ * - Update / delete: admin or the environment creator
+ */
+export function canEditEnvironment(
+ requestContext: Pick<RequestContext, 'subject' | 'roles'>,
+ created_by_subject_id?: string,
+): boolean {
+ return (
+ hasAdminRole(requestContext) ||
+ (created_by_subject_id !== undefined && requestContext.subject.id === created_by_subject_id)
+ );
+}
+
+/** Update / delete / run-now a schedule (and admin/creator schedule reads). */
+export function canEditSchedule(
+ requestContext: Pick<RequestContext, 'subject' | 'roles'>,
+ created_by_subject_id: string,
+): boolean {
+ return hasAdminRole(requestContext) || requestContext.subject.id === created_by_subject_id;
+}
+
/** Subject rebuilt from a stored creator snapshot, for work that runs without a live request. */
export function requestSubjectFromCreatedBySubject(subject: CreatedBySubject): RequestSubject {
return {
diff --git a/packages/trueforge/src/auth/middleware.ts b/packages/trueforge/src/auth/middleware.ts
index 6fa973c3f..230639816 100644
--- a/packages/trueforge/src/auth/middleware.ts
+++ b/packages/trueforge/src/auth/middleware.ts
@@ -7,7 +7,7 @@ import { jwtVerify } from 'jose';
import { updateLogContext } from '../logger';
import type { Authenticator } from './authenticator';
import { toRequestContext, type IdTokenClaims } from './claims';
-import { hasAdminRole, type RequestContext } from './identity';
+import { canAccessSettings, type RequestContext } from './identity';
import { getOidcVerify } from './oidc';
import { extractRequestToken, readBearerToken } from './token';
@@ -25,6 +25,7 @@ export function createAuthMiddleware(authenticator: Authenticator): MiddlewareHa
};
}
+/** Gates `/api/v1/settings` — uses {@link canAccessSettings} (always denied in TrueFoundry). */
export function createAdminAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
return async (c, next) => {
const requestContext = await tryAuthenticate({ authenticator, context: c });
@@ -32,7 +33,7 @@ export function createAdminAuthMiddleware(authenticator: Authenticator): Middlew
throw new HTTPException(401, { message: 'Authentication required' });
}
updateLogContext({ tenant_id: requestContext.tenant_id });
- if (!hasAdminRole(requestContext)) {
+ if (!canAccessSettings(requestContext)) {
throw new HTTPException(403, { message: 'Admin access required' });
}
c.set('request_context', requestContext);
diff --git a/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts b/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts
index bb3d28490..74b40f4f5 100644
--- a/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts
+++ b/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts
@@ -501,7 +501,6 @@ export class PostgresSandboxEnvironmentStore implements ISandboxEnvironmentStore
.where('tenant_id', '=', input.tenant_id)
.where('name', '=', input.name)
.where('lifecycle_stage', '=', 'active')
- .where(sql`created_by_subject->>'subject_id'`, '=', input.created_by_subject_id)
.forUpdate()
.executeTakeFirst();
if (environment === undefined) {
diff --git a/packages/trueforge/src/db/sandboxEnvironmentStore.ts b/packages/trueforge/src/db/sandboxEnvironmentStore.ts
index c874ce306..a171b3101 100644
--- a/packages/trueforge/src/db/sandboxEnvironmentStore.ts
+++ b/packages/trueforge/src/db/sandboxEnvironmentStore.ts
@@ -153,8 +153,6 @@ export interface MarkSandboxEnvironmentVersionFailedInput {
export interface DeleteSandboxEnvironmentInput {
tenant_id: string;
name: string;
- /** Soft-delete only if created by this subject. */
- created_by_subject_id: string;
}
/** Partial unique `(tenant_id, name) WHERE lifecycle_stage = 'active'` violation. */
diff --git a/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts b/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts
index 5834759a0..e95d8f566 100644
--- a/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts
+++ b/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts
@@ -607,7 +607,6 @@ export class SqliteSandboxEnvironmentStore implements ISandboxEnvironmentStore<T
.where('tenant_id', '=', input.tenant_id)
.where('name', '=', input.name)
.where('lifecycle_stage', '=', 'active')
- .where(sql`json_extract(created_by_subject, '$.subject_id')`, '=', input.created_by_subject_id)
.executeTakeFirst();
if (environment === undefined) {
return;
diff --git a/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts b/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts
index 4ba8a4b54..136c47545 100644
--- a/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts
+++ b/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts
@@ -117,6 +117,10 @@ export const createSandboxEnvironmentRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Unauthenticated.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'User does not have permission to edit Sandbox environment',
+ },
409: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'A sandbox environment with this name already exists.',
@@ -159,6 +163,10 @@ export const putSandboxEnvironmentRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Unauthenticated.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'User does not have permission to edit Sandbox environment',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Sandbox environment not found.',
@@ -198,6 +206,10 @@ export const deleteSandboxEnvironmentRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Unauthenticated.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'User does not have permission to edit Sandbox environment',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Sandbox environment not found or not owned by the caller.',
diff --git a/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts b/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts
index c51953cec..84d239f49 100644
--- a/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts
+++ b/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts
@@ -2,7 +2,9 @@ import { DAYTONA_SNAPSHOT_NOT_STARTED_REASON } from '@truefoundry/trueforge-core
import { createLogger } from 'winston';
import { createSandboxEnvironmentBuildRouter } from '../../../src/apis/sandboxEnvironmentBuild';
import { createSandboxEnvironmentsRouter } from '../../../src/apis/sandboxEnvironments';
-import { STANDALONE_REQUEST_CONTEXT, type RequestContext } from '../../../src/auth/identity';
+import type { RequestContext } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT, TRUEFOUNDRY_TENANT_ADMIN_ROLE } from '../../../src/auth/identity';
+import { getTrueForgeAuthMode, TrueForgeAuthMode } from '../../../src/config';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { createSqliteDb } from '../../../src/db/sqlite/client';
import { SqliteSandboxEnvironmentStore } from '../../../src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore';
@@ -19,6 +21,14 @@ jest.mock('../../../src/sandbox/providerUtils', () => {
};
});
+jest.mock('../../../src/config', () => {
+ const actual = jest.requireActual<typeof import('../../../src/config')>('../../../src/config');
+ return {
+ ...actual,
+ getTrueForgeAuthMode: jest.fn(() => actual.TrueForgeAuthMode.Standalone),
+ };
+});
+
const logger = createLogger({ silent: true });
const daytonaManifest = {
@@ -33,6 +43,7 @@ const daytonaManifest = {
describe('sandbox environments API → build controller path', () => {
afterEach(() => {
jest.restoreAllMocks();
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.Standalone);
});
async function setup() {
@@ -65,10 +76,11 @@ describe('sandbox environments API → build controller path', () => {
publicRouter,
buildRouter,
sandboxEnvironmentStore,
- setSubject(subjectId: string) {
+ setSubject(subjectId: string, roles: string[] = STANDALONE_REQUEST_CONTEXT.roles) {
requestContext = {
...STANDALONE_REQUEST_CONTEXT,
subject: { id: subjectId, type: 'user', display_name: subjectId },
+ roles,
};
},
};
@@ -235,7 +247,7 @@ describe('sandbox environments API → build controller path', () => {
expect(Array.isArray(listBody.data)).toBe(true);
});
- it('shares tenant environments for reads and use while restricting writes to the creator', async () => {
+ it('allows all users to read; create is admin-only; update/delete allow admin or creator', async () => {
const { publicRouter, setSubject } = await setup();
jest.mocked(providerUtils.toDaytonaSandboxProvider).mockReturnValue({
createSecret: jest.fn(),
@@ -245,7 +257,7 @@ describe('sandbox environments API → build controller path', () => {
build: jest.fn(),
} as never);
- setSubject('alice');
+ setSubject('alice', ['admin']);
const body = {
manifest: {
name: 'shared-env',
@@ -263,25 +275,165 @@ describe('sandbox environments API → build controller path', () => {
).status,
).toBe(201);
- setSubject('bob');
+ // Creator retains edit access even without admin role.
+ setSubject('alice', ['everyone']);
+ const creatorUpdate = await publicRouter.request('/', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'shared-env',
+ description: 'updated by creator',
+ image: { type: 'build', build_script: 'pip install httpx' },
+ },
+ }),
+ });
+ expect(creatorUpdate.status).toBe(200);
+ expect(((await creatorUpdate.json()) as { data: { description: string } }).data.description).toBe(
+ 'updated by creator',
+ );
+
+ setSubject('bob', ['everyone']);
const listed = (await (await publicRouter.request('/')).json()) as { data: { name: string }[] };
expect(listed.data.map(environment => environment.name)).toContain('shared-env');
expect((await publicRouter.request('/shared-env')).status).toBe(200);
+ expect(
+ (
+ await publicRouter.request('/', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'bob-env',
+ description: 'denied',
+ image: { type: 'build', build_script: 'pip install httpx' },
+ },
+ }),
+ })
+ ).status,
+ ).toBe(403);
const update = await publicRouter.request('/', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
- expect(update.status).toBe(404);
+ expect(update.status).toBe(403);
expect(await update.json()).toEqual({
- error: { message: 'Sandbox environment not found: shared-env' },
+ error: { message: 'User does not have permission to edit Sandbox environment' },
});
const remove = await publicRouter.request('/shared-env', { method: 'DELETE' });
- expect(remove.status).toBe(404);
+ expect(remove.status).toBe(403);
expect(await remove.json()).toEqual({
- error: { message: 'Sandbox environment not found: shared-env' },
+ error: { message: 'User does not have permission to edit Sandbox environment' },
+ });
+
+ setSubject('carol', ['admin']);
+ const adminUpdate = await publicRouter.request('/', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'shared-env',
+ description: 'updated by carol',
+ image: { type: 'build', build_script: 'pip install requests' },
+ },
+ }),
+ });
+ expect(adminUpdate.status).toBe(200);
+ expect(((await adminUpdate.json()) as { data: { description: string } }).data.description).toBe('updated by carol');
+ expect((await publicRouter.request('/shared-env', { method: 'DELETE' })).status).toBe(200);
+ });
+
+ it('in TrueFoundry mode create is tenant-admin only; update/delete allow tenant-admin or creator', async () => {
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.TrueFoundry);
+ const { publicRouter, setSubject } = await setup();
+ jest.mocked(providerUtils.toDaytonaSandboxProvider).mockReturnValue({
+ createSecret: jest.fn(),
+ updateSecret: jest.fn(),
+ deleteSecret: jest.fn(),
+ getBuildStatus: jest.fn(),
+ build: jest.fn(),
+ } as never);
+
+ setSubject('bob', ['everyone']);
+ expect(
+ (
+ await publicRouter.request('/', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'bob-env',
+ description: 'denied',
+ image: { type: 'build', build_script: 'pip install httpx' },
+ },
+ }),
+ })
+ ).status,
+ ).toBe(403);
+
+ setSubject('alice', [TRUEFOUNDRY_TENANT_ADMIN_ROLE]);
+ const body = {
+ manifest: {
+ name: 'tfy-env',
+ description: 'created by alice',
+ image: { type: 'build', build_script: 'pip install httpx' },
+ },
+ };
+ expect(
+ (
+ await publicRouter.request('/', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ ).status,
+ ).toBe(201);
+
+ setSubject('alice', ['everyone']);
+ const creatorUpdate = await publicRouter.request('/', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'tfy-env',
+ description: 'updated by creator',
+ image: { type: 'build', build_script: 'pip install httpx' },
+ },
+ }),
+ });
+ expect(creatorUpdate.status).toBe(200);
+
+ setSubject('bob', ['everyone']);
+ expect((await publicRouter.request('/tfy-env')).status).toBe(200);
+ expect(
+ (
+ await publicRouter.request('/', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ ).status,
+ ).toBe(403);
+
+ setSubject('carol', [TRUEFOUNDRY_TENANT_ADMIN_ROLE]);
+ const update = await publicRouter.request('/', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ manifest: {
+ name: 'tfy-env',
+ description: 'updated by carol',
+ image: { type: 'build', build_script: 'pip install requests' },
+ },
+ }),
});
+ expect(update.status).toBe(200);
+ expect(((await update.json()) as { data: { description: string } }).data.description).toBe('updated by carol');
+
+ expect((await publicRouter.request('/tfy-env', { method: 'DELETE' })).status).toBe(200);
+ expect((await publicRouter.request('/tfy-env')).status).toBe(404);
});
});
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index 49194728a..5342c0355 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -185,7 +185,7 @@ describe('schedule RBAC', () => {
expect((await postJson('/runs', 'POST', { schedule_id: '01jqzz000000000000000nope' })).status).toBe(404);
});
- it("does not let an OIDC settings admin access another user's schedule", async () => {
+ it('lets an admin read and mutate another user schedule; created_by_me still scopes list', async () => {
const { app, asUser, postJson } = await setup();
asUser(ALICE);
@@ -193,15 +193,18 @@ describe('schedule RBAC', () => {
const { id } = ((await created.json()) as { data: { id: string } }).data;
asUser(ADMIN);
- expect((await app.request(`/${id}`)).status).toBe(403);
+ expect((await app.request(`/${id}`)).status).toBe(200);
const adminList = await app.request('/');
- expect(ListSchedulesResponseSchema.parse(await adminList.json()).data).toEqual([]);
- expect((await app.request(`/${id}/runs`)).status).toBe(403);
+ expect(ListSchedulesResponseSchema.parse(await adminList.json()).data.map(row => row.id)).toEqual([id]);
+ expect(
+ ListSchedulesResponseSchema.parse(await (await app.request('/?created_by_me=true')).json()).data,
+ ).toHaveLength(0);
+ expect((await app.request(`/${id}/runs`)).status).toBe(200);
expect((await postJson(`/${id}`, 'PUT', { name: 'admin-renamed', manifest: scheduleBody.manifest })).status).toBe(
- 403,
+ 200,
);
- expect((await app.request(`/${id}`, { method: 'DELETE' })).status).toBe(403);
- expect((await postJson('/runs', 'POST', { schedule_id: id })).status).toBe(403);
+ expect((await postJson('/runs', 'POST', { schedule_id: id })).status).toBe(201);
+ expect((await app.request(`/${id}`, { method: 'DELETE' })).status).toBe(200);
});
it('lets an agent manager read schedules and runs but keeps mutations creator-only', async () => {
@@ -371,7 +374,7 @@ describe('create schedule run', () => {
]);
});
- it('does not let an OIDC settings admin trigger another creator schedule', async () => {
+ it('lets an admin trigger another creator schedule', async () => {
const { asUser, postJson } = await setup();
asUser(ALICE);
@@ -380,8 +383,8 @@ describe('create schedule run', () => {
asUser(ADMIN);
const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });
- expect(res.status).toBe(403);
- expect(mockedStartScheduleRun).not.toHaveBeenCalled();
+ expect(res.status).toBe(201);
+ expect(mockedStartScheduleRun).toHaveBeenCalled();
});
it('marks the run failed and returns 404 when startScheduleRun reports a missing agent', async () => {
diff --git a/packages/trueforge/tests/unit/auth/identity.test.ts b/packages/trueforge/tests/unit/auth/identity.test.ts
index 12a4062fb..3b6b26ddb 100644
--- a/packages/trueforge/tests/unit/auth/identity.test.ts
+++ b/packages/trueforge/tests/unit/auth/identity.test.ts
@@ -1,10 +1,23 @@
import { Hono } from 'hono';
import {
+ canAccessSettings,
+ canEditEnvironment,
+ canEditSchedule,
hasAdminRole,
requestContextFromCreatedBySubject,
resolveRequestContext,
STANDALONE_REQUEST_CONTEXT,
+ TRUEFOUNDRY_TENANT_ADMIN_ROLE,
} from '../../../src/auth/identity';
+import { getTrueForgeAuthMode, TrueForgeAuthMode } from '../../../src/config';
+
+jest.mock('../../../src/config', () => {
+ const actual = jest.requireActual<typeof import('../../../src/config')>('../../../src/config');
+ return {
+ ...actual,
+ getTrueForgeAuthMode: jest.fn(() => actual.TrueForgeAuthMode.Standalone),
+ };
+});
describe('STANDALONE_REQUEST_CONTEXT', () => {
it('has the fixed standalone identity shape', () => {
@@ -39,12 +52,61 @@ describe('requestContextFromCreatedBySubject', () => {
});
describe('hasAdminRole', () => {
+ afterEach(() => {
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.Standalone);
+ });
+
// Unit tests run under STANDALONE=true (.env.test) → mode Standalone.
it('treats admin as admin and other roles as non-admin in standalone', () => {
expect(hasAdminRole({ roles: ['admin'] })).toBe(true);
expect(hasAdminRole({ roles: ['everyone'] })).toBe(false);
expect(hasAdminRole(STANDALONE_REQUEST_CONTEXT)).toBe(true);
});
+
+ it('treats tenant-admin as admin in TrueFoundry mode', () => {
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.TrueFoundry);
+ expect(hasAdminRole({ roles: [TRUEFOUNDRY_TENANT_ADMIN_ROLE] })).toBe(true);
+ expect(hasAdminRole({ roles: ['everyone'] })).toBe(false);
+ });
+});
+
+describe('canAccessSettings', () => {
+ afterEach(() => {
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.Standalone);
+ });
+
+ it('follows hasAdminRole outside TrueFoundry and stays false in TrueFoundry', () => {
+ expect(canAccessSettings({ roles: ['admin'] })).toBe(true);
+ expect(canAccessSettings({ roles: ['everyone'] })).toBe(false);
+
+ jest.mocked(getTrueForgeAuthMode).mockReturnValue(TrueForgeAuthMode.TrueFoundry);
+ expect(canAccessSettings({ roles: [TRUEFOUNDRY_TENANT_ADMIN_ROLE] })).toBe(false);
+ expect(hasAdminRole({ roles: [TRUEFOUNDRY_TENANT_ADMIN_ROLE] })).toBe(true);
+ });
+});
+
+describe('canEditEnvironment', () => {
+ it('allows create for admins only, and update/delete for admin or creator', () => {
+ const alice = { roles: ['everyone'], subject: { id: 'alice', type: 'user', display_name: 'alice' } };
+ const bob = { roles: ['everyone'], subject: { id: 'bob', type: 'user', display_name: 'bob' } };
+ const admin = { roles: ['admin'], subject: { id: 'root', type: 'user', display_name: 'root' } };
+ expect(canEditEnvironment(admin)).toBe(true);
+ expect(canEditEnvironment(alice)).toBe(false);
+ expect(canEditEnvironment(alice, 'alice')).toBe(true);
+ expect(canEditEnvironment(bob, 'alice')).toBe(false);
+ expect(canEditEnvironment(admin, 'alice')).toBe(true);
+ });
+});
+
+describe('canEditSchedule', () => {
+ it('allows the creator or an admin', () => {
+ const alice = { roles: ['everyone'], subject: { id: 'alice', type: 'user', display_name: 'alice' } };
+ const bob = { roles: ['everyone'], subject: { id: 'bob', type: 'user', display_name: 'bob' } };
+ const admin = { roles: ['admin'], subject: { id: 'root', type: 'user', display_name: 'root' } };
+ expect(canEditSchedule(alice, 'alice')).toBe(true);
+ expect(canEditSchedule(bob, 'alice')).toBe(false);
+ expect(canEditSchedule(admin, 'alice')).toBe(true);
+ });
});
describe('resolveRequestContext', () => {
diff --git a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py
index 258990e88..24f9dce1f 100644
--- a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py
+++ b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py
@@ -15,6 +15,7 @@ from ..core.unchecked_base_model import construct_type
from ..errors.bad_gateway_error import BadGatewayError
from ..errors.bad_request_error import BadRequestError
from ..errors.conflict_error import ConflictError
+from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
@@ -185,6 +186,17 @@ class RawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 409:
raise ConflictError(
headers=dict(_response.headers),
@@ -291,6 +303,17 @@ class RawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 404:
raise NotFoundError(
headers=dict(_response.headers),
@@ -452,6 +475,17 @@ class RawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 404:
raise NotFoundError(
headers=dict(_response.headers),
@@ -664,6 +698,17 @@ class AsyncRawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 409:
raise ConflictError(
headers=dict(_response.headers),
@@ -770,6 +815,17 @@ class AsyncRawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 404:
raise NotFoundError(
headers=dict(_response.headers),
@@ -931,6 +987,17 @@ class AsyncRawSandboxEnvironmentsClient:
),
),
)
+ if _response.status_code == 403:
+ raise ForbiddenError(
+ headers=dict(_response.headers),
+ body=typing.cast(
+ RequestErrorResponse,
+ construct_type(
+ type_=RequestErrorResponse, # type: ignore
+ object_=_response.json(),
+ ),
+ ),
+ )
if _response.status_code == 404:
raise NotFoundError(
headers=dict(_response.headers),