Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(acceptance): let a Task run's operation token file evidence into its own round (#21335)

LiJian723a69f6744b
diff --git a/apps/server/src/routers/lambda/file/upload.operationToken.test.ts b/apps/server/src/routers/lambda/file/upload.operationToken.test.ts
new file mode 100644
index 00000000000..d5bd746156a
--- /dev/null
+++ b/apps/server/src/routers/lambda/file/upload.operationToken.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FileSource } from '@/types/files';
+
+import { uploadRouter } from './upload';
+
+const mocks = vi.hoisted(() => {
+ const transaction = {};
+ return {
+ checkHash: vi.fn(),
+ create: vi.fn(),
+ serverDB: {
+ transaction: vi.fn(async (callback: (trx: unknown) => unknown) => callback(transaction)),
+ },
+ transaction,
+ };
+});
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => mocks.serverDB) }));
+vi.mock('@/business/server/lambda-routers/file', () => ({
+ businessFileUploadCheck: vi.fn(),
+}));
+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));
+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));
+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn(function () {
+ return { checkHash: mocks.checkHash, create: mocks.create };
+ }),
+}));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(function () {
+ return {
+ getFileAccessUrl: vi.fn(async ({ id }: { id: string }) => `https://lobehub.com/f/${id}`),
+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 100 }),
+ };
+ }),
+}));
+vi.mock('@/server/services/fileUpload', () => ({
+ FileUploadService: vi.fn(function () {
+ return {
+ findLatest: vi.fn().mockResolvedValue(undefined),
+ hasAnyLiveSession: vi.fn().mockResolvedValue(false),
+ };
+ }),
+}));
+
+const upload = {
+ fileType: 'image/png',
+ hash: 'evidence-hash',
+ metadata: {},
+ name: 'R11-ENV-recheck.png',
+ size: 100,
+ url: 'files/2026-10-21/evidence-hash.png',
+};
+
+const operationCaller = () =>
+ uploadRouter.createCaller({
+ heteroOperationScope: 'op_task_run',
+ userId: 'operation-owner',
+ workspaceId: 'workspace-1',
+ } as any);
+
+describe('uploadRouter.createFile with a run operation token', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.checkHash.mockResolvedValue({ isExist: false });
+ mocks.create.mockResolvedValue({ id: 'evidence-file' });
+ });
+
+ it('files the upload as private acceptance evidence', async () => {
+ // The acceptance CLI uploads evidence with no source or visibility. Under the
+ // run's token it must not land in the creator's resource library.
+ await operationCaller().createFile(upload);
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ knowledgeBaseId: undefined,
+ parentId: undefined,
+ source: FileSource.Acceptance,
+ visibility: 'private',
+ }),
+ true,
+ mocks.transaction,
+ );
+ });
+
+ it.each([
+ ['a document parent', { parentId: 'docs_owner_folder' }],
+ ['a knowledge base', { knowledgeBaseId: 'kb_owner' }],
+ ['public visibility', { visibility: 'public' as const }],
+ ['another source', { source: FileSource.PageEditor }],
+ ])('refuses %s', async (_label, extra) => {
+ await expect(operationCaller().createFile({ ...upload, ...extra })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+
+ it('leaves a user session free to file into its library', async () => {
+ await uploadRouter
+ .createCaller({ userId: 'operation-owner', workspaceId: 'workspace-1' } as any)
+ .createFile({ ...upload, source: FileSource.PageEditor, visibility: 'public' });
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ source: FileSource.PageEditor, visibility: 'public' }),
+ true,
+ mocks.transaction,
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/file/upload.ts b/apps/server/src/routers/lambda/file/upload.ts
index 5491868fc2b..f4576e9b4d4 100644
--- a/apps/server/src/routers/lambda/file/upload.ts
+++ b/apps/server/src/routers/lambda/file/upload.ts
@@ -33,6 +33,38 @@ const isStoredObjectAvailable = async (fileService: FileService, url: string): P
}
};
+/**
+ * A run's operation token reaches `createFile` only to upload evidence into its
+ * own acceptance round (see `authorizeHeteroOperationEvidence`). Keep what it
+ * creates out of the creator's library: no folder or document parent, no
+ * knowledge base, never public, and always filed as acceptance evidence, which
+ * the resource listings hide.
+ */
+const scopeOperationTokenUpload = <
+ T extends {
+ knowledgeBaseId?: string;
+ parentId?: string;
+ source?: string;
+ visibility?: 'private' | 'public';
+ },
+>(
+ input: T,
+): T => {
+ if (
+ input.parentId ||
+ input.knowledgeBaseId ||
+ input.visibility === 'public' ||
+ (input.source !== undefined && input.source !== FileSource.Acceptance)
+ ) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: "This run's token can only upload acceptance evidence",
+ });
+ }
+
+ return { ...input, source: FileSource.Acceptance, visibility: 'private' };
+};
+
export const uploadRouter = router({
checkFileHash: fileProcedure
.use(withScopedPermission('file:upload'))
@@ -56,7 +88,8 @@ export const uploadRouter = router({
visibility: z.enum(['private', 'public']).optional(),
}),
)
- .mutation(async ({ ctx, input }) => {
+ .mutation(async ({ ctx, input: requested }) => {
+ const input = ctx.heteroOperationScope ? scopeOperationTokenUpload(requested) : requested;
const metadata = stripAgentShareFileProvenance(input.metadata);
const existingFile = await ctx.fileModel.checkHash(input.hash!);
const { isExist } = existingFile;
diff --git a/apps/server/src/routers/lambda/upload.test.ts b/apps/server/src/routers/lambda/upload.test.ts
index 7c585c138a0..f83b549f606 100644
--- a/apps/server/src/routers/lambda/upload.test.ts
+++ b/apps/server/src/routers/lambda/upload.test.ts
@@ -262,3 +262,58 @@ describe('uploadRouter', () => {
expect(routerMocks.createPreSignedUploadPartUrl).not.toHaveBeenCalled();
});
});
+
+describe("uploadRouter with a run's operation token", () => {
+ const caller = uploadRouter.createCaller({
+ heteroOperationScope: 'op_task_run',
+ userId: 'user-1',
+ } as any);
+ const evidencePath = `files/2026-10-21/${'a'.repeat(64)}.png`;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ routerMocks.businessFileUploadCheck.mockResolvedValue(undefined);
+ routerMocks.createPreSignedUrl.mockResolvedValue('https://example.com/upload');
+ routerMocks.getFileMetadata.mockRejectedValue(
+ Object.assign(new Error('Not Found'), { name: 'NotFound' }),
+ );
+ routerMocks.model.findActiveByPathname.mockResolvedValue(undefined);
+ routerMocks.model.create.mockImplementation(async (input: Record<string, unknown>) =>
+ createUpload(input),
+ );
+ });
+
+ it('signs a sized evidence upload through the reservation', async () => {
+ await expect(caller.createS3PreSignedUrl({ pathname: evidencePath, size: 100 })).resolves.toBe(
+ 'https://example.com/upload',
+ );
+
+ expect(routerMocks.model.create).toHaveBeenCalledWith(
+ expect.objectContaining({ pathname: evidencePath, size: 100 }),
+ routerMocks.transactionClient,
+ );
+ expect(routerMocks.createPreSignedUrl).toHaveBeenCalledWith(evidencePath, 100);
+ });
+
+ it.each([
+ ['an unsized PUT', { pathname: evidencePath }],
+ ['a pathname of its choosing', { pathname: 'files/avatars/owner.png', size: 100 }],
+ ['a traversal out of the files tree', { pathname: `files/../${'a'.repeat(64)}`, size: 100 }],
+ ])('refuses %s', async (_label, input) => {
+ // Without the reservation the signed key could overwrite an existing object
+ // and the upload would bypass quota and the length bound.
+ await expect(caller.createS3PreSignedUrl(input)).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(routerMocks.model.create).not.toHaveBeenCalled();
+ expect(routerMocks.createPreSignedUrl).not.toHaveBeenCalled();
+ });
+
+ it('still refuses a content-addressed key that already holds an object', async () => {
+ routerMocks.getFileMetadata.mockResolvedValue({ contentLength: 100 });
+
+ await expect(
+ caller.createS3PreSignedUrl({ pathname: evidencePath, size: 100 }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(routerMocks.createPreSignedUrl).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/upload.ts b/apps/server/src/routers/lambda/upload.ts
index 8a3fa77e87b..8f293da65d1 100644
--- a/apps/server/src/routers/lambda/upload.ts
+++ b/apps/server/src/routers/lambda/upload.ts
@@ -1,5 +1,6 @@
import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import type { FileUploadItem } from '@lobechat/database/schemas';
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
@@ -30,6 +31,31 @@ const uploadSizeSchema = z
.max(MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE)
.optional();
+/**
+ * The content-addressed key the CLI derives for an upload:
+ * `files/<YYYY-MM-DD>/<sha256>[.<ext>]` (`uploadFileBuffer`).
+ */
+const CONTENT_ADDRESSED_PATHNAME = /^files\/\d{4}-\d{2}-\d{2}\/[\da-f]{64}(?:\.[\w-]{1,16})?$/;
+
+/**
+ * A run's operation token reaches this router only to upload acceptance
+ * evidence. It must sign a sized PUT through the reservation, which charges
+ * quota, bounds the length and refuses a key that already holds an object, and
+ * only under a content-addressed key, never a pathname of its choosing.
+ */
+const assertOperationTokenUpload = (
+ ctx: { heteroOperationScope?: string },
+ input: { pathname: string; size?: number },
+) => {
+ if (!ctx.heteroOperationScope) return;
+ if (input.size === undefined || !CONTENT_ADDRESSED_PATHNAME.test(input.pathname)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: "This run's token uploads only sized evidence under a content-addressed path",
+ });
+ }
+};
+
const uploadProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -239,6 +265,7 @@ export const uploadRouter = router({
.use(withScopedPermission('file:upload'))
.input(z.object({ pathname: z.string().min(1), size: uploadSizeSchema }))
.mutation(async ({ ctx, input }) => {
+ assertOperationTokenUpload(ctx, input);
const s3 = new FileS3();
if (input.size === undefined) return s3.createPreSignedUrl(input.pathname);
diff --git a/apps/server/src/routers/lambda/user/profile.operationToken.test.ts b/apps/server/src/routers/lambda/user/profile.operationToken.test.ts
new file mode 100644
index 00000000000..ed6de1bdff8
--- /dev/null
+++ b/apps/server/src/routers/lambda/user/profile.operationToken.test.ts
@@ -0,0 +1,86 @@
+// @vitest-environment node
+import { Plans } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getReferralStatus, getSubscriptionPlan } from '@/business/server/user';
+import { MessageModel } from '@/database/models/message';
+import { SessionModel } from '@/database/models/session';
+import { UserModel } from '@/database/models/user';
+
+import { userRouter } from '.';
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/business/server/user', () => ({
+ getReferralStatus: vi.fn(),
+ getSubscriptionPlan: vi.fn(),
+ onUserActivityForBusiness: vi.fn(),
+}));
+vi.mock('@/database/server', () => ({ serverDB: {} }));
+vi.mock('@/database/models/message');
+vi.mock('@/database/models/session');
+vi.mock('@/database/models/user');
+vi.mock('@/server/modules/KeyVaultsEncrypt');
+vi.mock('@/server/modules/S3');
+vi.mock('@/server/services/user');
+vi.mock('@/server/services/understanding/service', () => ({
+ createUnderstandingService: vi.fn(),
+}));
+vi.mock('@/server/services/taskRecommendation/service', () => ({
+ createTaskRecommendationService: vi.fn(),
+ TaskRecommendationNotFoundError: class extends Error {},
+}));
+vi.mock('@/server/workflows/onboardingUnderstanding', () => ({
+ UnderstandingWorkflowUnavailableError: class extends Error {},
+}));
+
+const settings = {
+ general: { responseLanguage: 'zh-CN' },
+ keyVaults: { openai: { apiKey: 'sk-secret' } },
+ market: { accessToken: 'market-token' },
+};
+
+describe('userRouter.getUserState with a run operation token', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(getReferralStatus).mockResolvedValue(undefined);
+ vi.mocked(getSubscriptionPlan).mockResolvedValue(Plans.Free);
+ vi.mocked(UserModel).mockImplementation(function () {
+ return {
+ getUserSettings: vi.fn().mockResolvedValue(settings),
+ getUserState: vi.fn().mockResolvedValue({ email: '[email protected]', settings }),
+ } as any;
+ });
+ vi.mocked(MessageModel).mockImplementation(function () {
+ return { countUpTo: vi.fn().mockResolvedValue(0) } as any;
+ });
+ vi.mocked(SessionModel).mockImplementation(function () {
+ return { hasMoreThanN: vi.fn().mockResolvedValue(false) } as any;
+ });
+ });
+
+ it('returns only the report language', async () => {
+ // The acceptance CLI reads the response language through this route, and the
+ // token sits in the run's environment where the agent can read it: no
+ // credentials, and none of the creator's profile, plan or onboarding state.
+ const state = await userRouter
+ .createCaller({ heteroOperationScope: 'op_task_run', userId: 'operation-owner' } as any)
+ .getUserState();
+
+ expect(state).toEqual({
+ preference: {},
+ settings: { general: { responseLanguage: 'zh-CN' } },
+ userId: 'operation-owner',
+ });
+ expect(getSubscriptionPlan).not.toHaveBeenCalled();
+ expect(getReferralStatus).not.toHaveBeenCalled();
+ });
+
+ it('still returns the full state, credentials included, to a user session', async () => {
+ const state = await userRouter
+ .createCaller({ userId: 'operation-owner' } as any)
+ .getUserState();
+
+ expect(state.email).toBe('[email protected]');
+ expect(state.settings).toEqual(settings);
+ });
+});
diff --git a/apps/server/src/routers/lambda/user/profile.ts b/apps/server/src/routers/lambda/user/profile.ts
index 80cb2e33f43..c8a09ae4f43 100644
--- a/apps/server/src/routers/lambda/user/profile.ts
+++ b/apps/server/src/routers/lambda/user/profile.ts
@@ -61,6 +61,22 @@ export const profileRouter = router({
return ctx.userModel.getUserSSOProviders();
}),
getUserState: userProcedure.query(async ({ ctx }): Promise<UserInitializationState> => {
+ // A run's operation token reaches this route only for the acceptance CLI's
+ // report-language check, and it sits in the run's environment where the
+ // agent can read it. Return the response language and nothing else of the
+ // creator's profile; the token's calls are not the creator's activity.
+ if (ctx.heteroOperationScope) {
+ const userSettings = await ctx.userModel.getUserSettings();
+ const responseLanguage = (userSettings?.general as { responseLanguage?: unknown } | null)
+ ?.responseLanguage;
+
+ return {
+ preference: {},
+ settings: { general: typeof responseLanguage === 'string' ? { responseLanguage } : {} },
+ userId: ctx.userId,
+ };
+ }
+
try {
after(async () => {
try {
diff --git a/apps/server/src/routers/lambda/verify/execution.ts b/apps/server/src/routers/lambda/verify/execution.ts
index fc5bbc20308..6b3145babb0 100644
--- a/apps/server/src/routers/lambda/verify/execution.ts
+++ b/apps/server/src/routers/lambda/verify/execution.ts
@@ -8,7 +8,12 @@ import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
import { finalizeVerifyRun } from '@/server/services/verify';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
-import { resolveCheckResult, verifyProcedure, verifyWriteProcedure } from './procedures';
+import {
+ assertOperationInScope,
+ resolveCheckResult,
+ verifyProcedure,
+ verifyWriteProcedure,
+} from './procedures';
import { checkItemSchema, modelConfigSchema, onFailSchema, verifierTypeSchema } from './schemas';
const decisionSchema = z.enum(['accepted', 'rejected', 'overridden']);
@@ -196,7 +201,10 @@ export const executionRouter = router({
}),
getVerifyState: verifyProcedure
.input(z.object({ operationId: z.string() }))
- .query(async ({ ctx, input }) => ctx.runModel.getStateByOperation(input.operationId)),
+ .query(async ({ ctx, input }) => {
+ assertOperationInScope(ctx, input.operationId);
+ return ctx.runModel.getStateByOperation(input.operationId);
+ }),
skipPlan: verifyWriteProcedure
.input(z.object({ operationId: z.string() }))
.mutation(async ({ ctx, input }) => {
@@ -254,6 +262,7 @@ export const executionRouter = router({
listResults: verifyProcedure
.input(z.object({ operationId: z.string() }))
.query(async ({ ctx, input }) => {
+ assertOperationInScope(ctx, input.operationId);
const run = await ctx.runModel.findByOperation(input.operationId);
return run ? ctx.resultModel.listByRun(run.id) : [];
}),
diff --git a/apps/server/src/routers/lambda/verify/ingest.ts b/apps/server/src/routers/lambda/verify/ingest.ts
index c0f11f1a8c0..4c39d89a907 100644
--- a/apps/server/src/routers/lambda/verify/ingest.ts
+++ b/apps/server/src/routers/lambda/verify/ingest.ts
@@ -17,6 +17,8 @@ import { evidenceTypeForStoredFile, resolveLiveRoundForItem } from '@/server/ser
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import {
+ assertEvidenceOnlySubmission,
+ assertOperationInScope,
resolveCheckResult,
resolveVerifyRun,
verifyProcedure,
@@ -199,6 +201,12 @@ export const ingestRouter = router({
// Attaching evidence mutates another member's result β€” creator-scoped,
// mirroring submitCheckEvidence.
assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
+ if (ctx.heteroOperationScope) {
+ const run = result.verifyRunId
+ ? await ctx.runModel.findById(result.verifyRunId)
+ : undefined;
+ assertOperationInScope(ctx, run?.operationId);
+ }
return createVerifyEvidenceRow(ctx, result.id, input);
}),
@@ -249,11 +257,15 @@ export const ingestRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
+ assertEvidenceOnlySubmission(ctx, input);
const namedRun = input.verifyRunId
? await resolveVerifyRun(ctx, input.verifyRunId)
: await resolveRunByOperation(ctx, input.operationId!);
// The idempotent upsert overwrites the run's existing result rows.
assertWorkspaceRowManageable(ctx, namedRun.userId, 'verify run');
+ // A run's token names its own round; the repair redirect below is the
+ // server's choice, not the caller's.
+ assertOperationInScope(ctx, namedRun.operationId);
// A round whose failure already spawned a repair is never judged again;
// land the submission on the round the repair will be judged in.
const run = await resolveLiveRoundForItem(ctx, namedRun, input.checkItemId);
@@ -297,11 +309,9 @@ export const ingestRouter = router({
});
const evidence = input.evidence?.length
- ? await pMap(
- input.evidence,
- (e) => createVerifyEvidenceRow(ctx, checkResult.id, e),
- { concurrency: EVIDENCE_WRITE_CONCURRENCY },
- )
+ ? await pMap(input.evidence, (e) => createVerifyEvidenceRow(ctx, checkResult.id, e), {
+ concurrency: EVIDENCE_WRITE_CONCURRENCY,
+ })
: [];
return { checkResult, evidence };
diff --git a/apps/server/src/routers/lambda/verify/operationScope.test.ts b/apps/server/src/routers/lambda/verify/operationScope.test.ts
new file mode 100644
index 00000000000..b28bd252d48
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/operationScope.test.ts
@@ -0,0 +1,242 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as FileModelModule from '@/database/models/file';
+
+import { verifyRouter } from '.';
+
+const modelMocks = vi.hoisted(() => ({
+ createEvidence: vi.fn(),
+ findFileById: vi.fn(),
+ findResultById: vi.fn(),
+ findRunById: vi.fn(),
+ findRunByOperation: vi.fn(),
+ getStateByOperation: vi.fn(),
+ listResultsByRun: vi.fn(),
+ upsertByCheckItem: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return {
+ findById: modelMocks.findResultById,
+ listByRun: modelMocks.listResultsByRun,
+ upsertByCheckItem: modelMocks.upsertByCheckItem,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(function () {
+ return {
+ findByOperation: modelMocks.findRunByOperation,
+ findById: modelMocks.findRunById,
+ getStateByOperation: modelMocks.getStateByOperation,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/file', async (importOriginal) => {
+ const actual = await importOriginal<typeof FileModelModule>();
+ class FileModel extends actual.FileModel {
+ findById = modelMocks.findFileById as unknown as actual.FileModel['findById'];
+ }
+ return { ...actual, FileModel };
+});
+
+vi.mock('@/database/models/verifyEvidence', () => ({
+ VerifyEvidenceModel: vi.fn(function () {
+ return { create: modelMocks.createEvidence };
+ }),
+}));
+
+// The router context builds a FileService, which needs S3 env without this.
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(function () {
+ return { getFullFileUrl: vi.fn() };
+ }),
+}));
+
+const USER_ID = 'operation-owner';
+const OWN_OPERATION = 'op_own';
+
+/** A caller holding a Task run's operation token, as `oidcAuth` lets it through. */
+const createOperationCaller = () =>
+ verifyRouter.createCaller({ heteroOperationScope: OWN_OPERATION, userId: USER_ID } as any);
+
+const ownRun = { id: 'run-own', operationId: OWN_OPERATION, plan: [], userId: USER_ID };
+const otherRun = { id: 'run-other', operationId: 'op_other', plan: [], userId: USER_ID };
+
+describe("verifyRouter with a run's operation token", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ modelMocks.listResultsByRun.mockResolvedValue([]);
+ modelMocks.findFileById.mockResolvedValue(undefined);
+ });
+
+ it('files evidence into its own round by operation id', async () => {
+ modelMocks.findRunByOperation.mockResolvedValueOnce(ownRun);
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verifyRunId: 'run-own' });
+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+
+ await createOperationCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence: [{ fileId: 'files-1', type: 'screenshot' }],
+ operationId: OWN_OPERATION,
+ });
+
+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'run-own' }),
+ );
+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect.objectContaining({ checkResultId: 'result-1', fileId: 'files-1' }),
+ );
+ });
+
+ it("refuses another operation's round, by operation id or by run id", async () => {
+ modelMocks.findRunByOperation.mockResolvedValueOnce(otherRun);
+ await expect(
+ createOperationCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ operationId: 'op_other',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ modelMocks.findRunById.mockResolvedValueOnce(otherRun);
+ await expect(
+ createOperationCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ verifyRunId: 'run-other',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
+ });
+
+ it('keeps the observation a plan-round ingest sends', async () => {
+ modelMocks.findRunByOperation.mockResolvedValueOnce(ownRun);
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verifyRunId: 'run-own' });
+
+ await createOperationCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ operationId: OWN_OPERATION,
+ toulmin: { evidence: 'Ports are closed and git is clean after cleanup.' },
+ });
+
+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toulmin: { evidence: 'Ports are closed and git is clean after cleanup.' },
+ verdict: undefined,
+ }),
+ );
+ });
+
+ it.each([
+ ['a verdict', { verdict: 'passed' as const }],
+ ['a terminal status', { status: 'passed' as const }],
+ ['a confidence', { confidence: 1 }],
+ ['required-ness', { required: false }],
+ ['a verifier type', { verifierType: 'agent' as const }],
+ ['a title', { checkItemTitle: 'Renamed check' }],
+ ['a suggestion', { suggestion: 'Ship it' }],
+ ['Toulmin reasoning', { toulmin: { evidence: 'seen', reasoning: 'so it passes' } }],
+ ])('refuses %s, which only the verifier sets', async (_label, authored) => {
+ // A prompt-injected Task must not settle its own check before the
+ // independent verifier judges the evidence.
+ modelMocks.findRunByOperation.mockResolvedValue(ownRun);
+
+ await expect(
+ createOperationCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ operationId: OWN_OPERATION,
+ ...authored,
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
+ });
+
+ it('lets a user session submit a verdict', async () => {
+ modelMocks.findRunByOperation.mockResolvedValueOnce(ownRun);
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verifyRunId: 'run-own' });
+
+ await verifyRouter.createCaller({ userId: USER_ID } as any).submitCheckEvidence({
+ checkItemId: 'item-1',
+ operationId: OWN_OPERATION,
+ verdict: 'passed',
+ });
+
+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'passed', verdict: 'passed' }),
+ );
+ });
+
+ it("refuses evidence on a check result from another operation's round", async () => {
+ modelMocks.findResultById.mockResolvedValueOnce({
+ id: 'result-other',
+ userId: USER_ID,
+ verifyRunId: 'run-other',
+ });
+ modelMocks.findRunById.mockResolvedValueOnce(otherRun);
+
+ await expect(
+ createOperationCaller().uploadEvidence({
+ checkResultId: 'result-other',
+ content: 'note',
+ type: 'text',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(modelMocks.createEvidence).not.toHaveBeenCalled();
+ });
+
+ it('attaches evidence to a check result in its own round', async () => {
+ modelMocks.findResultById.mockResolvedValueOnce({
+ id: 'result-own',
+ userId: USER_ID,
+ verifyRunId: 'run-own',
+ });
+ modelMocks.findRunById.mockResolvedValueOnce(ownRun);
+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+
+ await createOperationCaller().uploadEvidence({
+ checkResultId: 'result-own',
+ content: 'note',
+ type: 'text',
+ });
+
+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect.objectContaining({ checkResultId: 'result-own' }),
+ );
+ });
+
+ it("reads only its own round's state, results and run", async () => {
+ modelMocks.getStateByOperation.mockResolvedValueOnce({ verifyRunId: 'run-own' });
+ await expect(
+ createOperationCaller().getVerifyState({ operationId: OWN_OPERATION }),
+ ).resolves.toEqual({ verifyRunId: 'run-own' });
+
+ await expect(
+ createOperationCaller().getVerifyState({ operationId: 'op_other' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ createOperationCaller().listResults({ operationId: 'op_other' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ modelMocks.findRunById.mockResolvedValueOnce(otherRun);
+ await expect(
+ createOperationCaller().getRun({ verifyRunId: '00000000-0000-4000-8000-000000000001' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(modelMocks.getStateByOperation).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves a user session unbound', async () => {
+ modelMocks.getStateByOperation.mockResolvedValueOnce({ verifyRunId: 'run-other' });
+
+ await expect(
+ verifyRouter
+ .createCaller({ userId: USER_ID } as any)
+ .getVerifyState({ operationId: 'op_other' }),
+ ).resolves.toEqual({ verifyRunId: 'run-other' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/verify/procedures.ts b/apps/server/src/routers/lambda/verify/procedures.ts
index 496342be4e8..74d122395f8 100644
--- a/apps/server/src/routers/lambda/verify/procedures.ts
+++ b/apps/server/src/routers/lambda/verify/procedures.ts
@@ -77,3 +77,61 @@ export const resolveCheckResult = async (
return result;
};
+
+/**
+ * A run's operation token (`heteroOperationScope`, let through by
+ * `authorizeHeteroOperationEvidence`) reaches only the round of the operation
+ * it was minted for. A user session passes through.
+ */
+export const assertOperationInScope = (
+ ctx: { heteroOperationScope?: string },
+ operationId: string | null | undefined,
+) => {
+ if (ctx.heteroOperationScope && operationId !== ctx.heteroOperationScope) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: "This run's token can only reach its own verification round",
+ });
+ }
+};
+
+/**
+ * Fields a builder may send under its run's operation token: which check the
+ * evidence answers, the evidence itself, and the observation it shows. The
+ * verdict, status, confidence, required-ness, verifier, title, index,
+ * suggestion and Toulmin judgement belong to the round's independent verifier.
+ */
+const OPERATION_TOKEN_SUBMIT_FIELDS = new Set([
+ 'checkItemId',
+ 'evidence',
+ 'operationId',
+ 'toulmin',
+ 'verifyRunId',
+]);
+
+/**
+ * Refuse a run's operation token any result-authoring field on
+ * `submitCheckEvidence`, so the Task cannot judge its own check before the
+ * verifier does. A user session passes through.
+ */
+export const assertEvidenceOnlySubmission = (
+ ctx: { heteroOperationScope?: string },
+ input: Record<string, unknown> & { toulmin?: Record<string, unknown> },
+) => {
+ if (!ctx.heteroOperationScope) return;
+
+ const authored = [
+ ...Object.keys(input).filter(
+ (key) => input[key] !== undefined && !OPERATION_TOKEN_SUBMIT_FIELDS.has(key),
+ ),
+ ...Object.keys(input.toulmin ?? {})
+ .filter((key) => input.toulmin![key] !== undefined && key !== 'evidence')
+ .map((key) => `toulmin.${key}`),
+ ];
+ if (authored.length > 0) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `This run's token submits evidence only; the verifier sets ${authored.join(', ')}`,
+ });
+ }
+};
diff --git a/apps/server/src/routers/lambda/verify/runs.ts b/apps/server/src/routers/lambda/verify/runs.ts
index 9bbe3bdbf0d..24105f63b21 100644
--- a/apps/server/src/routers/lambda/verify/runs.ts
+++ b/apps/server/src/routers/lambda/verify/runs.ts
@@ -8,7 +8,12 @@ import { FileService } from '@/server/services/file';
import { purgeVerifyRun } from '@/server/services/verify';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
-import { resolveVerifyRun, verifyProcedure, verifyWriteProcedure } from './procedures';
+import {
+ assertOperationInScope,
+ resolveVerifyRun,
+ verifyProcedure,
+ verifyWriteProcedure,
+} from './procedures';
import { checkItemSchema, verifyRunIdInputSchema } from './schemas';
const runSourceSchema = z.enum(['agent', 'agent-testing']);
@@ -175,9 +180,11 @@ export const runsRouter = router({
title: input.title,
}),
),
- getRun: verifyProcedure
- .input(verifyRunIdInputSchema)
- .query(async ({ ctx, input }) => ctx.runModel.findById(input.verifyRunId)),
+ getRun: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
+ const run = await ctx.runModel.findById(input.verifyRunId);
+ if (run) assertOperationInScope(ctx, run.operationId);
+ return run;
+ }),
// Delete a whole verification session: the run row cascades to its check
// results (β†’ their evidence) and its report via the schema FKs, and the
// evidence files only this run referenced are purged from storage.
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index d7b23eb1d8c..ef5ccf65849 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -77,8 +77,9 @@ export const prepareHeteroRun = async (
operationJwt = await signHeteroOperationJWT({
// A `/goal` run also gets `goal:manage` so it can create the goal the agent
// supervises; the server still derives the agent and topic from this
- // operation, never from the CLI.
- capabilities: heteroOperationCapabilities(prompt),
+ // operation, never from the CLI. A Task run also gets `acceptance:evidence`
+ // for its own verification round.
+ capabilities: heteroOperationCapabilities(prompt, { taskId: operationTaskId }),
operationId,
userId: deps.userId,
workspaceId: deps.workspaceId,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts
index 10190677906..9abfff1f860 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts
@@ -17,4 +17,17 @@ describe('heteroOperationCapabilities', () => {
]);
expect(heteroOperationCapabilities(undefined)).not.toContain('goal:manage');
});
+
+ it('lets a Task run file evidence into its own verification round', () => {
+ // On a device logged in as another member, the operation token is the only
+ // identity that can reach the round its creator owns.
+ expect(heteroOperationCapabilities('align the profile card', { taskId: 'task_1' })).toContain(
+ 'acceptance:evidence',
+ );
+ });
+
+ it('keeps acceptance evidence out of a run with no Task', () => {
+ expect(heteroOperationCapabilities('fix the build')).not.toContain('acceptance:evidence');
+ expect(heteroOperationCapabilities('fix the build', {})).not.toContain('acceptance:evidence');
+ });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts
index a91633d570c..6725ed14fc8 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts
@@ -11,11 +11,22 @@ import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';
* always-installed CLI, so it is granted only when the user asked for a goal
* with `/goal`: an ordinary coding run that meets instructions telling it to
* run that command must not be able to launch persistent follow-on work.
- * Renewal copies the minted claims, so a run never gains it later.
+ *
+ * `acceptance:evidence` lets a Task run file evidence into its own verification
+ * round (`lh acceptance run result submit|ingest --operation`). That round is
+ * owned by the operation's creator, so on a device logged in as another member
+ * the token is the only identity that can reach it. Only a Task run has a
+ * round to file into.
+ *
+ * Renewal copies the minted claims, so a run never gains either later.
*/
-export const heteroOperationCapabilities = (prompt: unknown): HeteroOperationCapability[] => [
+export const heteroOperationCapabilities = (
+ prompt: unknown,
+ options: { taskId?: string } = {},
+): HeteroOperationCapability[] => [
'hetero:ingest',
'hetero:finish',
'hetero:intervention:read',
...(isGoalPrompt(prompt) ? (['goal:manage'] as const) : []),
+ ...(options.taskId ? (['acceptance:evidence'] as const) : []),
];
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 45f14175ed0..1e590afcbb5 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -99,6 +99,13 @@ export interface AuthContext {
apiKeyScopes?: string[] | null;
clientIp?: string | null;
clientMetadata?: ClientMetadata;
+ /**
+ * Set only when a `hetero-operation` token was let through to an acceptance
+ * evidence route: the operation it was minted for. Those routes must keep
+ * their writes and reads on this operation's verification round β€” see
+ * `authorizeHeteroOperationEvidence`.
+ */
+ heteroOperationScope?: string;
jwtPayload?: ClientSecretPayload | null;
/**
* The browser tab this request came from, when it subscribed a one-shot
diff --git a/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts
new file mode 100644
index 00000000000..6b7757e5f04
--- /dev/null
+++ b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { trpc } from '@/libs/trpc/lambda/init';
+
+import {
+ HETERO_OPERATION_JWT_AUDIENCE,
+ HETERO_OPERATION_JWT_ISSUER,
+ HETERO_OPERATION_JWT_PURPOSE,
+} from '../../../utils/internalJwt';
+import { oidcAuth } from '../oidcAuth';
+
+const { resolvePrincipal } = vi.hoisted(() => ({ resolvePrincipal: vi.fn() }));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+
+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', () => {
+ class HeteroOperationPrincipalError extends Error {
+ constructor(
+ message: string,
+ readonly status: 401 | 403 | 409,
+ ) {
+ super(message);
+ }
+ }
+ return { HeteroOperationPrincipalError, resolveActiveHeteroOperationPrincipal: resolvePrincipal };
+});
+
+const scopeOf = ({ ctx }: { ctx: any }) => ({
+ scope: ctx.heteroOperationScope ?? null,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? null,
+});
+
+const testRouter = trpc.router({
+ verify: trpc.router({
+ deleteRun: trpc.procedure.use(oidcAuth).mutation(scopeOf),
+ submitCheckEvidence: trpc.procedure.use(oidcAuth).mutation(scopeOf),
+ }),
+});
+
+const createCaller = createCallerFactory(testRouter);
+
+const operationToken = (overrides: Record<string, unknown> = {}) => ({
+ aud: HETERO_OPERATION_JWT_AUDIENCE,
+ capabilities: ['hetero:ingest', 'hetero:finish', 'acceptance:evidence'],
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ iat: Math.floor(Date.now() / 1000),
+ iss: HETERO_OPERATION_JWT_ISSUER,
+ jti: 'jti-1',
+ operation_id: 'op_task_run',
+ purpose: HETERO_OPERATION_JWT_PURPOSE,
+ sub: 'operation-owner',
+ workspace_id: 'ws_1',
+ ...overrides,
+});
+
+describe('oidcAuth with a Task run operation token', () => {
+ beforeEach(() => {
+ resolvePrincipal.mockReset();
+ resolvePrincipal.mockResolvedValue({
+ operationId: 'op_task_run',
+ userId: 'operation-owner',
+ workspaceId: 'ws_1',
+ });
+ });
+
+ it("files evidence as the operation's owner, bound to its operation and workspace", async () => {
+ // The device running the Task may be logged in as another member; this token
+ // is the only identity that can reach the round the operation's owner holds.
+ const caller = createCaller({ oidcAuth: operationToken() } as any);
+
+ await expect(caller.verify.submitCheckEvidence()).resolves.toEqual({
+ scope: 'op_task_run',
+ userId: 'operation-owner',
+ workspaceId: 'ws_1',
+ });
+ expect(resolvePrincipal).toHaveBeenCalledWith(
+ expect.objectContaining({ capability: 'acceptance:evidence', operationId: 'op_task_run' }),
+ );
+ });
+
+ it('keeps rejecting the token on every other route', async () => {
+ const caller = createCaller({ oidcAuth: operationToken() } as any);
+
+ await expect(caller.verify.deleteRun()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(resolvePrincipal).not.toHaveBeenCalled();
+ });
+
+ it('rejects a token minted without acceptance:evidence', async () => {
+ const caller = createCaller({
+ oidcAuth: operationToken({ capabilities: ['hetero:ingest', 'hetero:finish'] }),
+ } as any);
+
+ await expect(caller.verify.submitCheckEvidence()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ });
+
+ it('rejects a workspace header that names another workspace', async () => {
+ const caller = createCaller({ oidcAuth: operationToken(), workspaceId: 'ws_other' } as any);
+
+ await expect(caller.verify.submitCheckEvidence()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ expect(resolvePrincipal).not.toHaveBeenCalled();
+ });
+
+ it('rejects the token once its run has ended', async () => {
+ const { HeteroOperationPrincipalError } =
+ await import('@/server/services/heterogeneousAgent/operationPrincipal');
+ resolvePrincipal.mockRejectedValueOnce(
+ new HeteroOperationPrincipalError('Operation has already ended', 409),
+ );
+ const caller = createCaller({ oidcAuth: operationToken() } as any);
+
+ await expect(caller.verify.submitCheckEvidence()).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ });
+});
diff --git a/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts b/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts
new file mode 100644
index 00000000000..2eee2f95ab2
--- /dev/null
+++ b/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts
@@ -0,0 +1,93 @@
+import { TRPCError } from '@trpc/server';
+
+import { validateHeteroOperationClaims } from '../../utils/internalJwt';
+import type { OIDCAuth } from '../context';
+
+/**
+ * Routes a Task run's operation token may call to file evidence into its own
+ * verification round: what `lh acceptance run result submit --operation` and
+ * `lh acceptance run ingest --operation` reach on the plan-round path.
+ *
+ * The round is owned by the operation's creator. On a device logged in as
+ * another member the token is the only identity that can reach it, so without
+ * these routes the run can produce evidence but never hand it in.
+ *
+ * The `verify.*` routes bind every read and write to `heteroOperationScope`,
+ * and `submitCheckEvidence` takes evidence only: the verdict and the rest of
+ * the result belong to the round's verifier. `upload.createS3PreSignedUrl`
+ * signs only a sized, reserved PUT under a content-addressed key.
+ * `file.createFile` files what this token uploads as private acceptance
+ * evidence, kept out of the creator's library, folders and knowledge bases, and
+ * `user.getUserState` (the report-language check) returns only the response
+ * language to it. Every other route keeps rejecting the token.
+ */
+export const HETERO_OPERATION_EVIDENCE_PATHS: ReadonlySet<string> = new Set([
+ 'file.checkFileHash',
+ 'file.createFile',
+ 'upload.abortS3Upload',
+ 'upload.createS3PreSignedUrl',
+ 'user.getUserState',
+ 'verify.getRun',
+ 'verify.getVerifyState',
+ 'verify.listResults',
+ 'verify.submitCheckEvidence',
+ 'verify.uploadEvidence',
+]);
+
+const reject = (message = 'hetero-operation tokens are not accepted on this endpoint') =>
+ new TRPCError({ code: 'UNAUTHORIZED', message });
+
+/**
+ * Let a `hetero-operation` token through to an evidence route, or throw.
+ *
+ * The token must carry `acceptance:evidence`, stay in the workspace it was
+ * minted for, and belong to a run that is still going under a principal that
+ * is still authorized β€” the same re-check every other operation endpoint makes.
+ */
+export const authorizeHeteroOperationEvidence = async (params: {
+ oidcAuth: OIDCAuth;
+ path: string;
+ workspaceId?: string | null;
+}) => {
+ const { oidcAuth, path, workspaceId } = params;
+ if (!HETERO_OPERATION_EVIDENCE_PATHS.has(path)) throw reject();
+
+ const claims = validateHeteroOperationClaims(oidcAuth as Record<string, unknown>);
+ if (!claims?.capabilities.includes('acceptance:evidence')) throw reject();
+ // A header naming another workspace must not move the token out of its own.
+ if (workspaceId && workspaceId !== claims.workspace_id) {
+ throw reject('Operation token is bound to another workspace');
+ }
+
+ // Loaded only once an operation token reaches an evidence route: `oidcAuth`
+ // sits in front of every authed router, and a static import would pull the
+ // workspace and RBAC models into each of them at module load.
+ const [
+ { getServerDB },
+ { HeteroOperationPrincipalError, resolveActiveHeteroOperationPrincipal },
+ ] = await Promise.all([
+ import('@/database/core/db-adaptor'),
+ import('@/server/services/heterogeneousAgent/operationPrincipal'),
+ ]);
+
+ try {
+ const principal = await resolveActiveHeteroOperationPrincipal({
+ capability: 'acceptance:evidence',
+ claims,
+ db: await getServerDB(),
+ operationId: claims.operation_id,
+ });
+ return {
+ heteroOperationScope: principal.operationId,
+ userId: principal.userId,
+ workspaceId: principal.workspaceId,
+ };
+ } catch (error) {
+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;
+ throw new TRPCError({
+ cause: error,
+ code: error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',
+ message: error.message,
+ });
+ }
+};
diff --git a/packages/trpc/src/lambda/middleware/oidcAuth.ts b/packages/trpc/src/lambda/middleware/oidcAuth.ts
index 1fee5184ce0..299bad598d2 100644
--- a/packages/trpc/src/lambda/middleware/oidcAuth.ts
+++ b/packages/trpc/src/lambda/middleware/oidcAuth.ts
@@ -1,20 +1,22 @@
-import { TRPCError } from '@trpc/server';
-
import { trpc } from '../init';
+import { authorizeHeteroOperationEvidence } from './heteroOperationEvidence';
export const oidcAuth = trpc.middleware(async (opts) => {
- const { ctx, next } = opts;
+ const { ctx, next, path } = opts;
// Check OIDC authentication
if (ctx.oidcAuth) {
- // hetero-operation tokens are long-lived (4h) and scoped exclusively to
- // heteroIngest / heteroFinish. Reject them here so a leaked sandbox JWT
- // cannot be replayed against any other authed route.
+ // hetero-operation tokens are long-lived (4h) and scoped to heteroIngest /
+ // heteroFinish, plus a Task run's own acceptance evidence. Reject them on
+ // every other route so a leaked sandbox JWT cannot be replayed against it.
if (ctx.oidcAuth.purpose === 'hetero-operation') {
- throw new TRPCError({
- code: 'UNAUTHORIZED',
- message: 'hetero-operation tokens are not accepted on this endpoint',
+ const scope = await authorizeHeteroOperationEvidence({
+ oidcAuth: ctx.oidcAuth,
+ path,
+ workspaceId: ctx.workspaceId,
});
+
+ return next({ ctx: { ...scope, oidcAuth: ctx.oidcAuth } });
}
return next({
diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index 8efb1493321..9d2c603601c 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -13,7 +13,12 @@ export const HETERO_OPERATION_JWT_AUDIENCE = 'urn:lobehub:hetero-operation';
export const HETERO_OPERATION_JWT_PURPOSE = 'hetero-operation';
export type HeteroOperationCapability =
- 'goal:manage' | 'hetero:finish' | 'hetero:ingest' | 'hetero:intervention:read' | 'model:invoke';
+ | 'acceptance:evidence'
+ | 'goal:manage'
+ | 'hetero:finish'
+ | 'hetero:ingest'
+ | 'hetero:intervention:read'
+ | 'model:invoke';
export interface HeteroOperationJwtClaims {
aud: typeof HETERO_OPERATION_JWT_AUDIENCE;
@@ -186,6 +191,7 @@ export const validateHeteroOperationClaims = (
!Array.isArray(capabilities) ||
!capabilities.every((capability) =>
[
+ 'acceptance:evidence',
'goal:manage',
'model:invoke',
'hetero:ingest',