feat(operations): add shared Operation layer for agent capabilities

Introduce @shumai/operations (pure definitions: Zod schemas, metadata,
CLI hints) and @shumai/core/src/operations (implementOperation and the
runOperation pipeline: validate, authorize, prepare, execute, validate
output, audit).

Migrate list_assets, create_folder, rename_asset, move_assets and
delete_asset to Operations, and add list_projects. The agent now builds
these tools from the registry, and the folder create/rename, file
rename and reparent routes call the same Operations.

Audit logs gain a nullable via column recording the surface. A lint
rule keeps the Prisma client out of Operation implementations.
This commit is contained in:
yiling
2026-10-26 11:36:36 +08:00
parent 47ee794ae4
commit 028fae0286
65 changed files with 2372 additions and 1149 deletions
+18
View File
@@ -1140,6 +1140,24 @@ export class AssetService {
throw new Error(`Asset has no team context: ${assetId}`)
}
/**
* Lightweight lookup of an asset's type and team/project, without building a full AssetInfo
* (no presigned URLs). Use it to capture context before a mutation such as a delete.
*/
async getAssetMeta(
assetId: string,
): Promise<{ id: string; name: string; type: AssetType; teamId: string; projectId?: string }> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
select: { id: true, name: true, type: true },
})
if (!asset) {
throw new HTTPException(404, { message: 'Asset not found' })
}
const { teamId, projectId } = await this.getAssetContext(assetId)
return { ...asset, teamId, projectId }
}
async resolveTargetAssetId(assetId: string): Promise<string> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
+4
View File
@@ -1,6 +1,7 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import type { AuditAction } from '@shumai/dtos'
import type { Via } from '@shumai/operations'
import { paginateQuery } from '@shumai/core/src/pagination'
import { logger } from '@shumai/core/src/logger'
@@ -11,6 +12,8 @@ export interface LogActionParams {
agentId?: string
projectId?: string
itemId?: string
/** Surface the action came through. Set by Operations; omitted elsewhere. */
via?: Via
}
export interface ListAuditLogsParams {
@@ -34,6 +37,7 @@ export class AuditLogService {
agentId: params.agentId,
projectId: params.projectId,
itemId: params.itemId,
via: params.via,
},
})
} catch (err) {
+2 -1
View File
@@ -30,7 +30,8 @@ export enum ResourceType {
}
export interface AuthzRequest {
user: User
/** Only the user's ID is used, so callers that only know the ID can pass `{ id }`. */
user: Pick<User, 'id'>
permission: Permission
type: ResourceType
id: string
@@ -0,0 +1,23 @@
import { createFolder } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const createFolderOp = implementOperation(createFolder, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.parent }],
execute: async (input, ctx) =>
toAssetSummary(
await assetService.createAsset({
name: input.name,
parentId: input.parent,
type: 'folder',
creatorId: ctx.userId,
agentId: ctx.agentId,
}),
),
audit: (_input, output) => [
{ action: AuditAction.folder_create, itemId: output.id, contextAssetId: output.id },
],
})
@@ -0,0 +1,23 @@
import { deleteAsset } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const deleteAssetOp = implementOperation(deleteAsset, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.assetId }],
// Resolve type and team before deleting: the audit entry needs them afterwards.
prepare: (input) => assetService.getAssetMeta(input.assetId),
execute: async (input) => {
await assetService.deleteAssets([input.assetId])
return { deletedAssetId: input.assetId }
},
audit: (input, _output, _ctx, asset) => [
{
action: asset.type === 'folder' ? AuditAction.folder_delete : AuditAction.file_delete,
itemId: input.assetId,
teamId: asset.teamId,
projectId: asset.projectId,
},
],
})
@@ -0,0 +1,25 @@
import { DEFAULT_PAGE_SIZE, listAssets } from '@shumai/operations'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const listAssetsOp = implementOperation(listAssets, {
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.parent }],
execute: async (input) => {
const result = await assetService.listChildren({
assetId: input.parent,
assetType: input.type ?? 'all',
first: input.first ?? DEFAULT_PAGE_SIZE,
after: input.after,
})
return {
data: result.data.map(toAssetSummary),
pageInfo: {
hasNextPage: Boolean(result.pageInfo.cursor),
endCursor: result.pageInfo.cursor ?? null,
},
total: result.pageInfo.total ?? result.data.length,
}
},
})
@@ -0,0 +1,30 @@
import { moveAssets } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const moveAssetsOp = implementOperation(moveAssets, {
authz: (input) => [
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.newParentId },
...input.assetIds.map((id) => ({
permission: Permission.Edit,
type: ResourceType.Asset,
id,
})),
],
execute: async (input, ctx) => {
await assetService.reparentAssets({
assetIds: input.assetIds,
newParentId: input.newParentId,
creatorId: ctx.userId,
})
return { movedAssetIds: input.assetIds, newParentId: input.newParentId }
},
audit: (input) =>
input.assetIds.map((assetId) => ({
action: AuditAction.asset_reparent,
itemId: assetId,
contextAssetId: input.newParentId,
})),
})
@@ -0,0 +1,19 @@
import { renameAsset } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const renameAssetOp = implementOperation(renameAsset, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.assetId }],
execute: async (input) =>
toAssetSummary(await assetService.updateAssetName({ id: input.assetId, name: input.name })),
audit: (input, output) => [
{
action: output.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update,
itemId: input.assetId,
contextAssetId: input.assetId,
},
],
})
@@ -0,0 +1,12 @@
import type { AssetSummary } from '@shumai/operations'
import type { AssetInfo } from '@shumai/dtos'
export function toAssetSummary(asset: AssetInfo): AssetSummary {
return {
id: asset.id,
name: asset.name,
type: asset.type,
size: Number(asset.sizeByte),
projectId: asset.projectId ?? null,
}
}
+17
View File
@@ -0,0 +1,17 @@
import type { Via } from '@shumai/operations'
/** Who is invoking an Operation and through which surface. */
export interface OperationContext {
/** The acting user. Permission checks and audit attribution use this user. */
userId: string
/** Where the invocation came from; recorded in audit logs. */
via: Via
/** The agent acting on the user's behalf, when invoked by Shumai's built-in agent. */
agentId?: string
/**
* Session hints from the caller (e.g. the agent's current team/project). Never used for
* authorization or audit attribution, which are always resolved from the affected resource.
*/
teamId?: string
projectId?: string
}
+66
View File
@@ -0,0 +1,66 @@
import type { z } from 'zod'
import type { AnyOperationDefinition } from '@shumai/operations'
import type { AuditAction } from '@shumai/dtos'
import type { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { OperationContext } from './context'
/** A permission the caller must hold before the Operation runs. */
export interface AuthzCheck {
permission: Permission
type: ResourceType
id: string
}
/**
* An audit log entry written after the Operation succeeds. Team and project are resolved
* from `contextAssetId`, or supplied explicitly when that asset may no longer resolve
* (e.g. after a delete; load them in `prepare`).
*/
export type AuditEntry =
| { action: AuditAction; itemId: string; contextAssetId: string }
| { action: AuditAction; itemId: string; teamId: string; projectId?: string }
export type OperationInput<TDef extends AnyOperationDefinition> = z.output<TDef['input']>
export type OperationOutput<TDef extends AnyOperationDefinition> = z.output<TDef['output']>
type OperationResult<TDef extends AnyOperationDefinition> = z.input<TDef['output']>
export interface OperationImplementation<TDef extends AnyOperationDefinition, TPrepared> {
/** Permissions required for this input. All are checked before any side effect. */
authz(
input: OperationInput<TDef>,
ctx: OperationContext,
): readonly AuthzCheck[] | Promise<readonly AuthzCheck[]>
/** Optional read-only step after authorization; its result is passed to `execute` and `audit`. */
prepare?(input: OperationInput<TDef>, ctx: OperationContext): Promise<TPrepared>
/** Perform the Operation by calling core services. Must return data matching the output schema. */
execute(
input: OperationInput<TDef>,
ctx: OperationContext,
prepared: TPrepared,
): Promise<OperationResult<TDef>>
/** Audit entries to record for a successful invocation. */
audit?(
input: OperationInput<TDef>,
output: OperationOutput<TDef>,
ctx: OperationContext,
prepared: TPrepared,
): readonly AuditEntry[] | Promise<readonly AuditEntry[]>
}
/** An Operation definition bound to its implementation. Run it with `runOperation`. */
export interface Operation<TDef extends AnyOperationDefinition = AnyOperationDefinition> {
readonly definition: TDef
readonly implementation: OperationImplementation<TDef, unknown>
}
export function implementOperation<TDef extends AnyOperationDefinition, TPrepared = undefined>(
definition: TDef,
implementation: OperationImplementation<TDef, TPrepared>,
): Operation<TDef> {
return Object.freeze({
definition,
// The prepared value only flows from this implementation's `prepare` into its own
// `execute`/`audit`, so erasing its type here is safe.
implementation: implementation as OperationImplementation<TDef, unknown>,
})
}
+18
View File
@@ -0,0 +1,18 @@
export type { OperationContext } from './context'
export {
implementOperation,
type AuditEntry,
type AuthzCheck,
type Operation,
type OperationImplementation,
type OperationInput,
type OperationOutput,
} from './implement'
export { runOperation } from './run'
export { getOperation, getOperationsForSurface, operations } from './registry'
export { createFolderOp } from './asset/create-folder'
export { deleteAssetOp } from './asset/delete-asset'
export { listAssetsOp } from './asset/list-assets'
export { moveAssetsOp } from './asset/move-assets'
export { renameAssetOp } from './asset/rename-asset'
export { listProjectsOp } from './project/list-projects'
@@ -0,0 +1,297 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { AuditAction } from '@shumai/dtos'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import {
createFolderOp,
deleteAssetOp,
listAssetsOp,
listProjectsOp,
moveAssetsOp,
renameAssetOp,
} from './index'
import { runOperation } from './run'
import type { OperationContext } from './context'
describe('asset and project Operations', () => {
setupTestDbHooks()
let owner: User
let reviewer: User
let outsider: User
let teamId: string
let projectId: string
let rootFolderId: string
const as = (user: User, via: OperationContext['via'] = 'cli'): OperationContext => ({
userId: user.id,
via,
})
beforeEach(async () => {
owner = await prisma.user.create({
data: { name: 'Owner', email: 'ops-owner@test.com', password: 'pw' },
})
reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'ops-reviewer@test.com', password: 'pw' },
})
outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'ops-outsider@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Ops Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
const project = await projectService.createProject(owner, { teamId, name: 'Ops Project' })
projectId = project.id
rootFolderId = project.rootFolder!
})
async function auditRows(action: AuditAction) {
return prisma.auditLog.findMany({ where: { action }, orderBy: { id: 'asc' } })
}
describe('create_folder', () => {
it('creates a folder attributed to the caller and audits it with via', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'Renders',
})
expect(folder).toEqual({
id: expect.any(String),
name: 'Renders',
type: 'folder',
size: 0,
projectId,
})
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.parentId).toBe(rootFolderId)
expect(row.creatorId).toBe(owner.id)
const [audit] = await auditRows(AuditAction.folder_create)
expect(audit).toMatchObject({
teamId,
projectId,
userId: owner.id,
itemId: folder.id,
via: 'cli',
})
})
it.each([
['reviewer', () => reviewer],
['non-member', () => outsider],
])('rejects a %s without creating anything', async (_label, user) => {
await expect(
runOperation(createFolderOp, as(user()), { parent: rootFolderId, name: 'Nope' }),
).rejects.toMatchObject({ status: 403 })
expect(await prisma.asset.count({ where: { name: 'Nope' } })).toBe(0)
expect(await auditRows(AuditAction.folder_create)).toHaveLength(0)
})
})
describe('list_assets', () => {
it('paginates with first/after and reports the total', async () => {
for (const name of ['a', 'b', 'c']) {
await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name })
}
const page1 = await runOperation(listAssetsOp, as(reviewer), {
parent: rootFolderId,
first: 2,
})
expect(page1.data).toHaveLength(2)
expect(page1.total).toBe(3)
expect(page1.pageInfo.hasNextPage).toBe(true)
expect(page1.pageInfo.endCursor).toEqual(expect.any(String))
const page2 = await runOperation(listAssetsOp, as(reviewer), {
parent: rootFolderId,
first: 2,
after: page1.pageInfo.endCursor!,
})
expect(page2.data).toHaveLength(1)
expect(page2.pageInfo).toEqual({ hasNextPage: false, endCursor: null })
const names = [...page1.data, ...page2.data].map((a) => a.name).sort()
expect(names).toEqual(['a', 'b', 'c'])
})
it('filters by type', async () => {
await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'only-folder' })
const files = await runOperation(listAssetsOp, as(owner), {
parent: rootFolderId,
type: 'file',
})
expect(files.data).toEqual([])
const folders = await runOperation(listAssetsOp, as(owner), {
parent: rootFolderId,
type: 'folder',
})
expect(folders.data.map((a) => a.name)).toEqual(['only-folder'])
})
it('rejects a non-member', async () => {
await expect(
runOperation(listAssetsOp, as(outsider), { parent: rootFolderId }),
).rejects.toMatchObject({ status: 403 })
})
it('rejects a page size above the maximum', async () => {
await expect(
runOperation(listAssetsOp, as(owner), { parent: rootFolderId, first: 500 }),
).rejects.toMatchObject({ status: 400 })
})
})
describe('rename_asset', () => {
it('renames and audits a folder update', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'old',
})
const renamed = await runOperation(renameAssetOp, as(owner, 'api'), {
assetId: folder.id,
name: 'new',
})
expect(renamed).toMatchObject({ id: folder.id, name: 'new', type: 'folder' })
const [audit] = await auditRows(AuditAction.folder_update)
expect(audit).toMatchObject({ itemId: folder.id, teamId, projectId, via: 'api' })
})
it('rejects a reviewer and leaves the name unchanged', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'keep',
})
await expect(
runOperation(renameAssetOp, as(reviewer), { assetId: folder.id, name: 'changed' }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.name).toBe('keep')
})
})
describe('move_assets', () => {
it('moves assets and audits each one', async () => {
const dest = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'dest',
})
const a = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'a' })
const b = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'b' })
const result = await runOperation(moveAssetsOp, as(owner, 'mcp'), {
assetIds: [a.id, b.id],
newParentId: dest.id,
})
expect(result).toEqual({ movedAssetIds: [a.id, b.id], newParentId: dest.id })
const moved = await prisma.asset.findMany({ where: { id: { in: [a.id, b.id] } } })
expect(moved.every((m) => m.parentId === dest.id)).toBe(true)
const audits = await auditRows(AuditAction.asset_reparent)
expect(audits.map((r) => r.itemId).sort()).toEqual([a.id, b.id].sort())
expect(audits.every((r) => r.via === 'mcp' && r.projectId === projectId)).toBe(true)
})
it('requires at least one asset', async () => {
await expect(
runOperation(moveAssetsOp, as(owner), { assetIds: [], newParentId: rootFolderId }),
).rejects.toMatchObject({ status: 400 })
})
it('rejects a reviewer without moving anything', async () => {
const dest = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'dest',
})
const a = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'a' })
await expect(
runOperation(moveAssetsOp, as(reviewer), { assetIds: [a.id], newParentId: dest.id }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: a.id } })
expect(row.parentId).toBe(rootFolderId)
})
})
describe('delete_asset', () => {
it('trashes the asset and audits with the context captured before deletion', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'trash-me',
})
const result = await runOperation(deleteAssetOp, as(owner, 'agent'), { assetId: folder.id })
expect(result).toEqual({ deletedAssetId: folder.id })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.isDeleted).toBe(true)
const [audit] = await auditRows(AuditAction.folder_delete)
expect(audit).toMatchObject({ itemId: folder.id, teamId, projectId, via: 'agent' })
})
it('rejects a reviewer without deleting', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'keep-me',
})
await expect(
runOperation(deleteAssetOp, as(reviewer), { assetId: folder.id }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.isDeleted).toBe(false)
})
it('returns 404 for an unknown asset', async () => {
await expect(
runOperation(deleteAssetOp, as(owner), { assetId: 'missing' }),
).rejects.toMatchObject({ status: 404 })
})
})
describe('list_projects', () => {
it("lists the caller's projects with their root folder", async () => {
const result = await runOperation(listProjectsOp, as(reviewer), {})
expect(result.data).toEqual([{ id: projectId, name: 'Ops Project', teamId, rootFolderId }])
})
it('returns nothing for a user outside every team', async () => {
const result = await runOperation(listProjectsOp, as(outsider), {})
expect(result.data).toEqual([])
})
})
describe('assetService.getAssetMeta', () => {
it('returns type and team context without building AssetInfo', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'meta',
})
await expect(assetService.getAssetMeta(folder.id)).resolves.toEqual({
id: folder.id,
name: 'meta',
type: 'folder',
teamId,
projectId,
})
})
it('throws a 404 for an unknown asset', async () => {
await expect(assetService.getAssetMeta('missing')).rejects.toMatchObject({ status: 404 })
})
})
})
@@ -0,0 +1,19 @@
import { listProjects, MAX_PAGE_SIZE } from '@shumai/operations'
import { projectService } from '@shumai/core/src/project/project'
import { implementOperation } from '../implement'
export const listProjectsOp = implementOperation(listProjects, {
// Only the caller's own projects are listed, scoped by team/project membership in the service.
authz: () => [],
execute: async (input, ctx) => {
const projects = await projectService.getUserProjects(ctx.userId, input.first ?? MAX_PAGE_SIZE)
return {
data: projects.map((p) => ({
id: p.id,
name: p.name,
teamId: p.teamId,
rootFolderId: p.rootFolder ?? null,
})),
}
},
})
+50
View File
@@ -0,0 +1,50 @@
import type { OperationName, Surface } from '@shumai/operations'
import { createFolderOp } from './asset/create-folder'
import { deleteAssetOp } from './asset/delete-asset'
import { listAssetsOp } from './asset/list-assets'
import { moveAssetsOp } from './asset/move-assets'
import { renameAssetOp } from './asset/rename-asset'
import type { Operation } from './implement'
import { listProjectsOp } from './project/list-projects'
type ImplementedName<TOps extends readonly Operation[]> = TOps[number]['definition']['name']
type MissingNames<TOps extends readonly Operation[]> = Exclude<OperationName, ImplementedName<TOps>>
/**
* Type-level guard: compiling fails with `missingImplementations` listing any definition in
* `@shumai/operations` that has no implementation here.
*/
function defineRegistry<const TOps extends readonly Operation[]>(
ops: TOps &
([MissingNames<TOps>] extends [never]
? unknown
: { missingImplementations: MissingNames<TOps> }),
): TOps {
return ops
}
/** Every implemented Operation. Each definition in `@shumai/operations` must appear exactly once. */
export const operations = defineRegistry([
listProjectsOp,
listAssetsOp,
createFolderOp,
renameAssetOp,
moveAssetsOp,
deleteAssetOp,
] as const)
const operationsByName = new Map<string, Operation>()
for (const op of operations) {
if (operationsByName.has(op.definition.name)) {
throw new Error(`Duplicate operation implementation "${op.definition.name}"`)
}
operationsByName.set(op.definition.name, op)
}
export function getOperation(name: string): Operation | undefined {
return operationsByName.get(name)
}
export function getOperationsForSurface(surface: Surface): Operation[] {
return operations.filter((op) => op.definition.surfaces.includes(surface))
}
+187
View File
@@ -0,0 +1,187 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { HTTPException } from 'hono/http-exception'
import { defineOperation } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation, type OperationImplementation } from './implement'
import { runOperation } from './run'
import type { OperationContext } from './context'
const touchThing = defineOperation({
name: 'touch_thing',
title: 'Touch Thing',
description: 'Touch a thing for testing.',
input: z.object({ thingId: z.string().min(1), otherId: z.string().optional() }),
output: z.object({ touched: z.string() }),
surfaces: ['agent'],
annotations: { readOnly: false, destructive: false },
})
const ctx: OperationContext = { userId: 'user-1', agentId: 'agent-1', via: 'agent' }
describe('runOperation', () => {
const calls: string[] = []
beforeEach(() => {
calls.length = 0
vi.spyOn(authzService, 'hasPermission').mockImplementation(async (req) => {
calls.push(`authz:${req.id}`)
})
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({
teamId: 'team-ctx',
projectId: 'project-ctx',
})
vi.spyOn(auditLogService, 'logAction').mockImplementation(async (params) => {
calls.push(`audit:${params.itemId}`)
return null
})
})
afterEach(() => {
vi.restoreAllMocks()
})
function makeOp(overrides: Partial<OperationImplementation<typeof touchThing, unknown>> = {}) {
return implementOperation(touchThing, {
authz: (input) => {
const checks = [
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.thingId },
]
if (input.otherId) {
checks.push({ permission: Permission.Read, type: ResourceType.Asset, id: input.otherId })
}
return checks
},
prepare: async () => {
calls.push('prepare')
return { label: 'prepared' }
},
execute: async (input, _ctx, prepared) => {
calls.push(`execute:${(prepared as { label: string }).label}`)
return { touched: input.thingId }
},
audit: (input) => [
{ action: AuditAction.file_update, itemId: input.thingId, contextAssetId: input.thingId },
],
...overrides,
})
}
it('runs validate → authz → prepare → execute → audit in order and returns the output', async () => {
const output = await runOperation(makeOp(), ctx, { thingId: 't1', otherId: 't2' })
expect(output).toEqual({ touched: 't1' })
expect(calls).toEqual(['authz:t1', 'authz:t2', 'prepare', 'execute:prepared', 'audit:t1'])
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 't1',
})
})
it('rejects invalid input with a 400 before checking permissions', async () => {
const promise = runOperation(makeOp(), ctx, { thingId: '' })
await expect(promise).rejects.toBeInstanceOf(HTTPException)
await expect(runOperation(makeOp(), ctx, { thingId: '' })).rejects.toMatchObject({
status: 400,
message: expect.stringContaining('Invalid input for touch_thing'),
})
expect(calls).toEqual([])
})
it('treats a missing input as an empty object', async () => {
await expect(runOperation(makeOp(), ctx, undefined)).rejects.toMatchObject({ status: 400 })
})
it('stops before any side effect when a later permission check fails', async () => {
vi.mocked(authzService.hasPermission).mockImplementation(async (req) => {
calls.push(`authz:${req.id}`)
if (req.id === 't2') throw new HTTPException(403, { message: 'Forbidden' })
})
await expect(runOperation(makeOp(), ctx, { thingId: 't1', otherId: 't2' })).rejects.toThrow(
'Forbidden',
)
expect(calls).toEqual(['authz:t1', 'authz:t2'])
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('fails with a 500 and writes no audit entry when the output does not match the schema', async () => {
const op = makeOp({
// Simulates an implementation bug the type checker cannot see
execute: async () => ({ touched: 42 }) as unknown as { touched: string },
})
await expect(runOperation(op, ctx, { thingId: 't1' })).rejects.toMatchObject({ status: 500 })
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('strips fields that are not part of the output schema', async () => {
const op = makeOp({
execute: async () => ({ touched: 't1', secret: 'x' }) as { touched: string },
})
await expect(runOperation(op, ctx, { thingId: 't1' })).resolves.toEqual({ touched: 't1' })
})
it('records audit entries with the caller, agent, via, and the resource team context', async () => {
await runOperation(makeOp(), { ...ctx, teamId: 'session-team' }, { thingId: 't1' })
expect(assetService.getAssetContext).toHaveBeenCalledWith('t1')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_update,
teamId: 'team-ctx',
projectId: 'project-ctx',
itemId: 't1',
userId: 'user-1',
agentId: 'agent-1',
via: 'agent',
})
})
it('uses explicit team context from audit entries when provided', async () => {
const op = makeOp({
audit: () => [
{ action: AuditAction.file_delete, itemId: 't1', teamId: 'team-x', projectId: 'p-x' },
],
})
await runOperation(op, { userId: 'user-1', via: 'api' }, { thingId: 't1' })
expect(assetService.getAssetContext).not.toHaveBeenCalled()
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_delete,
teamId: 'team-x',
projectId: 'p-x',
itemId: 't1',
userId: 'user-1',
agentId: undefined,
via: 'api',
})
})
it('still succeeds when the audit context cannot be resolved', async () => {
vi.mocked(assetService.getAssetContext).mockRejectedValue(new Error('Asset not found'))
await expect(runOperation(makeOp(), ctx, { thingId: 't1' })).resolves.toEqual({
touched: 't1',
})
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('propagates errors thrown by execute without auditing', async () => {
const op = makeOp({
execute: async () => {
throw new HTTPException(409, { message: 'Conflict' })
},
})
await expect(runOperation(op, ctx, { thingId: 't1' })).rejects.toMatchObject({ status: 409 })
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
})
+100
View File
@@ -0,0 +1,100 @@
import { z } from 'zod'
import { HTTPException } from 'hono/http-exception'
import type { AnyOperationDefinition } from '@shumai/operations'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import type { OperationContext } from './context'
import type { AuditEntry, Operation, OperationInput, OperationOutput } from './implement'
/**
* Run an Operation for a caller. Every surface (agent tools, MCP, CLI, REST routes) goes
* through this pipeline, in this order:
*
* 1. validate the input against the definition (HTTP 400 on failure)
* 2. check every declared permission, before any side effect
* 3. prepare (optional read-only step)
* 4. execute
* 5. validate the output against the definition (HTTP 500 on failure: a bug)
* 6. write audit entries
*
* Errors from authorization and services propagate unchanged (usually `HTTPException`).
*/
export async function runOperation<TDef extends AnyOperationDefinition>(
op: Operation<TDef>,
ctx: OperationContext,
rawInput: unknown,
): Promise<OperationOutput<TDef>> {
const { definition, implementation } = op
const parsedInput = definition.input.safeParse(rawInput ?? {})
if (!parsedInput.success) {
throw new HTTPException(400, {
message: `Invalid input for ${definition.name}: ${z.prettifyError(parsedInput.error)}`,
})
}
// safeParse on the generic schema type loses the concrete shape; the schema guarantees it.
const input = parsedInput.data as OperationInput<TDef>
const checks = await implementation.authz(input, ctx)
for (const check of checks) {
await authzService.hasPermission({ user: { id: ctx.userId }, ...check })
}
const prepared = implementation.prepare ? await implementation.prepare(input, ctx) : undefined
const result = await implementation.execute(input, ctx, prepared)
const parsedOutput = definition.output.safeParse(result)
if (!parsedOutput.success) {
logger.error(
{ operation: definition.name, issues: parsedOutput.error.issues },
'Operation returned output that does not match its schema',
)
throw new HTTPException(500, { message: `Operation ${definition.name} failed` })
}
const output = parsedOutput.data as OperationOutput<TDef>
if (implementation.audit) {
const entries = await implementation.audit(input, output, ctx, prepared)
for (const entry of entries) {
await writeAuditEntry(definition.name, entry, ctx)
}
}
return output
}
async function writeAuditEntry(
operation: string,
entry: AuditEntry,
ctx: OperationContext,
): Promise<void> {
let teamId: string
let projectId: string | undefined
if ('contextAssetId' in entry) {
try {
;({ teamId, projectId } = await assetService.getAssetContext(entry.contextAssetId))
} catch (err) {
// The Operation already succeeded; a missing audit entry must not turn it into a failure.
logger.warn(
{ err, operation, itemId: entry.itemId, contextAssetId: entry.contextAssetId },
'Skipping audit entry: could not resolve team context',
)
return
}
} else {
teamId = entry.teamId
projectId = entry.projectId
}
await auditLogService.logAction({
action: entry.action,
teamId,
projectId,
itemId: entry.itemId,
userId: ctx.userId,
agentId: ctx.agentId,
via: ctx.via,
})
}