feat(api): resolve endpoint resources and filter lists by access

This commit is contained in:
imccyu committed 2026-10-13 23:01:38 +08:00
1 parent d7bd68ee7a
commit 2640d3df82
21 files changed
+527 -21

No files matched your search

@@ -6,9 +6,10 @@ import { Context } from '@deepseek-ai/cordis'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import Storage from '@deepseek-ai/dsh-storage'
import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { RemoteError, type PeerId, type Principal, type RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol'
import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
import RemoteAccessService, { type RemoteAccessCondition, type RemoteAccessRole } from '@deepseek-ai/dsh-api-remote-access'
import WorkspaceController from '../src/index.ts'
import { DEFAULT_WORKSPACE_DIRECTORY } from '../src/default-workspace.ts'
import { WorkspaceFeed } from '../src/feed.ts'
@@ -67,11 +68,39 @@ async function harness(options: { systemDocuments?: boolean } = {}) {
ctx.provide('typert', {
lookups: { configure: () => dispose },
contexts: { configureHost: () => dispose },
resources: { register: vi.fn(() => dispose) },
} as never)
new RemoteAccessService(ctx)
const controller = new WorkspaceController(ctx, options.systemDocuments === true ? {} : { documentsDirectory: root })
return { controller, ctx, root, storageDomain }
}
declare module '@deepseek-ai/dsh-typert-protocol' {
interface PrincipalMap {
/** Test-only non-owner caller shared by the access specs. */
'test-guest': { readonly kind: 'test-guest'; readonly guest: string }
}
}
/** Opens the Workspace follow stream; each Workspace and Session in it still needs its own role. */
const FOLLOWER: RemoteAccessRole<'global'> = { name: 'test:workspace-follower', resource: 'global', actions: ['workspace/follow'] }
/** Shows one Workspace in the follow stream. */
const WORKSPACE_VIEWER: RemoteAccessRole<'workspace'> = { name: 'test:workspace-viewer', resource: 'workspace', actions: ['workspace/follow'] }
/** Shows one Session id in the follow stream. */
const SESSION_VIEWER: RemoteAccessRole<'session'> = { name: 'test:session-viewer', resource: 'session', actions: ['workspace/follow'] }
/** The Context a Gateway dispatch of `workspace/follow` binds for `principal`. */
function followerContext(ctx: Context, principal: Principal): Context {
const invocation: RemoteInvocation = {
request: { namespace: 'workspace', method: 'follow', args: {} },
service: 'workspaceController',
peer: { id: 'workspace-access-peer' as PeerId, ctx, principal, signal: new AbortController().signal, dispose: async () => {} },
signal: new AbortController().signal,
uplink: <In>(): AsyncIterable<In> => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }),
}
return ctx.extend({ invocation })
}
function stageDir(root: string, name: string): string {
const path = join(root, name)
mkdirSync(path, { recursive: true })
@@ -416,6 +445,110 @@ describe('WorkspaceController follow', () => {
await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined })
})
it('follows only the Workspaces and Sessions a non-owner may follow', async () => {
const { controller, ctx, root } = await harness()
// oxlint-disable-next-line typescript/unbound-method -- the assertion inspects the spy and never calls it.
expect(ctx.typert.resources.register).toHaveBeenCalledWith('workspace', { field: 'workspaceId' })
const shown = await controller.create({ path: stageDir(root, 'shown') })
const hiddenWorkspace = await controller.create({ path: stageDir(root, 'hidden') })
const shownId = shown.workspace.workspaceId
const hiddenId = hiddenWorkspace.workspace.workspaceId
const shared = ctx.sessions.create(SessionId('shared'), { meta: { cwd: shown.workspace.path } })
const secret = ctx.sessions.create(SessionId('secret'), { meta: { cwd: shown.workspace.path } })
const workspace = ctx.workspaceRegistry.get(shownId)
if (workspace === undefined) throw new Error('fixture Workspace disappeared')
await workspace.attachSession(shared.id)
await workspace.attachSession(secret.id)
await controller.pinSession({ sessionId: shared.id })
await controller.pinSession({ sessionId: secret.id })
ctx.remoteAccess.registerPolicy('test-guest', {
bindings: () => [
{ role: FOLLOWER, resource: { kind: 'global' } },
{ role: WORKSPACE_VIEWER, resource: { kind: 'workspace', id: shownId } },
{ role: SESSION_VIEWER, resource: { kind: 'session', id: shared.id } },
],
})
const guest: Principal = { kind: 'test-guest', guest: 'workspace-controller' }
const abort = new AbortController()
const iterator = followerContext(ctx, guest).workspaceController.follow(abort.signal)[Symbol.asyncIterator]()
await expect(nextFrame(iterator)).resolves.toEqual({
type: 'baseline',
value: {
items: [expect.objectContaining({ workspaceId: shownId, sessionIds: [shared.id] })],
archivedSessionIds: [],
pinnedSessionIds: [shared.id],
},
})
await controller.rename({ workspaceId: hiddenId, title: 'still hidden' })
await controller.rename({ workspaceId: shownId, title: 'renamed' })
await expect(nextFrame(iterator)).resolves.toMatchObject({
type: 'upsert', workspace: { workspaceId: shownId, title: 'renamed', sessionIds: [shared.id] },
})
await controller.unpinSession({ sessionId: secret.id })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'pinned', pinnedSessionIds: [shared.id] })
await controller.unpinSession({ sessionId: shared.id })
await controller.archiveSession({ sessionId: secret.id })
await controller.archiveSession({ sessionId: shared.id })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'pinned', pinnedSessionIds: [] })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'archived', archivedSessionIds: [] })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'archived', archivedSessionIds: [shared.id] })
await controller.delete({ workspaceId: hiddenId })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [shownId] })
await controller.delete({ workspaceId: shownId })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [] })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'remove', workspaceId: shownId })
abort.abort()
await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined })
})
it('sends a non-owner a replace increment when a delivered Workspace loses visibility, so it can reappear', async () => {
const { controller, ctx, root } = await harness()
const first = (await controller.create({ path: stageDir(root, 'first') })).workspace.workspaceId
const second = (await controller.create({ path: stageDir(root, 'second') })).workspace.workspaceId
// One Remote call reads its bindings once, so visibility changes during the stream come from the condition.
const allowedWorkspaces = new Set<string>([first, second])
const stillShared: RemoteAccessCondition<'workspace'> = ({ resource }) =>
allowedWorkspaces.has(resource.id) ? { kind: 'allow' } : { kind: 'deny', reason: 'test:unshared' }
ctx.remoteAccess.registerPolicy('test-guest', {
bindings: () => [
{ role: FOLLOWER, resource: { kind: 'global' } },
...[first, second].map(id => ({ role: WORKSPACE_VIEWER, resource: { kind: 'workspace', id } as const, condition: stillShared })),
],
})
const abort = new AbortController()
const iterator = followerContext(ctx, { kind: 'test-guest', guest: 'withdrawn' }).workspaceController.follow(abort.signal)[Symbol.asyncIterator]()
const ids = (frame: WorkspaceFollowFrame): string[] =>
frame.type === 'baseline' || frame.type === 'replace' ? frame.value.items.map(item => item.workspaceId).sort() : []
const opening = await nextFrame(iterator)
expect(opening.type).toBe('baseline')
expect(ids(opening)).toEqual([first, second].sort())
// Revoked: the next change replaces the state instead of sending a `remove` the Client would never undo.
allowedWorkspaces.delete(first)
await controller.rename({ workspaceId: first, title: 'revoked' })
const withoutFirst = await nextFrame(iterator)
expect(withoutFirst.type).toBe('replace')
expect(ids(withoutFirst)).toEqual([second])
allowedWorkspaces.delete(second)
const third = (await controller.create({ path: stageDir(root, 'third') })).workspace.workspaceId
const empty = await nextFrame(iterator)
expect(empty.type).toBe('replace')
expect(ids(empty)).toEqual([])
// A deletion reaches only a Client that received the Workspace.
await controller.delete({ workspaceId: third })
await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [] })
// Restored: the Workspace reappears through an ordinary upsert.
allowedWorkspaces.add(first)
await controller.rename({ workspaceId: first, title: 'restored' })
await expect(nextFrame(iterator)).resolves.toMatchObject({ type: 'upsert', workspace: { workspaceId: first, title: 'restored' } })
abort.abort()
await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined })
})
it('ignores unrelated domain writes and closes active followers on disposal', async () => {
const { controller, ctx, root } = await harness()
const abort = new AbortController()