Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

fix(api): report granted scopes for hosted principals (#3170)

Ricky Chin291e8d577425
diff --git a/apps/api/src/api-key/api-key.controller.spec.ts b/apps/api/src/api-key/api-key.controller.spec.ts
index bd6b4e9c0..42c0ed644 100644
--- a/apps/api/src/api-key/api-key.controller.spec.ts
+++ b/apps/api/src/api-key/api-key.controller.spec.ts
@@ -40,7 +40,9 @@ describe('API key authorization', () => {
{ provide: OrganizationService, useValue: { findOne: async (id: string) => ({ id }) } },
{
provide: OrganizationUserService,
- useValue: { findOne: async (organizationId: string) => (organizationId === 'org-1' ? membership : null) },
+ useValue: {
+ findOneCached: async (organizationId: string) => (organizationId === 'org-1' ? membership : null),
+ },
},
{ provide: getRedisConnectionToken(), useValue: { get: async () => null, set: async () => 'OK' } },
],
diff --git a/apps/api/src/box/controllers/box-last-activity-proxy-auth.spec.ts b/apps/api/src/box/controllers/box-last-activity-proxy-auth.spec.ts
index e563572f8..4c835fbac 100644
--- a/apps/api/src/box/controllers/box-last-activity-proxy-auth.spec.ts
+++ b/apps/api/src/box/controllers/box-last-activity-proxy-auth.spec.ts
@@ -63,7 +63,7 @@ describe('BoxController reached by the preview proxy', () => {
{
provide: OrganizationUserService,
useValue: {
- findOne: jest.fn().mockResolvedValue({
+ findOneCached: jest.fn().mockResolvedValue({
userId: 'user-1',
organizationId: 'org-1',
role: 'owner',
diff --git a/apps/api/src/box/controllers/custom-domain.controller.spec.ts b/apps/api/src/box/controllers/custom-domain.controller.spec.ts
index 63cd14669..b98a28a52 100644
--- a/apps/api/src/box/controllers/custom-domain.controller.spec.ts
+++ b/apps/api/src/box/controllers/custom-domain.controller.spec.ts
@@ -28,7 +28,7 @@ describe('custom domain HTTP authorization', () => {
beforeAll(async () => {
const guard = new OrganizationResourceActionGuard(
{ findOne: async () => ({ id: org }) } as never,
- { findOne: async () => (member ? { role: 'member', assignedRoles: [{ permissions }] } : null) } as never,
+ { findOneCached: async () => (member ? { role: 'member', assignedRoles: [{ permissions }] } : null) } as never,
new Reflector(),
)
Object.assign(guard, { redis: { get: async () => null, set: async () => undefined } })
diff --git a/apps/api/src/boxlite-rest/admin-api.spec.ts b/apps/api/src/boxlite-rest/admin-api.spec.ts
index eb372e33f..e19b6ebff 100644
--- a/apps/api/src/boxlite-rest/admin-api.spec.ts
+++ b/apps/api/src/boxlite-rest/admin-api.spec.ts
@@ -79,7 +79,7 @@ describe('Admin API HTTP contract', () => {
let app: INestApplication
let principal: any
const members = {
- findOne: jest.fn(async (org: string, user: string) =>
+ findOneCached: jest.fn(async (org: string, user: string) =>
org === 'org-1' && ['owner', 'member'].includes(user) ? { role: user, organizationId: org, userId: user } : null,
),
findPage: jest.fn(async () => [member]),
diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
index 9bbb14565..690299db4 100644
--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
@@ -115,7 +115,7 @@ describe('Checkpoint REST authentication and request admission', () => {
{
provide: OrganizationUserService,
useValue: {
- findOne: async (org: string, userId: string) =>
+ findOneCached: async (org: string, userId: string) =>
org === organizationId ? { organizationId: org, userId, role: OrganizationMemberRole.OWNER } : null,
},
},
diff --git a/apps/api/src/boxlite-rest/boxlite-domain-auth.spec.ts b/apps/api/src/boxlite-rest/boxlite-domain-auth.spec.ts
index b883b733a..75e6bfe8c 100644
--- a/apps/api/src/boxlite-rest/boxlite-domain-auth.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-domain-auth.spec.ts
@@ -9,6 +9,8 @@ import { PassportModule } from '@nestjs/passport'
import { Test } from '@nestjs/testing'
import { ApiKeyStrategy } from '../auth/api-key.strategy'
import { JwtStrategy } from '../auth/jwt.strategy'
+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'
+import { ImageCatalogService } from '../image/services/image-catalog.service'
import { OrganizationMemberRole } from '../organization/enums/organization-member-role.enum'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { OrganizationService } from '../organization/services/organization.service'
@@ -17,15 +19,18 @@ import { SystemRole } from '../user/enums/system-role.enum'
import { BoxService } from '../box/services/box.service'
import { DomainService } from '../box/services/domain.service'
import { BoxliteDomainController } from './boxlite-domain.controller'
+import { BoxliteImageController } from './boxlite-image.controller'
+import { BoxliteMeController } from './boxlite-me.controller'
-// Exercise the real Passport strategies and both controller guards over HTTP.
-// Only credential/user storage, membership storage, Redis and domain persistence
-// are fixtures; no guard or permission-policy decision is replaced.
+// Exercise the Passport strategies and resource permission policy over HTTP.
+// Credential storage, membership storage, Redis, resource storage and quotas are fixtures.
describe('Domain acquisition authorization', () => {
let app: INestApplication
let jwks: Server
let issuer: string
let claim: jest.Mock
+ let readerPermissions: OrganizationResourcePermission[]
+ const cache = new Map<string, string>()
const keys = generateKeyPairSync('rsa', { modulusLength: 2048 })
const audience = 'domain-authorization-test'
const organizationId = 'org-1'
@@ -60,7 +65,6 @@ describe('Domain acquisition authorization', () => {
await new Promise<void>((resolve) => jwks.listen(0, '127.0.0.1', resolve))
issuer = `http://127.0.0.1:${(jwks.address() as AddressInfo).port}`
- const cache = new Map<string, string>()
const redis = {
get: async (key: string) => cache.get(key) ?? null,
set: async (key: string, value: string) => {
@@ -101,36 +105,43 @@ describe('Domain acquisition authorization', () => {
updateLastUsedAt: jest.fn().mockResolvedValue(undefined),
}
claim = jest.fn().mockResolvedValue({ hostname: 'my-app.apps.test', url: 'https://my-app.apps.test', target: null })
+ const organizationUsers = Object.assign(Object.create(OrganizationUserService.prototype), {
+ redis,
+ organizationUserRepository: {
+ findOne: async ({ where }: { where: { organizationId: string; userId: string } }) => {
+ if (where.organizationId !== organizationId || where.userId === 'outsider') return null
+ return {
+ organizationId,
+ userId: where.userId,
+ role: where.userId === 'owner' ? OrganizationMemberRole.OWNER : OrganizationMemberRole.MEMBER,
+ assignedRoles: [
+ {
+ permissions:
+ where.userId === 'writer' ? [OrganizationResourcePermission.WRITE_BOXES] : readerPermissions,
+ },
+ ],
+ }
+ },
+ },
+ })
const moduleRef = await Test.createTestingModule({
imports: [PassportModule.register({ session: false })],
- controllers: [BoxliteDomainController],
+ controllers: [BoxliteDomainController, BoxliteImageController, BoxliteMeController],
providers: [
{ provide: DomainService, useValue: { claim } },
{ provide: BoxService, useValue: {} },
{ provide: getRedisConnectionToken(), useValue: redis },
- { provide: OrganizationService, useValue: { findOne: async (id: string) => ({ id }) } },
+ { provide: ImageCatalogService, useValue: { listReferences: async () => [] } },
{
- provide: OrganizationUserService,
+ provide: OrganizationService,
useValue: {
- findOne: async (org: string, userId: string) => {
- if (org !== organizationId || userId === 'outsider') return null
- return {
- organizationId: org,
- userId,
- role: userId === 'owner' ? OrganizationMemberRole.OWNER : OrganizationMemberRole.MEMBER,
- assignedRoles: [
- {
- permissions: [
- userId === 'writer'
- ? OrganizationResourcePermission.WRITE_BOXES
- : OrganizationResourcePermission.READ_IMAGES,
- ],
- },
- ],
- }
- },
+ findOne: async (id: string) => ({ id }),
+ findByUserWithDefaultFlag: async () => [
+ { organization: { id: organizationId }, isDefaultForAuthenticatedUser: true },
+ ],
},
},
+ { provide: OrganizationUserService, useValue: organizationUsers },
{
provide: ApiKeyStrategy,
useFactory: () =>
@@ -154,7 +165,10 @@ describe('Domain acquisition authorization', () => {
),
},
],
- }).compile()
+ })
+ .overrideGuard(AuthenticatedRateLimitGuard)
+ .useValue({ canActivate: () => true })
+ .compile()
app = moduleRef.createNestApplication()
app.setGlobalPrefix('api')
await app.listen(0, '127.0.0.1')
@@ -165,13 +179,17 @@ describe('Domain acquisition authorization', () => {
if (jwks?.listening)
await new Promise<void>((resolve, reject) => jwks.close((error) => (error ? reject(error) : resolve())))
})
- beforeEach(() => claim.mockClear())
+ beforeEach(() => {
+ claim.mockClear()
+ cache.clear()
+ readerPermissions = [OrganizationResourcePermission.READ_IMAGES]
+ })
- async function request(path: string, token?: string): Promise<Response> {
+ async function request(path: string, token?: string, method = 'POST'): Promise<Response> {
return fetch(`http://127.0.0.1:${(app.getHttpServer().address() as AddressInfo).port}/api${path}`, {
- method: 'POST',
+ method,
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
- body: JSON.stringify({ name: 'my-app' }),
+ body: method === 'POST' ? JSON.stringify({ name: 'my-app' }) : undefined,
})
}
@@ -220,4 +238,26 @@ describe('Domain acquisition authorization', () => {
}
expect(claim).not.toHaveBeenCalled()
})
+
+ it('reports the same image permission that the resource route sees across a membership update', async () => {
+ const token = jwt('reader')
+ const images = `/v1/${organizationId}/images`
+ const cacheKey = OrganizationUserService.membershipCacheKey(organizationId, 'reader')
+ readerPermissions = []
+
+ expect((await request(images, token, 'GET')).status).toBe(403)
+ expect(cache.has(cacheKey)).toBe(true)
+
+ readerPermissions = [OrganizationResourcePermission.READ_IMAGES]
+ expect((await request(images, token, 'GET')).status).toBe(403)
+ const cachedPrincipal = await request('/v1/me', token, 'GET')
+ expect(cachedPrincipal.status).toBe(200)
+ expect((await cachedPrincipal.json()).scopes).not.toContain('image:read')
+
+ cache.delete(cacheKey)
+ const refreshedPrincipal = await request('/v1/me', token, 'GET')
+ expect(refreshedPrincipal.status).toBe(200)
+ expect((await refreshedPrincipal.json()).scopes).toContain('image:read')
+ expect((await request(images, token, 'GET')).status).toBe(200)
+ })
})
diff --git a/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts b/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts
new file mode 100644
index 000000000..4d85964e9
--- /dev/null
+++ b/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { INestApplication, UnauthorizedException } from '@nestjs/common'
+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'
+import { PassportModule } from '@nestjs/passport'
+import { Test } from '@nestjs/testing'
+import { EventEmitter } from 'node:events'
+import { ApiKeyStrategy } from '../auth/api-key.strategy'
+import { Box } from '../box/entities/box.entity'
+import { BoxDesiredState } from '../box/enums/box-desired-state.enum'
+import { BoxState } from '../box/enums/box-state.enum'
+import { BoxService } from '../box/services/box.service'
+import { BoxStateWaiterService } from '../box/services/box-state-waiter.service'
+import { CheckpointRecoverService } from '../box/services/checkpoint-recover.service'
+import { OrganizationMemberRole } from '../organization/enums/organization-member-role.enum'
+import { OrganizationResourcePermission as Permission } from '../organization/enums/organization-resource-permission.enum'
+import { OrganizationService } from '../organization/services/organization.service'
+import { OrganizationUserService } from '../organization/services/organization-user.service'
+import { SystemRole } from '../user/enums/system-role.enum'
+import { BoxliteBoxController } from './boxlite-box.controller'
+import { BoxliteMeController } from './boxlite-me.controller'
+import { CommerceBoxLimitService } from './commerce-box-limit.service'
+
+jest.mock('http-proxy-middleware', () => ({ createProxyMiddleware: jest.fn() }))
+
+describe('Hosted API key scope discovery and Box deletion', () => {
+ const organizationId = 'scope-test-org'
+ const userId = 'scope-test-owner'
+ const boxName = 'cleanup-target'
+ const keyPermissions = new Map<string, Permission[]>([
+ ['operations-key', [Permission.WRITE_BOXES]],
+ ['delete-key', [Permission.DELETE_BOXES]],
+ ])
+ let app: INestApplication
+ let base: string
+ let box: Box
+ const boxRepository = {
+ findOne: jest.fn(async ({ where }: { where: Partial<Pick<Box, 'id' | 'name' | 'organizationId'>> }) =>
+ where.organizationId === box.organizationId && (where.id === box.id || where.name === box.name) ? box : null,
+ ),
+ findWithCheckpointState: async () => ({ box, checkpointState: null }),
+ updateWhere: async (_id: string, { updateData }: { updateData: Partial<Box> }) => Object.assign(box, updateData),
+ }
+
+ beforeAll(async () => {
+ const redis = {
+ get: async () => null,
+ set: async () => 'OK',
+ setex: async () => 'OK',
+ }
+ const apiKeys = {
+ async getApiKeyByValue(token: string) {
+ const permissions = keyPermissions.get(token)
+ if (!permissions) throw new UnauthorizedException()
+ return { organizationId, userId, name: token, permissions }
+ },
+ updateLastUsedAt: async () => undefined,
+ }
+ const boxService = Object.assign(Object.create(BoxService.prototype), {
+ boxRepository,
+ eventEmitter: new EventEmitter(),
+ boxActivityService: { getLastActivityAt: async () => null },
+ imagePreparationService: { preparingImage: async () => new Set() },
+ boxExitCodeService: { getExitCode: async () => undefined },
+ })
+ const module = await Test.createTestingModule({
+ imports: [PassportModule.register({ session: false })],
+ controllers: [BoxliteMeController, BoxliteBoxController],
+ providers: [
+ { provide: BoxService, useValue: boxService },
+ { provide: BoxStateWaiterService, useValue: {} },
+ { provide: CheckpointRecoverService, useValue: {} },
+ { provide: CommerceBoxLimitService, useValue: {} },
+ { provide: getRedisConnectionToken(), useValue: redis },
+ { provide: OrganizationService, useValue: { findOne: async (id: string) => ({ id }) } },
+ {
+ provide: OrganizationUserService,
+ useValue: { findOneCached: async () => ({ organizationId, userId, role: OrganizationMemberRole.OWNER }) },
+ },
+ {
+ provide: ApiKeyStrategy,
+ useFactory: () =>
+ new ApiKeyStrategy(
+ redis as never,
+ apiKeys as never,
+ { findOne: async () => ({ id: userId, role: SystemRole.USER }) } as never,
+ { get: () => undefined } as never,
+ { findByApiKey: async () => null } as never,
+ { findOneByProxyApiKey: async () => null } as never,
+ ),
+ },
+ ],
+ }).compile()
+ app = module.createNestApplication({ logger: false })
+ app.setGlobalPrefix('api')
+ await app.listen(0, '127.0.0.1')
+ base = await app.getUrl()
+ })
+
+ afterAll(async () => {
+ await app?.close()
+ })
+
+ beforeEach(() => {
+ box = Object.assign(new Box('us', boxName), {
+ organizationId,
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.STOPPED,
+ })
+ boxRepository.findOne.mockClear()
+ })
+
+ function request(path: string, token: string, method = 'GET') {
+ return fetch(`${base}/api/v1/${path}`, { method, headers: { authorization: `Bearer ${token}` } })
+ }
+
+ it('reports only operation scopes and forbids deleting an existing or unknown Box', async () => {
+ const token = 'operations-key'
+ const principal = await request('me', token)
+ expect(principal.status).toBe(200)
+ expect((await request(`boxes/${box.id}`, token)).status).toBe(200)
+ boxRepository.findOne.mockClear()
+
+ expect((await request(`boxes/${box.id}`, token, 'DELETE')).status).toBe(403)
+ expect((await request('boxes/unknown-box', token, 'DELETE')).status).toBe(403)
+ expect(boxRepository.findOne).not.toHaveBeenCalled()
+ expect(box.desiredState).toBe(BoxDesiredState.STOPPED)
+ expect((await principal.json()).scopes).toEqual(['box:read', 'box:write', 'box:exec', 'me:read'])
+ })
+
+ it('reports the granted delete scope and records destruction of an existing Box', async () => {
+ const token = 'delete-key'
+ const principal = await request('me', token)
+ expect(principal.status).toBe(200)
+ expect((await request(`boxes/${boxName}`, token)).status).toBe(200)
+
+ expect((await request(`boxes/${box.id}`, token, 'DELETE')).status).toBe(204)
+ expect(box.desiredState).toBe(BoxDesiredState.DESTROYED)
+ expect(box.pending).toBe(true)
+ expect((await request(`boxes/${boxName}`, token)).status).toBe(404)
+ expect((await principal.json()).scopes).toEqual(['box:read', 'box:delete', 'me:read'])
+ })
+
+ it.each([
+ [Permission.READ_IMAGES, 'image:read'],
+ [Permission.WRITE_IMAGES, 'image:write'],
+ [Permission.READ_VOLUMES, 'volume:read'],
+ [Permission.WRITE_VOLUMES, 'volume:write'],
+ [Permission.DELETE_VOLUMES, 'volume:delete'],
+ ])('reports the scope for the individual grant %s', async (permission, scope) => {
+ const token = 'resource-scope-key'
+ keyPermissions.set(token, [permission])
+ const principal = await request('me', token)
+ expect(principal.status).toBe(200)
+ expect((await principal.json()).scopes).toEqual(['box:read', scope, 'me:read'])
+ })
+})
diff --git a/apps/api/src/boxlite-rest/boxlite-management-rate-limit.spec.ts b/apps/api/src/boxlite-rest/boxlite-management-rate-limit.spec.ts
index a3df273bf..c0740ffb6 100644
--- a/apps/api/src/boxlite-rest/boxlite-management-rate-limit.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-management-rate-limit.spec.ts
@@ -98,7 +98,7 @@ describe('BoxLite management rate limits', () => {
{ provide: OrganizationService, useValue: organizations },
{
provide: OrganizationUserService,
- useValue: { findOne: jest.fn().mockResolvedValue({ role: OrganizationMemberRole.OWNER }) },
+ useValue: { findOneCached: jest.fn().mockResolvedValue({ role: OrganizationMemberRole.OWNER }) },
},
{ provide: getRedisConnectionToken(), useValue: redis },
],
diff --git a/apps/api/src/boxlite-rest/boxlite-me.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-me.controller.spec.ts
index e48cd58ee..32caf35a6 100644
--- a/apps/api/src/boxlite-rest/boxlite-me.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-me.controller.spec.ts
@@ -4,17 +4,31 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { Test } from '@nestjs/testing'
import { ApiKey } from '../api-key/api-key.entity'
import { AuthContext } from '../common/interfaces/auth-context.interface'
+import { OrganizationMemberRole } from '../organization/enums/organization-member-role.enum'
+import { OrganizationResourcePermission as Permission } from '../organization/enums/organization-resource-permission.enum'
import { OrganizationService } from '../organization/services/organization.service'
+import { OrganizationUserService } from '../organization/services/organization-user.service'
+import { SystemRole } from '../user/enums/system-role.enum'
import { BoxliteMeController } from './boxlite-me.controller'
describe('BoxliteMeController', () => {
- // resolvePathPrefix only touches OrganizationService on the user-session path;
- // API-key contexts short-circuit on apiKey.organizationId.
- function makeController(orgFindByUser: jest.Mock = jest.fn()): BoxliteMeController {
- const organizationService = { findByUserWithDefaultFlag: orgFindByUser } as unknown as OrganizationService
- return new BoxliteMeController(organizationService)
+ const user: AuthContext = { userId: 'user-2', email: '[email protected]', role: SystemRole.USER }
+
+ async function makeController(
+ findByUserWithDefaultFlag = jest.fn().mockResolvedValue([]),
+ findOneCached = jest.fn().mockResolvedValue(null),
+ ): Promise<BoxliteMeController> {
+ const module = await Test.createTestingModule({
+ controllers: [BoxliteMeController],
+ providers: [
+ { provide: OrganizationService, useValue: { findByUserWithDefaultFlag } },
+ { provide: OrganizationUserService, useValue: { findOneCached } },
+ ],
+ }).compile()
+ return module.get(BoxliteMeController)
}
function apiKeyContext(expiresAt?: Date): AuthContext {
@@ -27,7 +41,7 @@ describe('BoxliteMeController', () => {
return {
userId: 'user-1',
- role: 'user' as AuthContext['role'],
+ role: SystemRole.USER,
apiKey,
organizationId: apiKey.organizationId,
}
@@ -36,30 +50,54 @@ describe('BoxliteMeController', () => {
describe('GET /v1/me — expires_at is sourced from ApiKey.expiresAt', () => {
it('returns the API key expiry as an ISO string (same field the dashboard renders)', async () => {
const expiresAt = new Date('2026-06-07T12:00:00.000Z')
- const result = await makeController().getMe(apiKeyContext(expiresAt))
+ const controller = await makeController()
+ const result = await controller.getMe(apiKeyContext(expiresAt))
expect(result.principal_type).toBe('service_account')
expect(result.expires_at).toBe(expiresAt.toISOString())
})
it('returns null for a non-expiring API key (expiresAt unset)', async () => {
- const result = await makeController().getMe(apiKeyContext(undefined))
+ const controller = await makeController()
+ const result = await controller.getMe(apiKeyContext(undefined))
expect(result.expires_at).toBeNull()
})
it('returns null for an interactive user session (no API key)', async () => {
- const findByUser = jest.fn().mockResolvedValue([])
- const ctx: AuthContext = {
- userId: 'user-2',
- email: '[email protected]',
- role: 'user' as AuthContext['role'],
- }
-
- const result = await makeController(findByUser).getMe(ctx)
+ const controller = await makeController()
+ const result = await controller.getMe(user)
expect(result.principal_type).toBe('user')
expect(result.expires_at).toBeNull()
})
})
+
+ it.each([
+ [true, 'marked-default', ['box:read', 'image:read', 'me:read']],
+ [false, 'first-membership', ['box:read', 'box:delete', 'me:read']],
+ ])(
+ 'reports the interactive user scopes for the resolved prefix (default marked: %s)',
+ async (markDefault, prefix, scopes) => {
+ const findOrganizations = jest.fn().mockResolvedValue([
+ { organization: { id: 'first-membership' }, isDefaultForAuthenticatedUser: false },
+ { organization: { id: 'marked-default' }, isDefaultForAuthenticatedUser: markDefault },
+ ])
+ const findMembership = jest.fn(async (organizationId: string) => ({
+ role: OrganizationMemberRole.MEMBER,
+ assignedRoles: [
+ { permissions: [organizationId === 'marked-default' ? Permission.READ_IMAGES : Permission.DELETE_BOXES] },
+ ],
+ }))
+ const controller = await makeController(findOrganizations, findMembership)
+
+ expect(await controller.getMe(user)).toMatchObject({ path_prefix: prefix, scopes })
+ },
+ )
+
+ it('reports identity access alone for an interactive user with no organization', async () => {
+ const controller = await makeController()
+
+ expect(await controller.getMe(user)).toMatchObject({ path_prefix: null, scopes: ['me:read'] })
+ })
})
diff --git a/apps/api/src/boxlite-rest/boxlite-me.controller.ts b/apps/api/src/boxlite-rest/boxlite-me.controller.ts
index 324a768fa..8542fe5b7 100644
--- a/apps/api/src/boxlite-rest/boxlite-me.controller.ts
+++ b/apps/api/src/boxlite-rest/boxlite-me.controller.ts
@@ -9,9 +9,25 @@ import { ApiBearerAuth, ApiTags, ApiExcludeController } from '@nestjs/swagger'
import { CombinedAuthGuard } from '../auth/combined-auth.guard'
import { AuthContext } from '../common/decorators/auth-context.decorator'
import { AuthContext as AuthCtx } from '../common/interfaces/auth-context.interface'
+import { OrganizationResourcePermission as Permission } from '../organization/enums/organization-resource-permission.enum'
+import { hasOrganizationResourcePermissions } from '../organization/guards/organization-resource-action.guard'
import { OrganizationService } from '../organization/services/organization.service'
+import { OrganizationUserService } from '../organization/services/organization-user.service'
+import { SystemRole } from '../user/enums/system-role.enum'
import { PrincipalDto } from './dto/principal.dto'
+const ORGANIZATION_SCOPE_PERMISSIONS: Record<string, Permission[]> = {
+ 'box:read': [],
+ 'box:write': [Permission.WRITE_BOXES],
+ 'box:exec': [Permission.WRITE_BOXES],
+ 'box:delete': [Permission.DELETE_BOXES],
+ 'image:read': [Permission.READ_IMAGES],
+ 'image:write': [Permission.WRITE_IMAGES],
+ 'volume:read': [Permission.READ_VOLUMES],
+ 'volume:write': [Permission.WRITE_VOLUMES],
+ 'volume:delete': [Permission.DELETE_VOLUMES],
+}
+
/**
* `GET /v1/me` — identity for the calling credential.
*
@@ -28,11 +44,22 @@ import { PrincipalDto } from './dto/principal.dto'
@UseGuards(CombinedAuthGuard)
@ApiBearerAuth()
export class BoxliteMeController {
- constructor(private readonly organizationService: OrganizationService) {}
+ constructor(
+ private readonly organizationService: OrganizationService,
+ private readonly organizationUserService: OrganizationUserService,
+ ) {}
@Get('me')
async getMe(@AuthContext() ctx: AuthCtx): Promise<PrincipalDto> {
const pathPrefix = await this.resolvePathPrefix(ctx)
+ const organizationUser =
+ pathPrefix && ctx.role !== SystemRole.ADMIN
+ ? ((await this.organizationUserService.findOneCached(pathPrefix, ctx.userId)) ?? undefined)
+ : undefined
+ const subject = { role: ctx.role, apiKey: ctx.apiKey, organizationUser }
+ const scopes = Object.entries(ORGANIZATION_SCOPE_PERMISSIONS)
+ .filter(([, permissions]) => hasOrganizationResourcePermissions(subject, permissions))
+ .map(([scope]) => scope)
const principalType: 'user' | 'service_account' = ctx.apiKey ? 'service_account' : 'user'
@@ -42,21 +69,7 @@ export class BoxliteMeController {
email: ctx.email || undefined,
display_name: undefined,
path_prefix: pathPrefix,
- // TODO: source scopes from ctx.apiKey?.scopes once the ApiKey entity
- // has a `scopes` column. For now grant the full set used by the OpenAPI
- // spec's documented scope vocabulary.
- scopes: [
- 'box:read',
- 'box:write',
- 'box:exec',
- 'box:delete',
- 'image:read',
- 'image:write',
- 'volume:read',
- 'volume:write',
- 'volume:delete',
- 'me:read',
- ],
+ scopes: [...scopes, 'me:read'],
// Source of truth for key expiry is ApiKey.expiresAt — the same column the
// dashboard's `/api-keys` list renders. Returning a hardcoded null here let
// clients believe a soon-to-expire key was permanent (P1-2). `null` stays
diff --git a/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts b/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
index b9a547c3b..e94edf552 100644
--- a/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
@@ -313,7 +313,7 @@ async function startSshApp(principal?: Record<string, unknown>): Promise<SshApp>
{
provide: OrganizationUserService,
useValue: {
- findOne: async (organizationId: string, userId: string) => ({ organizationId, userId, role: 'member' }),
+ findOneCached: async (organizationId: string, userId: string) => ({ organizationId, userId, role: 'member' }),
},
},
{ provide: getRedisConnectionToken(), useValue: { get: async () => null, set: async () => 'OK' } },
diff --git a/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts b/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts
index 90bb1821d..03f2eef60 100644
--- a/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts
@@ -98,7 +98,7 @@ describe('execution inventory authorization', () => {
const guard = new OrganizationResourceActionGuard(
{ findOne: async (id: string) => ({ id }) } as never,
{
- findOne: async (organizationId: string, userId: string) =>
+ findOneCached: async (organizationId: string, userId: string) =>
member ? { organizationId, userId, role: 'member' } : null,
} as never,
reflector,
diff --git a/apps/api/src/ci/ci-connect.controller.spec.ts b/apps/api/src/ci/ci-connect.controller.spec.ts
index 80315283f..3af724fa5 100644
--- a/apps/api/src/ci/ci-connect.controller.spec.ts
+++ b/apps/api/src/ci/ci-connect.controller.spec.ts
@@ -63,7 +63,7 @@ describe('CI connect HTTP authorization boundary', () => {
}
const organizationService = { findOne: async (id: string) => (id === org ? { id } : null) }
const memberService = {
- findOne: async (_: string, id: string) => ({ role: id.startsWith('member') ? 'member' : 'owner' }),
+ findOneCached: async (_: string, id: string) => ({ role: id.startsWith('member') ? 'member' : 'owner' }),
}
const guard = new OrganizationActionGuard(organizationService as any, memberService as any, new Reflector())
;(guard as any).redis = redis
diff --git a/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts b/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts
index db8091cf0..3472162cc 100644
--- a/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts
+++ b/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts
@@ -92,10 +92,13 @@ integration('organization cancellation feedback (Postgres and authenticated HTTP
await startApp()
})
async function startApp() {
- const membership = {
- findOne: (org: string, user: string) =>
- org === organizationId && roles.has(user) ? { role: roles.get(user) } : null,
- }
+ const membership = Object.assign(Object.create(OrganizationUserService.prototype), {
+ redis: cache,
+ organizationUserRepository: {
+ findOne: ({ where }: { where: { organizationId: string; userId: string } }) =>
+ where.organizationId === organizationId && roles.has(where.userId) ? { role: roles.get(where.userId) } : null,
+ },
+ })
const module = await Test.createTestingModule({
controllers: [CancellationFeedbackController],
providers: [
@@ -194,6 +197,7 @@ integration('organization cancellation feedback (Postgres and authenticated HTTP
})
it('checks current ownership even when the access guard cached an owner', async () => {
expect((await put()).status).toBe(204)
+ expect(cache.has(OrganizationUserService.membershipCacheKey(organizationId, 'owner'))).toBe(true)
roles.set('owner', OrganizationMemberRole.MEMBER)
expect((await put({ reasons: ['completed'] })).status).toBe(403)
expect((await stored()).reasons).toEqual(['other', 'pricing'])
diff --git a/apps/api/src/organization/controllers/coupon-claims.integration.spec.ts b/apps/api/src/organization/controllers/coupon-claims.integration.spec.ts
index ef0903a96..5de7187fd 100644
--- a/apps/api/src/organization/controllers/coupon-claims.integration.spec.ts
+++ b/apps/api/src/organization/controllers/coupon-claims.integration.spec.ts
@@ -116,10 +116,15 @@ describe('POST /api/organizations/:organizationId/coupon-claims', () => {
.setExpirationTime('1h')
.sign(privateKey)
}
- const membership = {
- findOne: (org: string, userId: string) =>
- org.toLowerCase() === organizationId && roles.has(userId) ? { role: roles.get(userId) } : null,
- }
+ const membership = Object.assign(Object.create(OrganizationUserService.prototype), {
+ redis: cache,
+ organizationUserRepository: {
+ findOne: ({ where }: { where: { organizationId: string; userId: string } }) =>
+ where.organizationId.toLowerCase() === organizationId && roles.has(where.userId)
+ ? { role: roles.get(where.userId) }
+ : null,
+ },
+ })
const module = await Test.createTestingModule({
controllers: [CouponClaimsController],
providers: [
@@ -296,7 +301,7 @@ describe('POST /api/organizations/:organizationId/coupon-claims', () => {
['system administrator without ownership', 'admin', otherOrganizationId, 403],
['unverified owner', 'unverified', organizationId, 403],
] as const)('rejects %s before contacting Commerce', async (_label, identity, org, expected) => {
- const token = identity === null ? null : tokens[identity] ?? identity
+ const token = identity === null ? null : (tokens[identity] ?? identity)
const response = await post(claim, token, org)
expect(response.status).toBe(expected)
if (identity === 'unverified') expect(response.data.code).toBe('email_verification_required')
@@ -310,6 +315,7 @@ describe('POST /api/organizations/:organizationId/coupon-claims', () => {
it.each(['removed', 'demoted'])('denies a cached owner whose membership was %s', async (change) => {
expect((await post()).status).toBe(202)
+ expect(cache.has(OrganizationUserService.membershipCacheKey(organizationId, 'owner'))).toBe(true)
if (change === 'removed') roles.delete('owner')
else roles.set('owner', OrganizationMemberRole.MEMBER)
expect((await post()).status).toBe(403)
diff --git a/apps/api/src/organization/controllers/onboarding.controller.spec.ts b/apps/api/src/organization/controllers/onboarding.controller.spec.ts
index f06cc604b..68bf74069 100644
--- a/apps/api/src/organization/controllers/onboarding.controller.spec.ts
+++ b/apps/api/src/organization/controllers/onboarding.controller.spec.ts
@@ -15,13 +15,7 @@ import { OnboardingService } from '../services/onboarding.service'
import { AuthContext } from '../../common/interfaces/auth-context.interface'
jest.mock('../services/organization.service', () => ({ OrganizationService: class {} }))
-jest.mock('../services/organization-user.service', () => ({
- OrganizationUserService: class {
- static membershipCacheKey() {
- return 'test-membership'
- }
- },
-}))
+jest.mock('../services/organization-user.service', () => ({ OrganizationUserService: class {} }))
jest.mock('../../common/guards/authenticated-rate-limit.guard', () => ({ AuthenticatedRateLimitGuard: class {} }))
describe('onboarding route access', () => {
@@ -113,7 +107,7 @@ describe('onboarding route access', () => {
])('enforces membership %s for %s', async (role, method, allowed) => {
const guard = new OrganizationActionGuard(
{ findOne: jest.fn().mockResolvedValue({ id: 'org' }) } as never,
- { findOne: jest.fn().mockResolvedValue(role ? { role } : null) } as never,
+ { findOneCached: jest.fn().mockResolvedValue(role ? { role } : null) } as never,
new Reflector(),
)
Object.assign(guard, { redis: { get: jest.fn().mockResolvedValue(null), set: jest.fn() } })
diff --git a/apps/api/src/organization/guards/organization-access.guard.spec.ts b/apps/api/src/organization/guards/organization-access.guard.spec.ts
index b1f5b66b1..7e4768dd6 100644
--- a/apps/api/src/organization/guards/organization-access.guard.spec.ts
+++ b/apps/api/src/organization/guards/organization-access.guard.spec.ts
@@ -32,7 +32,7 @@ function createGuard() {
findOne: jest.fn().mockResolvedValue(organization),
}
const organizationUserService = {
- findOne: jest.fn().mockResolvedValue(organizationUser),
+ findOneCached: jest.fn().mockResolvedValue(organizationUser),
}
const guard = new OrganizationAccessGuard(organizationService as any, organizationUserService as any)
@@ -61,7 +61,7 @@ describe('OrganizationAccessGuard', () => {
await expect(guard.canActivate(httpContext(request))).resolves.toBe(true)
expect(mocks.organizationService.findOne).toHaveBeenCalledWith('org-123')
- expect(mocks.organizationUserService.findOne).toHaveBeenCalledWith('org-123', 'user-1')
+ expect(mocks.organizationUserService.findOneCached).toHaveBeenCalledWith('org-123', 'user-1')
expect(request.user).toMatchObject({
organizationId: 'org-123',
organization: { id: 'org-123' },
@@ -85,7 +85,7 @@ describe('OrganizationAccessGuard', () => {
await expect(guard.canActivate(httpContext(request))).resolves.toBe(false)
expect(mocks.organizationService.findOne).not.toHaveBeenCalled()
- expect(mocks.organizationUserService.findOne).not.toHaveBeenCalled()
+ expect(mocks.organizationUserService.findOneCached).not.toHaveBeenCalled()
})
// The membership lookup answers for any user: TypeORM drops a where condition
diff --git a/apps/api/src/organization/guards/organization-access.guard.ts b/apps/api/src/organization/guards/organization-access.guard.ts
index eedfc9c29..5fb62c89c 100644
--- a/apps/api/src/organization/guards/organization-access.guard.ts
+++ b/apps/api/src/organization/guards/organization-access.guard.ts
@@ -12,7 +12,6 @@ import { SystemRole } from '../../user/enums/system-role.enum'
import { InjectRedis } from '@nestjs-modules/ioredis'
import Redis from 'ioredis'
import { Organization } from '../entities/organization.entity'
-import { OrganizationUser } from '../entities/organization-user.entity'
@Injectable()
export class OrganizationAccessGuard implements CanActivate {
@@ -95,7 +94,7 @@ export class OrganizationAccessGuard implements CanActivate {
return false
}
- const organizationUser = await this.getCachedOrganizationUser(organizationId, authContext.userId)
+ const organizationUser = await this.organizationUserService.findOneCached(organizationId, authContext.userId)
if (!organizationUser) {
this.logger.warn(
@@ -142,23 +141,4 @@ export class OrganizationAccessGuard implements CanActivate {
return null
}
}
-
- private async getCachedOrganizationUser(organizationId: string, userId: string): Promise<OrganizationUser | null> {
- const cacheKey = OrganizationUserService.membershipCacheKey(organizationId, userId)
- try {
- const cachedOrganizationUser = await this.redis.get(cacheKey)
- if (cachedOrganizationUser) {
- return JSON.parse(cachedOrganizationUser)
- }
- const organizationUser = await this.organizationUserService.findOne(organizationId, userId)
- if (organizationUser) {
- await this.redis.set(cacheKey, JSON.stringify(organizationUser), 'EX', 10)
- return organizationUser
- }
- return null
- } catch (ex) {
- this.logger.error('Error getting cached organization user:', ex)
- return null
- }
- }
}
diff --git a/apps/api/src/organization/guards/organization-resource-action.guard.spec.ts b/apps/api/src/organization/guards/organization-resource-action.guard.spec.ts
index 88dced6b7..ee7072714 100644
--- a/apps/api/src/organization/guards/organization-resource-action.guard.spec.ts
+++ b/apps/api/src/organization/guards/organization-resource-action.guard.spec.ts
@@ -40,7 +40,7 @@ function httpContext(request: Record<string, unknown>, handler = function handle
function createGuard() {
const reflector = new Reflector()
const organizationService = { findOne: jest.fn() }
- const organizationUserService = { findOne: jest.fn() }
+ const organizationUserService = { findOneCached: jest.fn() }
const guard = new OrganizationResourceActionGuard(
organizationService as never,
organizationUserService as never,
@@ -76,7 +76,7 @@ describe('OrganizationResourceActionGuard', () => {
await expect(guard.canActivate(httpContext(request, handler))).resolves.toBe(true)
expect(organizationService.findOne).not.toHaveBeenCalled()
- expect(organizationUserService.findOne).not.toHaveBeenCalled()
+ expect(organizationUserService.findOneCached).not.toHaveBeenCalled()
})
it('lets runner-authenticated box resource routes defer access checks to BoxAccessGuard', async () => {
@@ -96,7 +96,7 @@ describe('OrganizationResourceActionGuard', () => {
await expect(guard.canActivate(httpContext(request, handler))).resolves.toBe(true)
expect(organizationService.findOne).not.toHaveBeenCalled()
- expect(organizationUserService.findOne).not.toHaveBeenCalled()
+ expect(organizationUserService.findOneCached).not.toHaveBeenCalled()
})
// The exemption is keyed on the role first, the guard second. A human context
@@ -141,7 +141,7 @@ describe('OrganizationResourceActionGuard', () => {
await expect(guard.canActivate(httpContext(request, handler))).resolves.toBe(true)
expect(organizationService.findOne).not.toHaveBeenCalled()
- expect(organizationUserService.findOne).not.toHaveBeenCalled()
+ expect(organizationUserService.findOneCached).not.toHaveBeenCalled()
})
it('does not bypass organization context for runner users on non-runner routes', async () => {
@@ -166,7 +166,7 @@ describe('OrganizationResourceActionGuard', () => {
await expect(guard.canActivate(httpContext({ params: {} }))).resolves.toBe(false)
expect(organizationService.findOne).not.toHaveBeenCalled()
- expect(organizationUserService.findOne).not.toHaveBeenCalled()
+ expect(organizationUserService.findOneCached).not.toHaveBeenCalled()
})
})
@@ -194,7 +194,7 @@ describe('OrganizationResourceActionGuard resource permissions', () => {
function memberOf(role: 'owner' | 'member') {
const { guard, organizationService, organizationUserService } = createGuard()
organizationService.findOne.mockResolvedValue({ id: 'org-1' })
- organizationUserService.findOne.mockResolvedValue({ role, assignedRoles: [] })
+ organizationUserService.findOneCached.mockResolvedValue({ role, assignedRoles: [] })
return guard
}
diff --git a/apps/api/src/organization/services/organization-user-lookup.spec.ts b/apps/api/src/organization/services/organization-user-lookup.spec.ts
index 83725fb60..8a696fd21 100644
--- a/apps/api/src/organization/services/organization-user-lookup.spec.ts
+++ b/apps/api/src/organization/services/organization-user-lookup.spec.ts
@@ -7,30 +7,57 @@ import { OrganizationUserService } from './organization-user.service'
import { OrganizationMemberRole } from '../enums/organization-member-role.enum'
describe('OrganizationUserService membership lookups', () => {
+ const organizationId = 'org-1'
+ const userId = 'user-1'
+
// TypeORM drops a where condition whose value is undefined, so the repository
// answers with the organization's member whatever user is asked for.
function serviceOverOneMember() {
- const member = { organizationId: 'org-1', userId: 'user-1', role: OrganizationMemberRole.OWNER }
+ const member = { organizationId, userId, role: OrganizationMemberRole.OWNER }
const repository = {
findOne: jest.fn(async () => member),
exists: jest.fn(async () => true),
}
- return new OrganizationUserService(
+ const redis = { get: jest.fn().mockResolvedValue(null) }
+ const service = new OrganizationUserService(
repository as never,
{} as never,
{} as never,
{} as never,
{} as never,
- {} as never,
+ redis as never,
)
+ return { service, repository, redis }
}
// Machine credentials (runner, proxy, ...) carry no user, and callers such as the
// preview access check pass their missing user id straight through.
it('finds no membership for a caller without a user', async () => {
- const service = serviceOverOneMember()
+ const { service } = serviceOverOneMember()
+
+ await expect(service.findOne(organizationId, undefined as never)).resolves.toBeNull()
+ await expect(service.exists(organizationId, undefined as never)).resolves.toBe(false)
+ })
+
+ it.each([
+ ['organization', undefined as never, userId],
+ ['user', organizationId, undefined as never],
+ ] as const)('skips membership reads when the %s ID is missing', async (_identifier, orgId, memberId) => {
+ const { service, repository, redis } = serviceOverOneMember()
+
+ await expect(service.findOneCached(orgId, memberId)).resolves.toBeNull()
+
+ expect(redis.get).not.toHaveBeenCalled()
+ expect(repository.findOne).not.toHaveBeenCalled()
+ })
+
+ it('returns no membership when Redis cannot read the cached membership', async () => {
+ const { service, repository, redis } = serviceOverOneMember()
+ redis.get.mockRejectedValueOnce(new Error('Redis unavailable'))
+
+ await expect(service.findOneCached(organizationId, userId)).resolves.toBeNull()
- await expect(service.findOne('org-1', undefined as never)).resolves.toBeNull()
- await expect(service.exists('org-1', undefined as never)).resolves.toBe(false)
+ expect(redis.get).toHaveBeenCalled()
+ expect(repository.findOne).not.toHaveBeenCalled()
})
})
diff --git a/apps/api/src/organization/services/organization-user.service.ts b/apps/api/src/organization/services/organization-user.service.ts
index 0f6dbf62d..25b87c5d0 100644
--- a/apps/api/src/organization/services/organization-user.service.ts
+++ b/apps/api/src/organization/services/organization-user.service.ts
@@ -39,7 +39,7 @@ export class OrganizationUserService {
@InjectRedis() private readonly redis: Redis,
) {}
- /** Redis key under which OrganizationAccessGuard caches a membership. */
+ /** Redis key for the membership snapshot used by resource authorization. */
static membershipCacheKey(organizationId: string, userId: string): string {
return `organization-user:${organizationId}:${userId}`
}
@@ -93,6 +93,29 @@ export class OrganizationUserService {
})
}
+ async findOneCached(organizationId: string, userId: string): Promise<OrganizationUser | null> {
+ if (!organizationId || !userId) {
+ return null
+ }
+
+ const cacheKey = OrganizationUserService.membershipCacheKey(organizationId, userId)
+ try {
+ const cached = await this.redis.get(cacheKey)
+ if (cached) {
+ return JSON.parse(cached)
+ }
+
+ const membership = await this.findOne(organizationId, userId)
+ if (membership) {
+ await this.redis.set(cacheKey, JSON.stringify(membership), 'EX', 10)
+ }
+ return membership
+ } catch (error) {
+ this.logger.error('Error getting cached organization user:', error)
+ return null
+ }
+ }
+
/** The membership a user marked as their default, with the permissions it holds. */
async findDefault(
userId: string,
diff --git a/apps/api/src/organization/services/organization.service.spec.ts b/apps/api/src/organization/services/organization.service.spec.ts
index 52dc0ce8b..3a12fdfdc 100644
--- a/apps/api/src/organization/services/organization.service.spec.ts
+++ b/apps/api/src/organization/services/organization.service.spec.ts
@@ -164,7 +164,7 @@ describe('OrganizationService.assertOrganizationIsNotSuspended', () => {
organization({ suspended: true, suspendedUntil, suspensionReason: 'flagged for suspected abuse by support' }),
)
const guard = new OrganizationAccessGuard(service, {
- findOne: jest.fn().mockResolvedValue({ organizationId: 'org-1', userId: 'user-1' }),
+ findOneCached: jest.fn().mockResolvedValue({ organizationId: 'org-1', userId: 'user-1' }),
} as any)
const cache = new Map<string, string>()
;(guard as any).redis = {
diff --git a/apps/api/src/registry/controllers/registries-update.controller.spec.ts b/apps/api/src/registry/controllers/registries-update.controller.spec.ts
index 5e6a303df..cccba44a0 100644
--- a/apps/api/src/registry/controllers/registries-update.controller.spec.ts
+++ b/apps/api/src/registry/controllers/registries-update.controller.spec.ts
@@ -31,14 +31,14 @@ describe('Registry credential update HTTP boundary', () => {
const audit = { createLog: jest.fn(), updateLog: jest.fn() }
beforeAll(async () => {
- // Exercise the real resource guard with cached organization/membership
- // data; only authentication and the rate limiter are outside this test.
- const guard = Object.assign(new OrganizationResourceActionGuard({} as never, {} as never, new Reflector()), {
- redis: {
- get: async (key: string) =>
- JSON.stringify(key === `organization:${ORG}` ? { id: ORG } : { role: OrganizationMemberRole.OWNER }),
- },
- })
+ const guard = Object.assign(
+ new OrganizationResourceActionGuard(
+ {} as never,
+ { findOneCached: async () => ({ role: OrganizationMemberRole.OWNER }) } as never,
+ new Reflector(),
+ ),
+ { redis: { get: async () => JSON.stringify({ id: ORG }) } },
+ )
const moduleRef = await Test.createTestingModule({
controllers: [RegistriesController],
providers: [{ provide: RegistriesService, useValue: service }],
diff --git a/apps/e2e/README.md b/apps/e2e/README.md
index 9eb84b610..1f98742e6 100644
--- a/apps/e2e/README.md
+++ b/apps/e2e/README.md
@@ -452,9 +452,9 @@ stage. It is dispatch-only, plus one call from `deploy-infra.yml`:
| `prod` | `api.boxlite.ai` | `-m smoke` | no |
The workflow writes the selected stage's credentials to
-`~/.boxlite/credentials.toml` with mode `0600`. Each key's organization is
-discovered through `/v1/me`; API-key permissions come from `/api-keys/current`,
-not the placeholder scopes in `/v1/me`.
+`~/.boxlite/credentials.toml` with mode `0600`. The workflow discovers each key's
+organization through `/v1/me` and reads its stored permission names through
+`/api-keys/current`.
| Stage | Repository secret | Profile | Role |
| --- | --- | --- | --- |
diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.md
index 75e3556f0..7c0ef5eec 100644
--- a/docs/contributing/architecture/platform/api.md
+++ b/docs/contributing/architecture/platform/api.md
@@ -694,12 +694,14 @@ registry login routes `read:registries`, `write:registries`, or
`delete:registries`. Attaching a managed volume while creating a box is authorized
independently of `write:boxes`: the caller must also hold `read:volumes` and
`write:volumes`, so a box-only credential cannot reach another's volume data
-(GHSA-2qqv-7cwv-mj8h). A system admin and an interactive owner without an API key
-are not permission-bounded; every API key is bounded by the permissions it
-carries. The WebSocket `/attach` upgrade enforces `write:boxes` inline — an
-upgrade never passes through the organization guard — using the same admin and
-owner exemptions, so it resolves the caller's system role just as the HTTP path
-does. A browser, which cannot set `Authorization` on a WebSocket, instead sends a
+(GHSA-2qqv-7cwv-mj8h). Resource permission checks exempt system administrators,
+including their API keys. Organization owners have all organization resource
+permissions in an interactive session. API keys issued to ordinary users are
+bounded by their stored permissions. The WebSocket `/attach` upgrade enforces
+`write:boxes` inline — an upgrade never passes through the organization guard —
+using the same administrator and owner exemptions. It resolves the caller's
+system role as the HTTP path does. A browser, which cannot set `Authorization`
+on a WebSocket, instead sends a
`?ticket=` bought from `POST /box/{boxIdOrName}/attach-tickets`. Spending it
re-checks the ticket's credential the same way:
the API key that bought it, which must still exist and be unexpired, or else
@@ -707,6 +709,14 @@ its user. The attach URL may omit `{prefix}`; the ticket already names the organ
`GET /v1/me` can return `path_prefix: null` for an authenticated user with no
organization membership.
+`GET /v1/me` evaluates scopes in the organization resolved by `path_prefix`,
+using the same ten-second membership cache and permission policy as the HTTP
+resource guards. An ordinary user's API key with `write:boxes` alone receives
+`box:read`, `box:write`, `box:exec`, and `me:read`. The Box and volume deletion
+scopes are `box:delete` and `volume:delete`, corresponding to `delete:boxes` and
+`delete:volumes`. Ordinary users without organization access receive
+`me:read` alone.
+
<details>
<summary><b>Discovery</b> · 2 routes</summary>