fix(agent): enforce access checks in read_thread and before file uploads (#493)

read_thread returned any comment thread by ID. It now requires Read on
the thread's asset for the acting user, and confines system agents
without a user to their own team.

create_file and create_version uploaded to storage before checking Edit
permission, leaving orphaned objects on denied calls. The permission
check now runs first.
This commit is contained in:
Yiling-J
2026-10-26 11:14:37 +08:00
committed by GitHub
parent 22486b893b
commit 47ee794ae4
9 changed files with 223 additions and 27 deletions
+3
View File
@@ -10,6 +10,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
* **agent**: Fix an issue where an agent could read a comment thread from a project or team the user doesn't have access to by referencing its ID
* **agent**: Fix an issue where an agent creating a file or a new version in a folder the user can't edit still uploaded the file to storage before the request was rejected
### Changed
* **api-token**: API tokens are now stored securely, so they can no longer be read back from the database. A new token is shown only once when you create it, so copy it right away; the token list now shows just the last few characters. Existing tokens keep working without any changes.
+1 -1
View File
@@ -352,7 +352,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
)
}
const readThread = createReadThreadTool()
const readThread = createReadThreadTool({ userId, teamId })
const rawTools = [
...mediaTools,
readSkill,
@@ -347,6 +347,42 @@ describe('createCreateFileTool', () => {
expect((tool.parameters as any).properties.metadata).toBeUndefined()
})
describe('when the user lacks Edit permission on the parent', () => {
const denied = new Error('User is not a member of the team')
beforeEach(() => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(denied)
})
it('does not upload a local file to storage', async () => {
const filePath = createTempFile('# Not allowed', 'create-file-denied.md')
const tool = createCreateFileTool('user-1')
await expect(
tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null }),
).rejects.toThrow(denied.message)
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
expect(s3Service.putObject).not.toHaveBeenCalled()
expect(assetService.createFile).not.toHaveBeenCalled()
})
it('does not write inline content to storage', async () => {
const tool = createCreateFileTool('user-1')
await expect(
tool.execute('call-1', {
parent: 'folder-1',
path: null,
data: { name: 'notes.md', content: 'hello' },
}),
).rejects.toThrow(denied.message)
expect(s3Service.putObject).not.toHaveBeenCalled()
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
expect(assetService.createFile).not.toHaveBeenCalled()
})
})
it('should pass agentId and record audit log when agentContext is provided', async () => {
const filePath = createTempFile('# Agent file', 'agent-file.md')
+8 -7
View File
@@ -83,6 +83,14 @@ export function createCreateFileTool(
const p = params as CreateFileToolParams
const source = assertExactlyOneSource(p)
// Authorize before touching storage so a denied call leaves no orphaned object behind.
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: p.parent,
})
let name: string
let size: number
let mimeType: string
@@ -113,13 +121,6 @@ export function createCreateFileTool(
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', s3Key, content, size, mimeType)
}
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: p.parent,
})
const asset = await assetService.createFile({
parentId: p.parent,
name,
@@ -62,6 +62,21 @@ describe('createCreateVersionTool', () => {
return filePath
}
it('should not upload to storage when the user lacks Edit permission on the parent', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
new Error('User is not a member of the team'),
)
const filePath = createTempFile('# Not allowed', 'create-version-denied.md')
const tool = createCreateVersionTool('user-1')
await expect(tool.execute('call-1', { parent: 'file-1', path: filePath })).rejects.toThrow(
'User is not a member of the team',
)
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
expect(assetService.createVersion).not.toHaveBeenCalled()
})
it('should upload a local file and create a version via assetService.createVersion', async () => {
const filePath = createTempFile('# Hello from disk', 'create-version-test.md')
+9 -7
View File
@@ -49,6 +49,15 @@ export function createCreateVersionTool(
// The harness validates tool args against `createVersionSchema` before calling
// execute, so `params` is guaranteed to match this shape.
const p = params as CreateVersionToolParams
// Authorize before touching storage so a denied call leaves no orphaned object behind.
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: p.parent,
})
const absolutePath = path.resolve(process.cwd(), p.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${p.path}`)
@@ -62,13 +71,6 @@ export function createCreateVersionTool(
const s3Key = `files/${ulid()}/${sanitizeFilename(name)}`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: p.parent,
})
const asset = await assetService.createVersion({
parentId: p.parent,
name,
@@ -0,0 +1,91 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { createReadThreadTool } from './read-thread'
/**
* Real-database authorization tests for `read_thread`.
*
* Reproduces a bug where the tool returned any comment thread by ID without
* checking that the invoking user (or, for system agents, the agent's team)
* has access to the asset the thread belongs to.
*/
describe('read_thread authorization', () => {
setupTestDbHooks()
async function seedTeamWithThread(label: string) {
const team = await prisma.team.create({ data: { name: `Team ${label}` } })
const project = await prisma.project.create({
data: { name: `Project ${label}`, teamId: team.id },
})
const asset = await prisma.asset.create({
data: { name: `${label}.png`, type: 'file', status: 'uploaded', projectId: project.id },
})
const author = await prisma.user.create({
data: { name: `Author ${label}`, email: `author-${label}@test.com`, password: 'pw' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: author.id, role: 'owner' },
})
const thread = await prisma.assetComment.create({
data: { assetId: asset.id, creatorId: author.id, message: `secret message ${label}` },
})
await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: author.id,
replyToId: thread.id,
message: `secret reply ${label}`,
},
})
return { team, project, asset, author, thread }
}
it('lets a team member read a thread in their team', async () => {
const a = await seedTeamWithThread('a')
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
const result = await tool.execute('call-1', { threadId: a.thread.id })
const text = (result.content[0] as { text: string }).text
expect(text).toContain('secret message a')
expect(text).toContain('secret reply a')
})
it('rejects a user reading a thread from another team', async () => {
const a = await seedTeamWithThread('a')
const b = await seedTeamWithThread('b')
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow(
'User is not a member of the team',
)
})
it('rejects a project-scoped member reading a thread in a project they cannot access', async () => {
const b = await seedTeamWithThread('b')
const outsider = await prisma.user.create({
data: { name: 'Project scoped', email: 'scoped@test.com', password: 'pw' },
})
await prisma.teamMember.create({
data: { teamId: b.team.id, userId: outsider.id, role: 'editor', scope: 'project' },
})
const tool = createReadThreadTool({ userId: outsider.id, teamId: b.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow()
})
it('confines a system agent (no user) to threads in its own team', async () => {
const a = await seedTeamWithThread('a')
const b = await seedTeamWithThread('b')
const tool = createReadThreadTool({ teamId: a.team.id })
const own = await tool.execute('call-1', { threadId: a.thread.id })
expect((own.content[0] as { text: string }).text).toContain('secret message a')
await expect(tool.execute('call-2', { threadId: b.thread.id })).rejects.toThrow('Access denied')
})
})
+23 -7
View File
@@ -1,6 +1,15 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createReadThreadTool } from './read-thread'
import { prisma } from '@shumai/db'
import { authzService } from '@shumai/core/src/authz/authz'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
@@ -27,7 +36,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null)
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-1', { threadId: 'non-existent' })
const textContent = (result.content[0] as { text: string }).text
@@ -39,7 +48,7 @@ describe('createReadThreadTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock return
vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'asset-1' } as any)
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-asset', { threadId: 'asset-1' })
const textContent = (result.content[0] as { text: string }).text
@@ -49,6 +58,7 @@ describe('createReadThreadTool', () => {
it('should return thread root message and notice when there are no replies', async () => {
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
id: 'root-1',
assetId: 'asset-1',
message: 'Initial top-level question',
creator: { name: 'Alice' },
second: 12.5,
@@ -57,10 +67,16 @@ describe('createReadThreadTool', () => {
} as any)
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([])
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-2', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'read',
type: 'asset',
id: 'asset-1',
})
expect(textContent).toContain(
'Thread Root [Alice] (id: root-1, time: 12.5s, has_markup: true): Initial top-level question',
)
@@ -90,7 +106,7 @@ describe('createReadThreadTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
@@ -122,7 +138,7 @@ describe('createReadThreadTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-agent', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
@@ -153,7 +169,7 @@ describe('createReadThreadTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3d', { threadId: 'root-3d' })
const textContent = (result.content[0] as { text: string }).text
@@ -166,7 +182,7 @@ describe('createReadThreadTool', () => {
})
it('should describe threadId parameter as referencing <thread id="..." /> in <context>', () => {
const tool = createReadThreadTool()
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const description = (tool.parameters as any).properties.threadId.description
expect(description).toContain('<thread id="..." />')
+37 -5
View File
@@ -1,6 +1,8 @@
import { prisma } from '@shumai/db'
import { prisma, type User } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { getProxyType } from '@shumai/core/src/utils/mime'
@@ -32,10 +34,38 @@ function formatCommentMeta(
return `(${parts.join(', ')})`
}
export const createReadThreadTool = (): AgentTool<
typeof readThreadSchema,
{ threadId: string }
> => ({
export interface ReadThreadToolContext {
/** The user the agent acts for. When set, the user must be able to read the thread's asset. */
userId?: string
/** The agent's team. System agents without a user may only read threads in this team. */
teamId: string
}
/**
* Ensure the caller may read a thread on `assetId` before any thread content is
* returned: the acting user needs Read on the asset; a system agent (no user)
* is confined to its own team.
*/
async function assertCanReadThread(assetId: string, ctx: ReadThreadToolContext): Promise<void> {
if (ctx.userId) {
await authzService.hasPermission({
user: { id: ctx.userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
return
}
const assetCtx = await assetService.getAssetContext(assetId).catch(() => null)
if (!assetCtx || assetCtx.teamId !== ctx.teamId) {
throw new Error('Access denied: this comment thread does not belong to your team.')
}
}
export const createReadThreadTool = (
ctx: ReadThreadToolContext,
): AgentTool<typeof readThreadSchema, { threadId: string }> => ({
name: 'read_thread',
label: 'Read Comment Thread',
description: 'Reads all comments and replies inside a specific comment thread.',
@@ -64,6 +94,8 @@ export const createReadThreadTool = (): AgentTool<
}
}
await assertCanReadThread(rootComment.assetId, ctx)
const replies = await prisma.assetComment.findMany({
where: {
replyToId: rootComment.id,