Files
opencode-manager/backend/test/services/opencode/config-recovery.test.ts
T
Chris Scott 90a3c29c12 feat(sandbox): add KVM-backed agent sandboxing via microsandbox (#338)
* feat(sandbox): add KVM-backed agent sandboxing via microsandbox

* feat(sandbox): route host-shell surfaces into microVM via shell wrapper

* feat(sandbox): route host-shell surfaces into microVM via shell wrapper

* fix(sandbox): harden enforcement validation and backup handling

* fix(sandbox): bound lifecycle queue and harden install/backup paths

Bound the OpenCode supervisor lifecycle queue to one running plus one
pending operation so repeated restarts cannot stack unbounded HTTP
requests, while exempting stop() so shutdown is never dropped.

Reject enforcement backups that carry no recoverable removed sections,
matching the existing fail-closed handling of unparseable backups.

Install OpenCode through a private mktemp staging directory instead of
the predictable /tmp/opencode path.

Use named path/os imports in the files added by this branch.

* refactor(sandbox): remove OpenCode version allowlist gating under enforcement

* fix(settings): use resolved opencode binary and verify installed version

* refactor(sandbox): scope enforcement to agent bash tool only

* fix(sandbox): plan bash against factory directory and attest runtime tmpfs; align permission reply API

* fix(sandbox): pin neutral entrypoint and persist opencode upgrades across rebuilds

* fix(sandbox): align canonical spec with msb 0.6.8 runtime defaults

* feat(sandbox): show unwrapped sandboxed bash commands in message UI

* refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands

* feat(sandbox): route notifications through a host-side manager tool

* feat(sandbox): route all assistant capabilities through the ocm tool

Add an allow-listed request action to the generated ocm plugin so agents
reach settings, assistant reload, repos, git-info, workspaces, and
schedules through the tool instead of curling the internal API with a
bearer token, which is impossible under sandboxing.

Rewrite the curl-based skills to use the ocm request action and drop the
apiBaseUrl plumbing. Remove the now-unread .opencode/internal-token file
and the sandbox tmpfs mask that hid it; attestation now rejects any
tmpfs other than the runtime /tmp mount.

* fix(sidebar): wire new-session and new-schedule actions to every page

AssistantRedirect never registered a listener for the sidebar's
new-session event, so the desktop sidebar CTA on /assistant was a
no-op; the Schedules pages had the same gap for new-schedule.

Make useSidebarAction the single source of truth for action keys and
event dispatch, and warn when an action is dispatched with no mounted
handler so an unhandled CTA fails loudly instead of silently. Wire the
missing listeners to the existing per-page handlers.

* feat(sandbox): forward git credentials into the microVM and add sandbox guest image

* feat(sandbox): add git credential forwarding toggle to settings
2026-08-25 23:38:52 -04:00

290 lines
9.1 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-unused-vars */
import { describe, it, expect, vi } from 'vitest'
vi.mock('@opencode-manager/shared/config/env', () => ({
getWorkspacePath: vi.fn(() => '/test/workspace'),
getOpenCodeConfigFilePath: vi.fn(() => '/test/workspace/.config/opencode.json'),
getReposPath: vi.fn(() => '/test/workspace/repos'),
getAgentsMdPath: vi.fn(() => '/test/workspace/AGENTS.md'),
getDatabasePath: vi.fn(() => ':memory:'),
getConfigPath: vi.fn(() => '/test/workspace/config'),
ENV: {
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
DATABASE: { PATH: ':memory:' },
FILE_LIMITS: {
MAX_SIZE_BYTES: 1024 * 1024,
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
},
},
FILE_LIMITS: {
MAX_SIZE_BYTES: 1024 * 1024,
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
},
}))
vi.mock('../../../src/utils/logger', () => ({
logger: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}))
import { patchConfigWithRecovery } from '../../../src/services/opencode/config-recovery'
import type { OpenCodeClient, ForwardRequest } from '../../../src/services/opencode/client'
function createStubClient(
responses: Array<{ status: number; text: string }>,
capturedRequests?: ForwardRequest[],
): OpenCodeClient {
let callIndex = 0
return {
async forward(req: ForwardRequest) {
capturedRequests?.push(req)
const response = responses[callIndex++] ?? responses[responses.length - 1]!
return new Response(response.text, {
status: response.status,
headers: { 'Content-Type': 'application/json' },
})
},
async forwardRaw(_request: Request) {
throw new Error('not used')
},
async getJson<T>(_path: string) {
throw new Error('not used')
},
async postJson<T>(_path: string, _body: unknown) {
throw new Error('not used')
},
async setProviderAuth(_providerId: string, _apiKey: string) {
throw new Error('not used')
},
async deleteProviderAuth(_providerId: string) {
throw new Error('not used')
},
}
}
describe('patchConfigWithRecovery', () => {
it('should return success on 200 response with single forward call', async () => {
const config = { agent: { name: 'test' } }
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 200, text: '{}' },
], captured)
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(true)
expect(result.appliedConfig).toBe(config)
expect(result.error).toBeUndefined()
expect(captured).toHaveLength(1)
})
it('should recover by removing command.review on 400 with structured errors', async () => {
const errorResponse = {
success: false,
data: { command: { review: 'some value' } },
errors: [
{ path: ['command', 'review'], message: 'Invalid command review field' },
],
}
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 400, text: JSON.stringify(errorResponse) },
{ status: 200, text: '{}' },
], captured)
const config = { command: { review: 'test', other: 'value' }, agent: { name: 'test' } }
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(true)
expect(result.removedFields).toContain('command.review')
expect(result.details).toHaveLength(1)
expect(captured).toHaveLength(2)
const retryBody = JSON.parse(captured[1]!.body!) as { command?: { review?: unknown; other?: unknown }; agent?: unknown }
expect(retryBody.command?.review).toBeUndefined()
expect(retryBody.command?.other).toBe('value')
expect(retryBody.agent).toEqual({ name: 'test' })
expect(result.appliedConfig).toBeDefined()
expect((result.appliedConfig as { command?: { review?: unknown } }).command?.review).toBeUndefined()
})
it('should recover from ConfigInvalidError data.issues shape', async () => {
const errorResponse = {
name: 'ConfigInvalidError',
data: {
issues: [
{ path: ['command', 'review'], message: 'Invalid review' },
],
},
}
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 400, text: JSON.stringify(errorResponse) },
{ status: 200, text: '{}' },
], captured)
const config = { command: { review: 'test' } }
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(true)
expect(result.removedFields).toContain('command.review')
expect(captured).toHaveLength(2)
const retryBody = JSON.parse(captured[1]!.body!) as { command?: { review?: unknown } }
expect(retryBody.command?.review).toBeUndefined()
expect((result.appliedConfig as { command?: { review?: unknown } }).command?.review).toBeUndefined()
})
it('should NOT retry if path depth > 3', async () => {
const errorResponse = {
success: false,
data: {},
errors: [
{ path: ['a', 'b', 'c', 'd'], message: 'Too deep' },
],
}
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 400, text: JSON.stringify(errorResponse) },
], captured)
const config = { a: { b: { c: { d: 'value' } } } }
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(false)
expect(result.removedFields).toBeUndefined()
expect(captured).toHaveLength(1)
expect(result.details).toHaveLength(1)
expect(result.details?.[0]?.message).toBe('Too deep')
})
it('should NOT retry if path is root', async () => {
const errorResponse = {
success: false,
data: {},
errors: [
{ path: ['root'], message: 'Invalid configuration' },
],
}
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 400, text: JSON.stringify(errorResponse) },
], captured)
const config = { invalid: 'config' }
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(false)
expect(result.removedFields).toBeUndefined()
expect(captured).toHaveLength(1)
expect(result.details).toHaveLength(1)
expect(result.details?.[0]?.path).toBe('root')
})
it('should return retry errors when retry also fails', async () => {
const initialError = {
success: false,
data: {},
errors: [
{ path: ['command', 'review'], message: 'Initial error' },
],
}
const retryError = {
success: false,
data: {},
errors: [
{ path: ['agent'], message: 'Retry error - agent invalid' },
],
}
let callCount = 0
const client: OpenCodeClient = {
async forward(_req: ForwardRequest) {
callCount++
if (callCount === 1) {
return new Response(JSON.stringify(initialError), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
}
return new Response(JSON.stringify(retryError), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
},
async forwardRaw(_request: Request) {
throw new Error('not used')
},
async getJson<T>(_path: string) {
throw new Error('not used')
},
async postJson<T>(_path: string, _body: unknown) {
throw new Error('not used')
},
async setProviderAuth(providerId: string, apiKey: string) {
throw new Error('not used')
},
async deleteProviderAuth(providerId: string) {
throw new Error('not used')
},
}
const config = { command: { review: 'test' } }
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(false)
expect(result.removedFields).toContain('command.review')
expect(result.details).toHaveLength(1)
expect(result.details?.[0]?.message).toBe('Retry error - agent invalid')
expect(callCount).toBe(2)
})
it('should return error with Parse error on unparseable response', async () => {
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 400, text: 'not valid json at all' },
], captured)
const config = {}
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(false)
expect(result.error).toContain('Parse error')
expect(captured).toHaveLength(1)
})
it('should return error on 502 from client.forward', async () => {
const error502Response = { error: 'Proxy request failed' }
const captured: ForwardRequest[] = []
const client = createStubClient([
{ status: 502, text: JSON.stringify(error502Response) },
], captured)
const config = {}
const result = await patchConfigWithRecovery(client, config)
expect(result.success).toBe(false)
expect(result.error).toBeDefined()
expect(captured).toHaveLength(1)
})
})