mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(sandbox): add KVM-backed agent sandboxing via microsandbox
This commit is contained in:
1 parent
1d477bdee4
commit
aa3fb48a62
80 files changed
+17304
-204
No files matched your search
@@ -9,6 +9,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
isRestartPending: vi.fn(() => false),
|
||||
isSandboxEnforced: vi.fn(() => false),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -22,22 +23,36 @@ vi.mock('bun:sqlite', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/sandbox/capability', () => ({
|
||||
detectSandboxCapability: vi.fn(),
|
||||
}))
|
||||
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { createHealthRoutes } from '../../src/routes/health'
|
||||
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
|
||||
const mockIsSandboxEnforced = opencodeServerManager.isSandboxEnforced as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('Health Routes', () => {
|
||||
let healthApp: ReturnType<typeof createHealthRoutes>
|
||||
let mockDb: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available or not writable' })
|
||||
mockIsSandboxEnforced.mockReturnValue(false)
|
||||
|
||||
const mockPrepareGet = vi.fn()
|
||||
const mockQueryGet = vi.fn()
|
||||
mockDb = {
|
||||
prepare: vi.fn(() => ({
|
||||
get: mockPrepareGet,
|
||||
})),
|
||||
query: vi.fn(() => ({
|
||||
get: mockQueryGet,
|
||||
})),
|
||||
} as any
|
||||
|
||||
healthApp = createHealthRoutes(mockDb)
|
||||
@@ -101,6 +116,156 @@ describe('Health Routes', () => {
|
||||
expect(json.database).toBe('disconnected')
|
||||
})
|
||||
|
||||
it('should include sandbox availability and enforcement in the payload', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({ available: true, enabled: true, enforced: true, msbVersion: 'msb 0.3.1' })
|
||||
})
|
||||
|
||||
it('should keep the overall status unchanged when the sandbox runtime is unavailable', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: false,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports enabled-but-not-enforced when the preference is enabled but the child has not restarted', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: true,
|
||||
enforced: false,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an enforced running child even when the sandbox runtime is unavailable', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: true,
|
||||
enforced: true,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an enforced running child while a disable-pending restart still runs it', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: true,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 200 with a safe sandbox status when the sandbox status lookup throws', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDb.query.mockImplementationOnce(() => {
|
||||
throw new Error('user_preferences table is unavailable')
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: false,
|
||||
reason: 'user_preferences table is unavailable',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the running child enforcement in the fallback payload when the sandbox status lookup throws', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query.mockImplementationOnce(() => {
|
||||
throw new Error('user_preferences table is unavailable')
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: true,
|
||||
reason: 'user_preferences table is unavailable',
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 503 when health check throws an error', async () => {
|
||||
mockDb.prepare().get.mockImplementationOnce(() => {
|
||||
throw new Error('Database error')
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, vi } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { mkdirSync, rmSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { createOpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { buildSandboxExecCommandString, resolveSandboxExecUser, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../src/services/sandbox/command'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import { getReposPath, getScheduleWorktreesPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
|
||||
|
||||
function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: string } {
|
||||
const memoryMatch = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(ENV.SANDBOX.MEMORY)
|
||||
const memoryMib = memoryMatch
|
||||
? memoryMatch[2] === undefined || memoryMatch[2] === 'M' || memoryMatch[2] === 'm'
|
||||
? Math.floor(Number(memoryMatch[1]))
|
||||
: Math.floor(Number(memoryMatch[1]) * 1024)
|
||||
: 0
|
||||
const bindMount = (host: string) => ({
|
||||
type: 'Bind',
|
||||
host,
|
||||
guest: host,
|
||||
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
|
||||
stat_virtualization: 'strict',
|
||||
host_permissions: 'private',
|
||||
follow_root_symlinks: false,
|
||||
quota_mib: null,
|
||||
})
|
||||
const config = {
|
||||
name: WORKSPACE_SANDBOX_NAME,
|
||||
image: { Oci: { reference: ENV.SANDBOX.IMAGE, root_disk: { kind: 'managed', size_mib: 4096 } } },
|
||||
resources: { cpus: ENV.SANDBOX.CPUS, memory_mib: memoryMib, max_cpus: ENV.SANDBOX.CPUS, max_memory_mib: memoryMib },
|
||||
runtime: {
|
||||
workdir: getReposPath(),
|
||||
shell: null,
|
||||
scripts: {},
|
||||
entrypoint: null,
|
||||
cmd: ['sleep', 'infinity'],
|
||||
hostname: null,
|
||||
user: resolveSandboxExecUser(),
|
||||
log_level: null,
|
||||
metrics_sample_interval_ms: null,
|
||||
disable_metrics_sample: false,
|
||||
},
|
||||
env: [],
|
||||
labels: { 'ocm.managed': 'true', 'ocm.net': ENV.SANDBOX.NET },
|
||||
rlimits: [],
|
||||
mounts: [
|
||||
bindMount(getReposPath()),
|
||||
bindMount(getScheduleWorktreesPath()),
|
||||
{ type: 'Tmpfs', guest: sandboxSecretMaskPath(), size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } },
|
||||
],
|
||||
patches: [],
|
||||
network: {
|
||||
enabled: true,
|
||||
ports: [],
|
||||
policy: {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
},
|
||||
max_connections: null,
|
||||
trust_host_cas: false,
|
||||
},
|
||||
init: null,
|
||||
pull_policy: 'IfMissing',
|
||||
security_profile: 'default',
|
||||
lifecycle: { ephemeral: false, max_duration_secs: null, idle_timeout_secs: null },
|
||||
manifest_digest: 'sha256:0000000000000000000000000000000000000000000000000000000000000000',
|
||||
}
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: JSON.stringify({
|
||||
name: WORKSPACE_SANDBOX_NAME,
|
||||
status: 'Running',
|
||||
config,
|
||||
created_at: '2026-08-12T00:00:00Z',
|
||||
updated_at: '2026-08-12T00:00:00Z',
|
||||
active_config: config,
|
||||
pending_changes: [],
|
||||
}),
|
||||
stderr: '',
|
||||
}
|
||||
}
|
||||
|
||||
mock.module('../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(async (args: string[]) => {
|
||||
if (args.includes('inspect')) return trustedRunningInspect()
|
||||
return { exitCode: 0, stdout: '[]', stderr: '' }
|
||||
}),
|
||||
}))
|
||||
|
||||
mock.module('../../src/services/sandbox/capability', () => ({
|
||||
detectSandboxCapability: vi.fn(() => ({ available: true, msbVersion: 'msb 0.3.1' })),
|
||||
resetSandboxCapabilityCache: () => {},
|
||||
}))
|
||||
|
||||
const mockExecuteCommand = executeCommand as ReturnType<typeof vi.fn>
|
||||
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('internal sandbox routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let app: Hono
|
||||
let token: string
|
||||
let repoDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
mockExecuteCommand.mockClear()
|
||||
mockDetectSandboxCapability.mockReset()
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
const openCodeClient = createOpenCodeClient()
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, stubWorktreeManager)
|
||||
const notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
repoDir = path.join(getReposPath(), 'sandbox-route-test')
|
||||
mkdirSync(repoDir, { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
rmSync(repoDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function postCommand(body: unknown, auth = true) {
|
||||
return app.request('/api/internal/sandbox/command', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(auth ? { authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('POST /command returns 401 without bearer token', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' }, false)
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('POST /command returns host mode when the sandbox preference is off', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ mode: 'host' })
|
||||
expect(mockExecuteCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /command returns a wrapped sandbox command when enforcement is on', async () => {
|
||||
settingsService.updateSettings({ sandbox: { enabled: true } })
|
||||
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
mode: 'sandbox',
|
||||
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /command returns 400 for a malformed body', async () => {
|
||||
const res = await postCommand({ directory: '', command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(await res.json()).toEqual({ error: 'Invalid request' })
|
||||
})
|
||||
|
||||
it('POST /command blocks an enabled request when the capability is unavailable instead of running on the host', async () => {
|
||||
settingsService.updateSettings({ sandbox: { enabled: true } })
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
|
||||
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
|
||||
expect(mockExecuteCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /command never returns host mode for an enforced request even when the preference is off', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi', enforced: true })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
mode: 'sandbox',
|
||||
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /command blocks an enforced request for a directory outside the project roots', async () => {
|
||||
const res = await postCommand({ directory: '/etc', command: 'echo hi', enforced: true })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { mode: string; reason?: string }
|
||||
expect(body.mode).toBe('blocked')
|
||||
expect(String(body.reason)).toContain('outside the sandboxed project roots')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,405 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from '../../src/routes/opencode-auth-proxy'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
|
||||
const isSandboxEnforcedMock = vi.hoisted(() => vi.fn().mockReturnValue(false))
|
||||
const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
|
||||
OpenCodeServerManager: class {},
|
||||
getSandboxVerifiedOpenCodeVersions: () => [],
|
||||
isSandboxVerifiedOpenCodeVersion: () => false,
|
||||
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
|
||||
ConfigReloadError: class extends Error {},
|
||||
NonRecoverableStartupError: class extends Error {},
|
||||
}))
|
||||
|
||||
const forwardRawMock = vi.hoisted(() => vi.fn<OpenCodeClient['forwardRaw']>(async () => new Response('ok', { status: 200 })))
|
||||
|
||||
vi.mock('../../src/services/opencode/client', () => ({
|
||||
createOpenCodeClient: vi.fn(),
|
||||
}))
|
||||
|
||||
const passThroughAuth: MiddlewareHandler = async (c, next) => {
|
||||
await next()
|
||||
}
|
||||
|
||||
function buildApp() {
|
||||
const app = new Hono()
|
||||
app.route(
|
||||
'/api/opencode',
|
||||
createAuthenticatedOpenCodeProxyRoutes({ forwardRaw: forwardRawMock } as unknown as OpenCodeClient, passThroughAuth),
|
||||
)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('authenticated opencode proxy routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
isLifecycleInitializedMock.mockReturnValue(true)
|
||||
forwardRawMock.mockResolvedValue(new Response('ok', { status: 200 }))
|
||||
})
|
||||
|
||||
it('returns 503 and never forwards when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/message')
|
||||
expect(res.status).toBe(503)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 503 through the proxy gate on a below-threshold health failure and reopens once the supervisor recovers', async () => {
|
||||
const lifecycle = { initialized: true }
|
||||
isLifecycleInitializedMock.mockImplementation(() => lifecycle.initialized)
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
await supervisor.start()
|
||||
|
||||
const healthyRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(healthyRes.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
const status = await supervisor.checkNow('manual')
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const blockedRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(blockedRes.status).toBe(503)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
|
||||
const reopenedRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(reopenedRes.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('forwards ordinary endpoints when enforcement is off', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/message')
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 503 for MCP auth endpoints when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(503)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards MCP auth endpoints through the lifecycle-gated proxy when initialized', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
|
||||
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth')
|
||||
})
|
||||
|
||||
it('forwards MCP auth authenticate endpoints through the lifecycle-gated proxy when initialized', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth/authenticate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
|
||||
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth/authenticate')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/shell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/shell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks /api-prefixed PTY creation with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/api/pty', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell spellings with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/%73hell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators in proxied paths when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1%2Fshell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards safely encoded non-execution paths when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/%6dessage')
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sanitizes plugins from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.theme).toBe('dark')
|
||||
expect(forwarded.plugin).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sanitizes local MCP servers and formatter config from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] } },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.formatter).toBeUndefined()
|
||||
expect(forwarded.mcp).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a malformed PATCH /config body with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{not json',
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
it('forwards PATCH /config mutations raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.plugin).toEqual(['opencode-plugin-npm'])
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('only remote MCP servers')
|
||||
})
|
||||
|
||||
it('forwards a remote MCP server add when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards MCP server adds raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'local-server',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as { config: { type: string } }
|
||||
expect(forwarded.config.type).toBe('local')
|
||||
})
|
||||
|
||||
it('sanitizes LSP servers and experimental hooks from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'x'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.lsp).toBeUndefined()
|
||||
expect(forwarded.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
})
|
||||
|
||||
it('forwards a PATCH /config mutation without host-execution sections unchanged when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ theme: 'dark' })
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('well-known')
|
||||
})
|
||||
|
||||
it('forwards api and oauth auth writes when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/anthropic', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'api', key: 'sk-test' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ type: 'api', key: 'sk-test' })
|
||||
})
|
||||
|
||||
it('forwards auth writes raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.type).toBe('wellknown')
|
||||
})
|
||||
|
||||
it('strips custom provider npm selectors from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'x',
|
||||
provider: {
|
||||
evil: { npm: 'file:///repo/evil-provider.js' },
|
||||
builtin: { options: { apiKey: 'k' } },
|
||||
},
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.model).toBe('x')
|
||||
expect(forwarded.provider).toEqual({ builtin: { options: { apiKey: 'k' } } })
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { createOpenCodeProxyRoutes } from '../../src/routes/opencode-proxy'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
@@ -12,6 +13,19 @@ vi.mock('../../src/services/internal-token', () => ({
|
||||
getOrCreateInternalToken: vi.fn().mockReturnValue('test-internal-token'),
|
||||
}))
|
||||
|
||||
const isSandboxEnforcedMock = vi.hoisted(() => vi.fn().mockReturnValue(false))
|
||||
const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
|
||||
OpenCodeServerManager: class {},
|
||||
getSandboxVerifiedOpenCodeVersions: () => [],
|
||||
isSandboxVerifiedOpenCodeVersion: () => false,
|
||||
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
|
||||
ConfigReloadError: class extends Error {},
|
||||
NonRecoverableStartupError: class extends Error {},
|
||||
}))
|
||||
|
||||
const mockSettingsService = {
|
||||
getOpenCodeServerPassword: vi.fn().mockReturnValue('test-password'),
|
||||
} as unknown as SettingsService
|
||||
@@ -24,6 +38,8 @@ describe('opencode-proxy routes', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
isLifecycleInitializedMock.mockReturnValue(true)
|
||||
originalFetch = globalThis.fetch
|
||||
app = new Hono()
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(mockDb, mockSettingsService))
|
||||
@@ -40,6 +56,20 @@ describe('opencode-proxy routes', () => {
|
||||
expect(body.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('returns 503 and never forwards when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/message', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 401 with invalid bearer token', async () => {
|
||||
const res = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer wrong-token' },
|
||||
@@ -271,4 +301,503 @@ describe('opencode-proxy routes', () => {
|
||||
expect(res.headers.get('transfer-encoding')).toBeNull()
|
||||
expect(res.headers.get('content-type')).toBe('text/plain')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/shell', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('host process')
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/shell', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell spellings with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/%73hell', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('host process')
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators in proxied paths when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1%2Fshell', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards safely encoded non-execution paths when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/%6dessage', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks PTY creation with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/pty', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks /api-prefixed PTY creation with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/api/pty', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks custom slash command execution with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/command', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('only remote MCP servers')
|
||||
})
|
||||
|
||||
it('rejects a command-bearing MCP add without an explicit local type with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { command: ['npx', 'evil-server'] },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards a remote MCP server add when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards MCP server adds raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'local-server',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as { config: { type: string } }
|
||||
expect(forwarded.config.type).toBe('local')
|
||||
})
|
||||
|
||||
it('sanitizes LSP servers and experimental hooks from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'x'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.lsp).toBeUndefined()
|
||||
expect(forwarded.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
})
|
||||
|
||||
it('forwards ordinary agent endpoints when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/prompt_async', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sanitizes plugins from a PATCH /config mutation when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.theme).toBe('dark')
|
||||
expect(forwarded.plugin).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sanitizes local MCP servers and formatter config from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] } },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.formatter).toBeUndefined()
|
||||
expect(forwarded.mcp).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a malformed PATCH /config body with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{not json',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
it('forwards PATCH /config mutations raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.plugin).toEqual(['opencode-plugin-npm'])
|
||||
})
|
||||
|
||||
it('forwards non-config mutations raw when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/message', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ content: 'hello' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.content).toBe('hello')
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('well-known')
|
||||
})
|
||||
|
||||
it('forwards api and oauth auth writes when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/auth/anthropic', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'api', key: 'sk-test' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ type: 'api', key: 'sk-test' })
|
||||
})
|
||||
|
||||
it('forwards auth writes raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.type).toBe('wellknown')
|
||||
})
|
||||
|
||||
it('returns 503 through the proxy gate on a below-threshold health failure and reopens once the supervisor recovers', async () => {
|
||||
const lifecycle = { initialized: true }
|
||||
isLifecycleInitializedMock.mockImplementation(() => lifecycle.initialized)
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
await supervisor.start()
|
||||
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const healthyRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(healthyRes.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
const status = await supervisor.checkNow('manual')
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const blockedRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(blockedRes.status).toBe(503)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
|
||||
const reopenedRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(reopenedRes.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -33,6 +33,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
clearStartupError: vi.fn(),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
isSandboxEnforced: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -53,6 +54,7 @@ const mockScheduleService = {} as ScheduleService
|
||||
describe('Repo Routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(false)
|
||||
})
|
||||
|
||||
describe('POST /:id/access', () => {
|
||||
@@ -320,4 +322,62 @@ describe('Repo Routes', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/workspaces', () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
}
|
||||
|
||||
it('refuses and cleans up a workspace created outside the project roots while sandboxing is enforced', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(true)
|
||||
|
||||
const forward = vi.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({ id: 'wrk_outside', directory: '/workspace/.opencode/state/workspaces/wrk_outside', branch: null }),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('not available while sandboxing is enabled')
|
||||
expect(forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: '/experimental/workspace/wrk_outside',
|
||||
directory: '/tmp/test-repo',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('allows workspace creation when sandboxing is not enforced', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(false)
|
||||
|
||||
const forward = vi.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({ id: 'wrk_ok', directory: '/workspace/.opencode/state/workspaces/wrk_ok', branch: null }),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { id: string }
|
||||
expect(body.id).toBe('wrk_ok')
|
||||
expect(forward).not.toHaveBeenCalledWith(expect.objectContaining({ method: 'DELETE' }))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -5,8 +5,10 @@ import { createSettingsRoutes } from '../../src/routes/settings'
|
||||
import { encryptSecret } from '../../src/utils/crypto'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: class Database {},
|
||||
@@ -19,6 +21,8 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
getVersion: vi.fn(),
|
||||
fetchVersion: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
checkHealth: vi.fn(() => true),
|
||||
reinitializeBinDirectory: vi.fn(),
|
||||
},
|
||||
ConfigReloadError: class ConfigReloadError extends Error {
|
||||
@@ -181,8 +185,81 @@ describe('OpenCode Server Auth Routes', () => {
|
||||
const restored = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
|
||||
expect(restored?.value).toBe(previous.value)
|
||||
})
|
||||
|
||||
it('keeps the proxy lifecycle gate closed during the supervised restart and reopens only after a verified healthy restart', async () => {
|
||||
const lifecycle = { initialized: false }
|
||||
const { app: supervisedApp, manager } = createSupervisedApp(db, lifecycle)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
|
||||
const patchPromise = supervisedApp.request('/api/settings/opencode-server-auth', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'testpassword123' }),
|
||||
})
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
releaseRestart()
|
||||
const response = await patchPromise
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
expect(await response.json()).toEqual({ isSet: true, source: 'db' })
|
||||
expect(db.prepare('SELECT 1 FROM app_secrets WHERE key = ?').get('opencode_server_password')).toBeDefined()
|
||||
})
|
||||
|
||||
it('fails the auth update and restores the prior password when the supervised restart ends unhealthy, keeping the proxy gate closed', async () => {
|
||||
insertPassword('testpassword123')
|
||||
const previous = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string }
|
||||
const lifecycle = { initialized: false }
|
||||
const { app: supervisedApp, manager } = createSupervisedApp(db, lifecycle)
|
||||
manager.checkHealth.mockResolvedValue(false)
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const response = await supervisedApp.request('/api/settings/opencode-server-auth', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: null }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(manager.restart).toHaveBeenCalledTimes(2)
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const restored = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
|
||||
expect(restored?.value).toBe(previous.value)
|
||||
})
|
||||
})
|
||||
|
||||
function createSupervisedApp(db: Database, lifecycle: { initialized: boolean }) {
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
const routes = createSettingsRoutes(db, {} as GitAuthService, {} as OpenCodeClient, supervisor)
|
||||
return { app: new Hono().route('/api/settings', routes), manager }
|
||||
}
|
||||
|
||||
function insertPassword(password: string) {
|
||||
const encrypted = encryptSecret(password)
|
||||
const now = Date.now()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,18 @@ describe('entrypoint library wiring', () => {
|
||||
expect(warnIndex).toBeLessThan(chownIndex)
|
||||
})
|
||||
|
||||
it('grants node access to /dev/kvm before dropping privileges', () => {
|
||||
const entrypoint = read(entrypointPath)
|
||||
expect(entrypoint).toMatch(/^grant_kvm_access\(\) \{/m)
|
||||
const alignIndex = entrypoint.indexOf('if ! align_container_user node; then')
|
||||
const grantCallIndex = entrypoint.indexOf('if ! grant_kvm_access; then')
|
||||
const runuserIndex = entrypoint.indexOf('exec runuser -u node')
|
||||
expect(grantCallIndex, 'entrypoint must call grant_kvm_access').toBeGreaterThan(-1)
|
||||
expect(grantCallIndex).toBeGreaterThan(alignIndex)
|
||||
expect(runuserIndex).toBeGreaterThan(grantCallIndex)
|
||||
expect(entrypoint.slice(grantCallIndex, grantCallIndex + 60)).toMatch(/exit 1/)
|
||||
})
|
||||
|
||||
it('does not re-chown /app when ids change', () => {
|
||||
const entrypoint = read(entrypointPath)
|
||||
|
||||
@@ -66,6 +78,55 @@ describe('entrypoint library wiring', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('microsandbox runtime install', () => {
|
||||
const dockerfile = read(dockerfilePath)
|
||||
|
||||
it('declares MICROSANDBOX_VERSION next to the other tool args', () => {
|
||||
expect(dockerfile).toMatch(/ARG MICROSANDBOX_VERSION=0\.6\.8/)
|
||||
})
|
||||
|
||||
it('resolves the release URL from MICROSANDBOX_VERSION, not only the log message', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).toMatch(/releases\/download\/\$\{MSB_VERSION\}/)
|
||||
expect(microsandboxRun).toMatch(/MSB_VERSION="v\$\{MICROSANDBOX_VERSION\}"/)
|
||||
})
|
||||
|
||||
it('pins a tested version and avoids unauthenticated GitHub API lookups', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).not.toMatch(/releases\/latest\/download/)
|
||||
expect(microsandboxRun).not.toContain('install.microsandbox.dev')
|
||||
expect(microsandboxRun).not.toMatch(/api\.github\.com/)
|
||||
})
|
||||
|
||||
it('passes the same MICROSANDBOX_VERSION from the docker-build workflow', () => {
|
||||
const workflow = read(join(repoRoot, '.github/workflows/docker-build.yml'))
|
||||
expect(workflow).toContain('MICROSANDBOX_VERSION=0.6.8')
|
||||
expect(workflow).toContain('MICROSANDBOX_VERSION=${{ steps.versions.outputs.microsandbox }}')
|
||||
})
|
||||
|
||||
it('downloads the arch-specific bundle and verifies its checksum', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).toMatch(/MSB_BUNDLE="microsandbox-linux-\$\{MSB_TARGET\}\.tar\.gz"/)
|
||||
expect(microsandboxRun).toMatch(/MSB_TARGET="x86_64"/)
|
||||
expect(microsandboxRun).toMatch(/MSB_TARGET="aarch64"/)
|
||||
expect(microsandboxRun).toMatch(/checksums\.sha256/)
|
||||
expect(microsandboxRun).toMatch(/sha256sum -c --quiet/)
|
||||
})
|
||||
|
||||
it('installs msb and libkrunfw under /opt/microsandbox with the runtime symlinks', () => {
|
||||
expect(dockerfile).toContain('/opt/microsandbox/bin/msb')
|
||||
expect(dockerfile).toContain('/usr/local/bin/msb')
|
||||
expect(dockerfile).toContain('/opt/microsandbox/lib/libkrunfw.so')
|
||||
expect(dockerfile).toMatch(/chmod -R a\+rX \/opt\/microsandbox/)
|
||||
expect(dockerfile).toMatch(/msb --version/)
|
||||
})
|
||||
|
||||
it('keeps the state directory writable by the node user', () => {
|
||||
expect(dockerfile).toMatch(/mkdir -p \/workspace \/app\/data \/home\/node\/\.cache \/home\/node\/\.opencode \/home\/node\/\.microsandbox/)
|
||||
expect(dockerfile).toMatch(/chown -R node:node \/workspace \/app\/data \/home\/node/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace ownership configuration', () => {
|
||||
it('exposes PUID and PGID environment defaults in docker-compose.yml', () => {
|
||||
const compose = read(composePath)
|
||||
@@ -124,6 +185,28 @@ describe('workspace ownership configuration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox compose overlay', () => {
|
||||
const overlayPath = join(repoRoot, 'docker-compose.sandbox.yml')
|
||||
const overlay = read(overlayPath)
|
||||
|
||||
it('defaults SANDBOX_EXEC_USER from PUID so the guest identity tracks the workspace owner', () => {
|
||||
expect(overlay).toContain('- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}')
|
||||
})
|
||||
|
||||
it('keeps the base compose free of KVM and privileged flags', () => {
|
||||
const compose = read(composePath)
|
||||
expect(compose).not.toContain('privileged')
|
||||
expect(compose).not.toContain('/dev/kvm')
|
||||
})
|
||||
|
||||
it('grants KVM and persists microsandbox state only in the overlay', () => {
|
||||
expect(overlay).toContain('privileged: true')
|
||||
expect(overlay).toContain('"/dev/kvm:/dev/kvm"')
|
||||
expect(overlay).toContain('microsandbox-data:/home/node/.microsandbox')
|
||||
expect(overlay).toMatch(/^volumes:\n(?:.*\n)*?\s+microsandbox-data:/m)
|
||||
})
|
||||
})
|
||||
|
||||
describe('named-volume migration recipe', () => {
|
||||
const runMigrationShell = (src: string, dst: string) => {
|
||||
const scriptDir = mkdtempSync(join(tmpdir(), 'migrate-script-'))
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { mkdirSync, writeFileSync, rmSync, chmodSync, existsSync, readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { repoRoot } from '../helpers/repo-root'
|
||||
|
||||
const entrypointPath = join(repoRoot, 'scripts/docker-entrypoint.sh')
|
||||
|
||||
let stubDir: string
|
||||
let logPath: string
|
||||
|
||||
const writeStub = (name: string, body: string) => {
|
||||
const file = join(stubDir, name)
|
||||
writeFileSync(file, `#!/bin/bash\n${body}\n`)
|
||||
chmodSync(file, 0o755)
|
||||
}
|
||||
|
||||
const extractGrantKvmAccess = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const match = entrypoint.match(/^grant_kvm_access\(\) \{\n[\s\S]*?\n\}/m)
|
||||
if (!match) throw new Error('grant_kvm_access() not found in docker-entrypoint.sh')
|
||||
return match[0]
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubDir = join(tmpdir(), `ocm-entrypoint-${Date.now()}-${Math.random().toString(36).slice(2)}`)
|
||||
mkdirSync(stubDir, { recursive: true })
|
||||
logPath = join(stubDir, 'calls.log')
|
||||
|
||||
writeStub('stat', `echo "${'${OCM_STUB_DEV_GID:-44}'}"`)
|
||||
writeStub('getent', `
|
||||
if [ "$1" = "group" ] && [ "$2" = "${'${OCM_STUB_DEV_GID:-44}'}" ]; then
|
||||
echo "${'${OCM_STUB_GROUP_HOLDER}'}:x:$2:"
|
||||
exit 0
|
||||
fi
|
||||
exit 2`)
|
||||
writeStub('groupadd', `echo "groupadd $*" >> "$OCM_STUB_LOG"`)
|
||||
writeStub('usermod', `echo "usermod $*" >> "$OCM_STUB_LOG"`)
|
||||
writeStub('runuser', `echo "runuser $*" >> "$OCM_STUB_LOG"
|
||||
exit ${'${OCM_STUB_RUNUSER_EXIT:-0}'}`)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(stubDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const runScript = (snippet: string, env: Record<string, string> = {}) => {
|
||||
const scriptPath = join(stubDir, 'test.sh')
|
||||
writeFileSync(scriptPath, `set -e\n${extractGrantKvmAccess()}\n${snippet}\n`)
|
||||
return spawnSync('bash', [scriptPath], {
|
||||
encoding: 'utf-8',
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${stubDir}:${process.env.PATH}`,
|
||||
OCM_STUB_LOG: logPath,
|
||||
...env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stubCalls = () => {
|
||||
if (!existsSync(logPath)) return []
|
||||
return readFileSync(logPath, 'utf-8').split('\n').filter(Boolean)
|
||||
}
|
||||
|
||||
const mockDevice = () => {
|
||||
const dev = join(stubDir, 'dev-kvm')
|
||||
writeFileSync(dev, '')
|
||||
return dev
|
||||
}
|
||||
|
||||
describe('grant_kvm_access', () => {
|
||||
it('is a no-op when the device does not exist', () => {
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(join(stubDir, 'missing-device'))}; echo ok`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('ok')
|
||||
expect(stubCalls()).toEqual([])
|
||||
})
|
||||
|
||||
it('is a no-op when the device gid is not numeric', () => {
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(mockDevice())}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: 'abc',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('ok')
|
||||
expect(stubCalls()).toEqual([])
|
||||
})
|
||||
|
||||
it('reuses the existing group holding the device gid', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: '44',
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('Granted node access')
|
||||
expect(stubCalls().some((c) => c === 'usermod -aG video node')).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('runuser -u node -- test -r'))).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('runuser -u node -- test -w'))).toBe(true)
|
||||
})
|
||||
|
||||
it('creates a matching group when none holds the device gid', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: '232',
|
||||
OCM_STUB_GROUP_HOLDER: '',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('Granted node access')
|
||||
expect(stubCalls().some((c) => c === 'groupadd -g 232 kvm')).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('usermod -aG kvm node'))).toBe(true)
|
||||
})
|
||||
|
||||
it('fails clearly when the group cannot be created', () => {
|
||||
writeStub('groupadd', `echo "groupadd $*" >> "$OCM_STUB_LOG"\nexit 1`)
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_DEV_GID: '232',
|
||||
OCM_STUB_GROUP_HOLDER: '',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/could not create group/)
|
||||
})
|
||||
|
||||
it('fails clearly when node cannot be added to the group', () => {
|
||||
writeStub('usermod', `echo "usermod $*" >> "$OCM_STUB_LOG"\nexit 1`)
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/could not add node to group/)
|
||||
})
|
||||
|
||||
it('fails clearly when the node user cannot open the device', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
OCM_STUB_RUNUSER_EXIT: '1',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/node cannot access/)
|
||||
})
|
||||
})
|
||||
|
||||
const extractInstallOpencode = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const match = entrypoint.match(/^install_opencode\(\) \{\n[\s\S]*?\n\}/m)
|
||||
if (!match) throw new Error('install_opencode() not found in docker-entrypoint.sh')
|
||||
return match[0]
|
||||
}
|
||||
|
||||
const extractOpenCodeInstallSection = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const startMarker = 'echo "Checking OpenCode installation..."'
|
||||
const endMarker = 'echo "Starting OpenCode Manager Backend..."'
|
||||
const start = entrypoint.indexOf(startMarker)
|
||||
const end = entrypoint.indexOf(endMarker)
|
||||
if (start === -1 || end === -1 || end <= start) {
|
||||
throw new Error('OpenCode install section not found in docker-entrypoint.sh')
|
||||
}
|
||||
return entrypoint.slice(start, end)
|
||||
}
|
||||
|
||||
const runOpenCodeSection = (snippet: string, env: Record<string, string> = {}) => {
|
||||
const scriptPath = join(stubDir, 'test.sh')
|
||||
const homeDir = join(stubDir, 'home')
|
||||
writeFileSync(scriptPath, `set -e\n${snippet}\n`)
|
||||
return spawnSync('bash', [scriptPath], {
|
||||
encoding: 'utf-8',
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${stubDir}:${homeDir}/.opencode/bin:/usr/bin:/bin`,
|
||||
OCM_STUB_LOG: logPath,
|
||||
HOME: homeDir,
|
||||
...env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stubInstallTools = () => {
|
||||
writeStub('curl', `echo "curl $*" >> "$OCM_STUB_LOG"
|
||||
rm -rf /tmp/opencode /tmp/opencode.tar.gz
|
||||
mkdir -p "$HOME/.opencode/bin"
|
||||
printf '#!/bin/bash\\necho 1.18.16\\n' > "$HOME/.opencode/bin/opencode"
|
||||
chmod +x "$HOME/.opencode/bin/opencode"
|
||||
printf 'fake binary\\n' > /tmp/opencode`)
|
||||
writeStub('tar', `echo "tar $*" >> "$OCM_STUB_LOG"`)
|
||||
}
|
||||
|
||||
const curlLog = () => stubCalls().filter((c) => c.startsWith('curl '))
|
||||
|
||||
describe('install_opencode', () => {
|
||||
it('installs the bundled verified version, never latest', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`)
|
||||
expect(res.status).toBe(0)
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('honors an OPENCODE_BUNDLED_VERSION override for the download URL', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '1.22.0',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.22\.0\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('reinstalls the bundled verified version when opencode is missing', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('OpenCode not found. Installing...')
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('repairs a below-minimum opencode with the bundled verified version, not latest', () => {
|
||||
stubInstallTools()
|
||||
writeStub('opencode', `echo "opencode version 1.0.0"`)
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('below minimum required version')
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
})
|
||||
@@ -724,3 +724,31 @@ describe('installAssistantWorkspace', () => {
|
||||
expect(result.defaultAgent?.created).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('assistant mode directory contract', () => {
|
||||
it('resolves the assistant directory from the shared sandbox mount owner', async () => {
|
||||
const ws = await createTempAssistantWorkspace()
|
||||
try {
|
||||
const { getAssistantModePath, getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
|
||||
const { getAssistantModeDirectory } = await import('../../src/services/assistant-mode')
|
||||
const { sandboxSecretMaskPath } = await import('../../src/services/sandbox/command')
|
||||
|
||||
expect(getAssistantModeDirectory()).toBe(getAssistantModePath())
|
||||
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
|
||||
expect(getAssistantOpenCodeDir()).toBe(path.join(ws.assistantDir, '.opencode'))
|
||||
} finally {
|
||||
await ws.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the internal token underneath the sandboxed assistant .opencode directory', async () => {
|
||||
const ws = await createTempAssistantWorkspace()
|
||||
try {
|
||||
const { getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
|
||||
const tokenPath = path.join(ws.assistantDir, '.opencode/internal-token')
|
||||
expect(tokenPath).toContain(getAssistantOpenCodeDir())
|
||||
} finally {
|
||||
await ws.cleanup()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,32 @@ describe('ocm-gh-env plugin', () => {
|
||||
await expect(fs.access(file)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('atomically replaces a symlink at the plugin path with a regular file', async () => {
|
||||
const pluginDir = getGhEnvPluginDir(configHome)
|
||||
const pluginPath = path.join(pluginDir, 'ocm-gh-env.js')
|
||||
const symlinkTarget = path.join(pluginDir, 'attacker-hook.js')
|
||||
await fs.mkdir(pluginDir, { recursive: true })
|
||||
await fs.rm(pluginPath, { force: true })
|
||||
await fs.writeFile(symlinkTarget, 'export default async function () {}')
|
||||
await fs.symlink(symlinkTarget, pluginPath)
|
||||
|
||||
await installGhEnvPlugin(configHome)
|
||||
|
||||
const stat = await fs.lstat(pluginPath)
|
||||
expect(stat.isFile()).toBe(true)
|
||||
expect(stat.isSymbolicLink()).toBe(false)
|
||||
expect(await fs.readFile(pluginPath, 'utf-8')).toContain('shell.env')
|
||||
expect(await fs.readFile(symlinkTarget, 'utf-8')).toBe('export default async function () {}')
|
||||
})
|
||||
|
||||
it('throws when the plugin file cannot be written instead of swallowing the failure', async () => {
|
||||
const blockedHome = path.join(configHome, 'blocked')
|
||||
await fs.mkdir(blockedHome, { recursive: true })
|
||||
await fs.writeFile(path.join(blockedHome, 'opencode'), 'not a directory')
|
||||
|
||||
await expect(installGhEnvPlugin(blockedHome)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('injects fetched GH env into output.env', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const managerMock = vi.hoisted(() => ({
|
||||
getLastStartupError: vi.fn<() => string | null>(() => null),
|
||||
clearStartupError: vi.fn<() => void>(),
|
||||
restart: vi.fn<() => Promise<void>>(),
|
||||
checkHealth: vi.fn<() => boolean>(() => true),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: managerMock,
|
||||
}))
|
||||
|
||||
import {
|
||||
restartOpenCode,
|
||||
setOpenCodeRestartCoordinator,
|
||||
} from '../../src/services/opencode-restart'
|
||||
import type { OpenCodeRestartCoordinator } from '../../src/services/opencode-restart-coordinator'
|
||||
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
function createSupervisor(healthy: boolean): OpenCodeSupervisor {
|
||||
return {
|
||||
restart: vi.fn().mockResolvedValue({ healthy }),
|
||||
reloadConfig: vi.fn(),
|
||||
} as unknown as OpenCodeSupervisor
|
||||
}
|
||||
|
||||
function createCoordinator(healthy: boolean, resumedSessionIDs: string[] = []): OpenCodeRestartCoordinator {
|
||||
return {
|
||||
runWithResume: vi.fn(async (restart: () => Promise<boolean>) => ({
|
||||
healthy: healthy ?? (await restart()),
|
||||
resumedSessionIDs,
|
||||
})),
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
}
|
||||
|
||||
describe('restartOpenCode', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
it('throws with the startup failure reason when the coordinator reports an unhealthy restart', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting')
|
||||
setOpenCodeRestartCoordinator(createCoordinator(false))
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(true))).rejects.toThrow(
|
||||
'OpenCode version 1.18.15 does not support sandboxed bash tool rewriting',
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves resumed session IDs only when the coordinator reports a healthy restart', async () => {
|
||||
setOpenCodeRestartCoordinator(createCoordinator(true, ['session-1', 'session-2']))
|
||||
|
||||
const result = await restartOpenCode(createSupervisor(true))
|
||||
|
||||
expect(result).toEqual({ resumedSessionIDs: ['session-1', 'session-2'] })
|
||||
})
|
||||
|
||||
it('throws with the startup failure reason when the supervisor restart is unhealthy without a coordinator', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue('OpenCode server failed to become healthy')
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow('OpenCode server failed to become healthy')
|
||||
})
|
||||
|
||||
it('returns without resumed sessions when the supervisor restart is healthy without a coordinator', async () => {
|
||||
const supervisor = createSupervisor(true)
|
||||
|
||||
const result = await restartOpenCode(supervisor)
|
||||
|
||||
expect(result).toEqual({ resumedSessionIDs: [] })
|
||||
expect(supervisor.restart).toHaveBeenCalledWith('settings_restart')
|
||||
})
|
||||
|
||||
it('uses a generic failure message when no startup error is recorded', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue(null)
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow(
|
||||
'OpenCode server restart did not complete successfully',
|
||||
)
|
||||
})
|
||||
|
||||
it('propagates a manager restart failure when no supervisor is provided', async () => {
|
||||
managerMock.restart.mockRejectedValue(new Error('server failed to become healthy'))
|
||||
|
||||
await expect(restartOpenCode()).rejects.toThrow('server failed to become healthy')
|
||||
expect(managerMock.clearStartupError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ensureDirectoryExists, writeFileContent } from '../../src/services/file-operations'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
@@ -36,6 +36,8 @@ interface FakeManager {
|
||||
reloadConfig: ReturnType<typeof vi.fn>
|
||||
clearStartupError: ReturnType<typeof vi.fn>
|
||||
getLastStartupError: ReturnType<typeof vi.fn>
|
||||
isLastStartupErrorNonRecoverable: ReturnType<typeof vi.fn>
|
||||
setLifecycleInitialized: ReturnType<typeof vi.fn>
|
||||
getPort: ReturnType<typeof vi.fn>
|
||||
getVersion: ReturnType<typeof vi.fn>
|
||||
getMinVersion: ReturnType<typeof vi.fn>
|
||||
@@ -51,6 +53,10 @@ interface FakeSettingsService {
|
||||
}
|
||||
|
||||
describe('OpenCodeSupervisor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const createManager = (): FakeManager => ({
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -60,6 +66,8 @@ describe('OpenCodeSupervisor', () => {
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn(),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
@@ -122,6 +130,65 @@ describe('OpenCodeSupervisor', () => {
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('opens the proxy lifecycle gate when the managed child is attested healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('keeps the proxy lifecycle gate closed when startup fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.healthy).toBe(false)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate when recovery is exhausted and reopens it once health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('startup failed'))
|
||||
manager.checkHealth
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const failed = await supervisor.start()
|
||||
expect(failed.healthy).toBe(false)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('does not recover polling failures until the threshold is reached', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
@@ -137,6 +204,35 @@ describe('OpenCodeSupervisor', () => {
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(status.failureCount).toBe(1)
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate on a below-threshold health failure and reopens it once health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
|
||||
const unhealthy = await supervisor.checkNow('manual')
|
||||
|
||||
expect(unhealthy.state).toBe('unhealthy')
|
||||
expect(unhealthy.failureCount).toBe(1)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('captures debug state before debug recovery', async () => {
|
||||
@@ -171,4 +267,306 @@ describe('OpenCodeSupervisor', () => {
|
||||
|
||||
expect(manager.checkHealth).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not run configuration recovery for a non-recoverable startup failure', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(status.healthy).toBe(false)
|
||||
expect(status.lastError).toContain('does not support sandboxed bash tool rewriting')
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('does not run configuration recovery when a manual restart fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.restart.mockRejectedValueOnce(new Error('Failed to quarantine untrusted OpenCode plugins'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.restart('settings_restart')
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('stops the recovery ladder when a recovery restart fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('startup failed'))
|
||||
manager.checkHealth.mockResolvedValue(false)
|
||||
manager.restart.mockImplementation(async () => {
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
throw new Error('Failed to install the sandbox OpenCode plugin')
|
||||
})
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(status.lastError).toContain('Failed to install the sandbox OpenCode plugin')
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('still follows the normal recovery ladder for a recoverable startup failure', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode config validation failed: command.review: Invalid'))
|
||||
manager.checkHealth
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('healthy')
|
||||
expect(settings.archiveBrokenConfig).toHaveBeenCalledWith('default')
|
||||
expect(settings.restoreToLastKnownGoodConfig).toHaveBeenCalledWith('default')
|
||||
expect(settings.updateOpenCodeConfig).toHaveBeenCalled()
|
||||
expect(writeFileContent).toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('executes a restart requested during an active restart after the active restart completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const first = supervisor.restart('settings_restart')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
|
||||
const second = supervisor.restart('manual')
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
|
||||
releaseRestart()
|
||||
|
||||
const [firstStatus, secondStatus] = await Promise.all([first, second])
|
||||
|
||||
expect(manager.restart).toHaveBeenCalledTimes(2)
|
||||
expect(firstStatus.healthy).toBe(true)
|
||||
expect(secondStatus.healthy).toBe(true)
|
||||
})
|
||||
|
||||
it('executes a reload requested during an active reload after the active reload completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseReload!: () => void
|
||||
manager.reloadConfig.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseReload = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const first = supervisor.reloadConfig('settings_reload')
|
||||
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
|
||||
|
||||
const second = supervisor.reloadConfig('manual')
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.reloadConfig).toHaveBeenCalledTimes(1)
|
||||
|
||||
releaseReload()
|
||||
|
||||
const [firstStatus, secondStatus] = await Promise.all([first, second])
|
||||
|
||||
expect(manager.reloadConfig).toHaveBeenCalledTimes(2)
|
||||
expect(firstStatus.healthy).toBe(true)
|
||||
expect(secondStatus.healthy).toBe(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate for the whole restart transition and reopens once healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const restart = supervisor.restart('settings_restart')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseRestart()
|
||||
const status = await restart
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate for the whole reload transition and reopens once healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseReload!: () => void
|
||||
manager.reloadConfig.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseReload = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const reload = supervisor.reloadConfig('settings_reload')
|
||||
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseReload()
|
||||
const status = await reload
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate while stopping and never reopens it', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseStop!: () => void
|
||||
manager.stop.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseStop = resolve }),
|
||||
)
|
||||
|
||||
const stopPromise = supervisor.stop()
|
||||
await vi.waitFor(() => expect(manager.stop).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseStop()
|
||||
await stopPromise
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate while recovering a polling failure until health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
|
||||
const recovering = supervisor.checkNow('manual')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseRestart()
|
||||
const status = await recovering
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('executes a stop requested during an active restart after the restart completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const restart = supervisor.restart('manual')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
|
||||
const stopPromise = supervisor.stop()
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.stop).not.toHaveBeenCalled()
|
||||
|
||||
releaseRestart()
|
||||
|
||||
await Promise.all([restart, stopPromise])
|
||||
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
expect(manager.stop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -203,6 +203,68 @@ describe('OpenCodeClient', () => {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '192.168.1.10', configurable: true, writable: true })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', '127.0.0.1')
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
|
||||
} finally {
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '127.0.0.1', configurable: true, writable: true })
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('brackets an IPv6 loopback host in the request URL', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', '::1')
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
expect(capturedUrl?.origin).toBe('http://[::1]:5551')
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves a lazy host override on every request', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
const hosts: string[] = []
|
||||
let currentHost = '192.168.1.10'
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
hosts.push(input instanceof URL ? input.hostname : new URL(input.toString()).hostname)
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', () => currentHost)
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
currentHost = '127.0.0.1'
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
expect(hosts).toEqual(['192.168.1.10', '127.0.0.1'])
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('forwardRaw', () => {
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
decideSandboxProxyBlock,
|
||||
decideSandboxConfigBody,
|
||||
decideSandboxMcpAddBody,
|
||||
decideSandboxAuthBody,
|
||||
decideSandboxMutationBody,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
isSandboxAuthWrite,
|
||||
SANDBOX_BLOCKED_REASON_PREFIX,
|
||||
SANDBOX_CONFIG_MUTATION_REASON_PREFIX,
|
||||
} from '../../../src/services/opencode/proxy-policy'
|
||||
|
||||
describe('sandbox proxy policy', () => {
|
||||
it('passes every route through when enforcement is off', () => {
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/shell')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/pty')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/command')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint when enforced', () => {
|
||||
const decision = decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell')
|
||||
expect(decision.blocked).toBe(true)
|
||||
if (decision.blocked) {
|
||||
expect(decision.reason).toContain(SANDBOX_BLOCKED_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('host process')
|
||||
}
|
||||
})
|
||||
|
||||
it('blocks custom slash command execution when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/command').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks PTY creation and connection when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty/p1/connect').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('treats /api-prefixed execution routes identically to unprefixed routes when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/pty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/shell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/command').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/p%74y').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/session')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/session/ses_1/message')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators inside the /api prefix when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fsession/ses_1/shell').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies /api-prefixed config, mcp, and auth writes identically when enforced', () => {
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/%63onfig')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config/')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp/')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai/extra')).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves non-execution routes reachable when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/message')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'DELETE', '/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/config')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt_async')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('ignores methods that do not match a blocked route', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/shell')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/command')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('blocks percent-encoded spellings of blocked routes when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73hell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73%68%65%6c%6c').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%63ommand').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/p%74y').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/p%74y/ses_1/connect').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators, double-encoded, control, and malformed paths when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%2F..').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1%2Fshell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%5Cx').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%2573hell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%00').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%zz').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%c0%ae').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('passes safely encoded non-execution paths through when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/%6dessage')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt%5Fasync')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('classifies only enforced PATCH /config as a config mutation', () => {
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/config')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/%63onfig')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/config/')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/project')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'POST', '/config')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'GET', '/config')).toBe(false)
|
||||
expect(isSandboxConfigMutation(false, 'PATCH', '/config')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-config mutation bodies through untouched', () => {
|
||||
expect(decideSandboxConfigBody(true, 'GET', '/config', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(true, 'POST', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(true, 'PATCH', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(false, 'PATCH', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('strips configured plugins from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
theme: 'dark',
|
||||
plugin: ['opencode-plugin-npm'],
|
||||
mcp: { remote: { type: 'remote', url: 'https://example.com' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.theme).toBe('dark')
|
||||
expect(body.plugin).toBeUndefined()
|
||||
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
|
||||
}
|
||||
})
|
||||
|
||||
it('strips local MCP servers and formatter config from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] }, remote: { type: 'remote', url: 'https://example.com' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.formatter).toBeUndefined()
|
||||
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves a config mutation with no host-execution sections unchanged when enforced', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))
|
||||
expect(decision).toEqual({ kind: 'sanitized', body: JSON.stringify({ theme: 'dark' }) })
|
||||
})
|
||||
|
||||
it('fails closed on malformed or non-object config mutation bodies when enforced', () => {
|
||||
const invalidJson = decideSandboxConfigBody(true, 'PATCH', '/config', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const emptyBody = decideSandboxConfigBody(true, 'PATCH', '/config', '')
|
||||
expect(emptyBody.kind).toBe('reject')
|
||||
|
||||
const arrayBody = decideSandboxConfigBody(true, 'PATCH', '/config', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('strips LSP servers and experimental hook commands from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server', '--stdio'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'script.sh'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
model: 'x',
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.lsp).toBeUndefined()
|
||||
expect(body.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
expect(body.model).toBe('x')
|
||||
}
|
||||
})
|
||||
|
||||
it('strips the shell configuration from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
shell: { command: '/repo/bin/evil-shell', args: [] },
|
||||
model: 'x',
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.shell).toBeUndefined()
|
||||
expect(body.model).toBe('x')
|
||||
}
|
||||
})
|
||||
|
||||
it('strips an enabling lsp boolean from an enforced config mutation while keeping an explicit false', () => {
|
||||
const enabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: true, model: 'x' }))
|
||||
expect(enabled.kind).toBe('sanitized')
|
||||
if (enabled.kind === 'sanitized') {
|
||||
expect(JSON.parse(enabled.body)).toEqual({ model: 'x' })
|
||||
}
|
||||
|
||||
const disabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: false, model: 'x' }))
|
||||
expect(disabled).toEqual({ kind: 'sanitized', body: JSON.stringify({ lsp: false, model: 'x' }) })
|
||||
})
|
||||
|
||||
it('drops the experimental section entirely when only its hook carries commands', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
experimental: { hook: { session_completed: [{ command: ['echo', 'done'] }] } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.experimental).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('classifies only enforced POST /mcp as an MCP add', () => {
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/%6dcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp/')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp/my-server/connect')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'GET', '/mcp')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'DELETE', '/mcp')).toBe(false)
|
||||
expect(isSandboxMcpAdd(false, 'POST', '/mcp')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-MCP-add bodies through untouched', () => {
|
||||
expect(decideSandboxMcpAddBody(true, 'GET', '/mcp', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMcpAddBody(true, 'POST', '/mcp/my-server/connect', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMcpAddBody(false, 'POST', '/mcp', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'], environment: { TOKEN: 'secret' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
if (decision.kind === 'reject') {
|
||||
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('only remote MCP servers')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a command-bearing MCP add even without an explicit local type while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { command: ['npx', 'evil-server'] },
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('passes a provably remote MCP server add through while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}))
|
||||
expect(decision).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects malformed or non-object MCP add bodies while enforced', () => {
|
||||
const invalidJson = decideSandboxMcpAddBody(true, 'POST', '/mcp', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const arrayBody = decideSandboxMcpAddBody(true, 'POST', '/mcp', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('dispatches MCP adds before config mutations and leaves other bodies untouched', () => {
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
})).kind).toBe('reject')
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}))).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMutationBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))).toEqual({
|
||||
kind: 'sanitized',
|
||||
body: JSON.stringify({ theme: 'dark' }),
|
||||
})
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('strips custom provider npm selectors from an enforced config mutation while keeping built-in providers', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
model: 'x',
|
||||
provider: {
|
||||
'openai-native': { options: { apiKey: 'k' } },
|
||||
evil: { npm: 'file:///repo/evil-provider.js', options: { token: 't' } },
|
||||
remote: { npm: '@scope/remote-provider', models: { 'm-1': { name: 'M1' } } },
|
||||
},
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.model).toBe('x')
|
||||
expect(body.provider).toEqual({ 'openai-native': { options: { apiKey: 'k' } } })
|
||||
}
|
||||
})
|
||||
|
||||
it('classifies only enforced PUT /auth/{provider} as an auth write', () => {
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/%6fpenai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'POST', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'DELETE', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'GET', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai/extra')).toBe(false)
|
||||
expect(isSandboxAuthWrite(false, 'PUT', '/auth/openai')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-auth-write bodies through untouched', () => {
|
||||
expect(decideSandboxAuthBody(true, 'GET', '/auth/openai', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(true, 'DELETE', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(true, 'PUT', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(false, 'PUT', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write while enforced', () => {
|
||||
const decision = decideSandboxAuthBody(true, 'PUT', '/auth/sso.example.com', JSON.stringify({
|
||||
type: 'wellknown',
|
||||
key: 'SSO_TOKEN',
|
||||
token: 't',
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
if (decision.kind === 'reject') {
|
||||
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('well-known')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a malformed or non-object auth write body while enforced', () => {
|
||||
const invalidJson = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const arrayBody = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('passes api and oauth auth writes through while enforced', () => {
|
||||
const api = decideSandboxAuthBody(true, 'PUT', '/auth/anthropic', JSON.stringify({
|
||||
type: 'api',
|
||||
key: 'sk-test',
|
||||
}))
|
||||
expect(api).toEqual({ kind: 'passthrough' })
|
||||
|
||||
const oauth = decideSandboxAuthBody(true, 'PUT', '/auth/github', JSON.stringify({
|
||||
type: 'oauth',
|
||||
access: 'a',
|
||||
refresh: 'r',
|
||||
expires: 1,
|
||||
}))
|
||||
expect(oauth).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('dispatches auth writes before config mutations in the combined body decision', () => {
|
||||
expect(decideSandboxMutationBody(true, 'PUT', '/auth/evil', JSON.stringify({
|
||||
type: 'wellknown',
|
||||
key: 'K',
|
||||
token: 't',
|
||||
})).kind).toBe('reject')
|
||||
expect(decideSandboxMutationBody(true, 'PUT', '/auth/openai', JSON.stringify({
|
||||
type: 'api',
|
||||
key: 'k',
|
||||
}))).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { accessSync, realpathSync, statSync } from 'fs'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { detectSandboxCapability, resetSandboxCapabilityCache } from '../../../src/services/sandbox/capability'
|
||||
import { logger } from '../../../src/utils/logger'
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
accessSync: vi.fn(),
|
||||
realpathSync: vi.fn((candidate: string) => candidate),
|
||||
statSync: vi.fn(() => ({ uid: 0, gid: 0, mode: 0o755 })),
|
||||
constants: {
|
||||
R_OK: 4,
|
||||
W_OK: 2,
|
||||
X_OK: 1,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
spawnSync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockAccessSync = accessSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockSpawnSync = spawnSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockRealpathSync = realpathSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockStatSync = statSync as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('detectSandboxCapability', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
mockRealpathSync.mockImplementation((candidate: string) => candidate)
|
||||
mockStatSync.mockReturnValue({ uid: 0, gid: 0, mode: 0o755 })
|
||||
resetSandboxCapabilityCache()
|
||||
})
|
||||
afterEach(() => {
|
||||
resetSandboxCapabilityCache()
|
||||
})
|
||||
|
||||
it('reports unavailable when /dev/kvm is not accessible or writable', () => {
|
||||
mockAccessSync.mockImplementation(() => {
|
||||
throw new Error('ENOENT')
|
||||
})
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toContain('/dev/kvm')
|
||||
expect(mockSpawnSync).not.toHaveBeenCalled()
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('/dev/kvm'))
|
||||
})
|
||||
|
||||
it('reports unavailable when msb --version exits with a non-zero status', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 1, stdout: '', stderr: 'msb: not found' })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
})
|
||||
|
||||
it('reports unavailable when msb --version fails to spawn', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: null, stdout: '', stderr: '', error: new Error('spawn ENOENT') })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
})
|
||||
|
||||
it('reports available with the trimmed msb version when both probes succeed', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result).toEqual({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
})
|
||||
|
||||
it('reports unavailable when an explicit exec user uid does not match the manager uid', async () => {
|
||||
process.env.SANDBOX_EXEC_USER = '2000'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { logger } = await import('../../../src/utils/logger')
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
const getuid = vi.spyOn(proc, 'getuid').mockReturnValue(1000)
|
||||
const getgid = vi.spyOn(proc, 'getgid').mockReturnValue(1000)
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toContain('SANDBOX_EXEC_USER')
|
||||
expect(result.reason).toContain('1000')
|
||||
expect(spawnSync).not.toHaveBeenCalled()
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('SANDBOX_EXEC_USER'))
|
||||
expect(getuid).toHaveBeenCalled()
|
||||
expect(getgid).toHaveBeenCalled()
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
vi.restoreAllMocks()
|
||||
}
|
||||
})
|
||||
|
||||
it('memoizes the probe result until the cache is reset', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
|
||||
const first = detectSandboxCapability()
|
||||
const second = detectSandboxCapability()
|
||||
|
||||
expect(mockSpawnSync).toHaveBeenCalledTimes(1)
|
||||
expect(second).toBe(first)
|
||||
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const third = detectSandboxCapability()
|
||||
|
||||
expect(mockSpawnSync).toHaveBeenCalledTimes(2)
|
||||
expect(third).toEqual(first)
|
||||
})
|
||||
|
||||
it('resolves a relative MSB_PATH against PATH to one absolute executable before probing the version', async () => {
|
||||
const { mkdtempSync, writeFileSync, rmSync } = await vi.importActual<typeof import('fs')>('fs')
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-bin-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
|
||||
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(true)
|
||||
expect(spawnSync).toHaveBeenCalledWith(
|
||||
path.join(fakeBin, 'msb'),
|
||||
['--version'],
|
||||
expect.objectContaining({ encoding: 'utf8' }),
|
||||
)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('reports unavailable when a relative MSB_PATH cannot be resolved on PATH', async () => {
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = '/nonexistent-ocm-bin'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation((target: string) => {
|
||||
if (target === '/dev/kvm') return
|
||||
throw new Error('ENOENT')
|
||||
})
|
||||
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
expect(spawnSync).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,616 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
SANDBOX_UNAVAILABLE_PREFIX,
|
||||
buildBlockedCommand,
|
||||
buildCanonicalSandboxSpec,
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
buildSandboxVersionArgs,
|
||||
quoteForShell,
|
||||
resolveExpectedSandboxNetworkPolicy,
|
||||
resolveSandboxExecUser,
|
||||
resolveSandboxExecUserUid,
|
||||
sandboxMountRoots,
|
||||
sandboxNetworkPolicyMismatch,
|
||||
sandboxSecretMaskPath,
|
||||
} from '../../../src/services/sandbox/command'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('sandbox command builders', () => {
|
||||
it('builds the version probe as exactly --version', () => {
|
||||
expect(buildSandboxVersionArgs()).toEqual(['--version'])
|
||||
})
|
||||
|
||||
it('builds inspect args targeting the shared workspace sandbox with JSON output', () => {
|
||||
expect(buildSandboxInspectArgs()).toEqual(['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json'])
|
||||
})
|
||||
|
||||
it('builds remove args that force-remove the shared workspace sandbox', () => {
|
||||
expect(buildSandboxRemoveArgs()).toEqual(['rm', '--force', WORKSPACE_SANDBOX_NAME])
|
||||
})
|
||||
|
||||
it('builds list args that emit machine-readable JSON for all sandboxes', () => {
|
||||
expect(buildSandboxListArgs()).toEqual(['ls', '--format', 'json'])
|
||||
})
|
||||
|
||||
it('builds start args targeting the shared workspace sandbox', () => {
|
||||
expect(buildSandboxStartArgs()).toEqual(['start', WORKSPACE_SANDBOX_NAME])
|
||||
})
|
||||
|
||||
it('builds managed-stop args that filter by the ocm.managed label', () => {
|
||||
expect(buildSandboxStopManagedArgs()).toEqual(['stop', '--label', 'ocm.managed=true'])
|
||||
})
|
||||
|
||||
it('escapes embedded single quotes so values survive a shell round-trip', () => {
|
||||
const value = "echo 'a'b'"
|
||||
expect(quoteForShell(value)).toBe(`'echo '\\''a'\\''b'\\'''`)
|
||||
|
||||
const result = spawnSync('sh', ['-c', `printf '%s' ${quoteForShell(value)}`], { encoding: 'utf8' })
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe(value)
|
||||
})
|
||||
|
||||
it('builds create args with exactly two identical-path bind mounts and the detached flag', () => {
|
||||
const args = buildSandboxCreateArgs()
|
||||
|
||||
expect(args[0]).toBe('run')
|
||||
expect(args).toContain('-d')
|
||||
expect(args).toContain('--name')
|
||||
expect(args[args.indexOf('--name') + 1]).toBe(WORKSPACE_SANDBOX_NAME)
|
||||
expect(args[args.indexOf('-w') + 1]).toBe(getReposPath())
|
||||
expect(args[args.indexOf('-u') + 1]).toBe(resolveSandboxExecUser())
|
||||
|
||||
const labelArgs: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const value = args[i + 1]
|
||||
if (args[i] === '--label' && value !== undefined) {
|
||||
labelArgs.push(value)
|
||||
}
|
||||
}
|
||||
expect(labelArgs).toContain('ocm.managed=true')
|
||||
expect(labelArgs).toContain(`ocm.net=${ENV.SANDBOX.NET}`)
|
||||
|
||||
const mountArgs: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const value = args[i + 1]
|
||||
if (args[i] === '--mount-dir' && value !== undefined) {
|
||||
mountArgs.push(value)
|
||||
}
|
||||
}
|
||||
expect(mountArgs).toEqual(sandboxMountRoots().map((root) => `${root}:${root}`))
|
||||
expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`)
|
||||
expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`)
|
||||
})
|
||||
|
||||
it('masks the assistant .opencode directory with a tmpfs overlay', () => {
|
||||
const args = buildSandboxCreateArgs()
|
||||
|
||||
expect(args[args.indexOf('--tmpfs') + 1]).toBe(getAssistantOpenCodeDir())
|
||||
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
|
||||
})
|
||||
|
||||
it('never mounts the SSH/config/state workspace directories', () => {
|
||||
const joined = buildSandboxCreateArgs().join(' ')
|
||||
const workspacePath = path.dirname(getReposPath())
|
||||
|
||||
expect(joined).not.toContain(`${workspacePath}/.config`)
|
||||
expect(joined).not.toContain(`${workspacePath}/config`)
|
||||
expect(joined).not.toContain('auth.json')
|
||||
expect(joined).not.toContain(`${workspacePath}/.opencode`)
|
||||
expect(joined).not.toContain('/.opencode/state')
|
||||
})
|
||||
|
||||
it('derives a canonical spec from the create args matching the security configuration', () => {
|
||||
const spec = buildCanonicalSandboxSpec()
|
||||
const labels = spec.labels as Record<string, string>
|
||||
const resources = spec.resources as Record<string, number>
|
||||
const runtime = spec.runtime as Record<string, unknown>
|
||||
const mounts = spec.mounts as Array<Record<string, unknown>>
|
||||
const network = spec.network as Record<string, unknown>
|
||||
const lifecycle = spec.lifecycle as Record<string, unknown>
|
||||
|
||||
expect(spec.name).toBe(WORKSPACE_SANDBOX_NAME)
|
||||
const canonicalImage = spec.image as Record<string, { reference: string } | undefined>
|
||||
expect(canonicalImage.Oci?.reference).toBe(ENV.SANDBOX.IMAGE)
|
||||
expect(labels['ocm.managed']).toBe('true')
|
||||
expect(labels['ocm.net']).toBe(ENV.SANDBOX.NET)
|
||||
expect(resources.cpus).toBe(ENV.SANDBOX.CPUS)
|
||||
expect(typeof resources.memory_mib).toBe('number')
|
||||
expect(runtime.workdir).toBe(getReposPath())
|
||||
expect(runtime.user).toBe(resolveSandboxExecUser())
|
||||
expect(runtime.cmd).toEqual(['sleep', 'infinity'])
|
||||
expect(runtime.entrypoint).toBeNull()
|
||||
expect(spec.patches).toEqual([])
|
||||
expect(network.enabled).toBe(true)
|
||||
expect(network.ports).toEqual([])
|
||||
expect(lifecycle.ephemeral).toBe(false)
|
||||
expect(lifecycle.max_duration_secs).toBeNull()
|
||||
expect(lifecycle.idle_timeout_secs).toBeNull()
|
||||
|
||||
const binds = mounts.filter((mount) => mount.type === 'Bind')
|
||||
expect(binds).toHaveLength(2)
|
||||
expect(binds.map((mount) => mount.host)).toEqual([getReposPath(), getScheduleWorktreesPath()])
|
||||
for (const mount of binds) {
|
||||
expect(mount.guest).toBe(mount.host)
|
||||
const options = mount.options as Record<string, boolean>
|
||||
expect(options.readonly).toBe(false)
|
||||
expect(options.noexec).toBe(false)
|
||||
expect(options.nosuid).toBe(false)
|
||||
expect(options.nodev).toBe(false)
|
||||
expect(mount.stat_virtualization).toBe('strict')
|
||||
expect(mount.host_permissions).toBe('private')
|
||||
expect(mount.follow_root_symlinks).toBe(false)
|
||||
expect(mount.quota_mib).toBeNull()
|
||||
}
|
||||
|
||||
const tmpfs = mounts.find((mount) => mount.type === 'Tmpfs')
|
||||
expect(tmpfs?.guest).toBe(getAssistantOpenCodeDir())
|
||||
expect((tmpfs as Record<string, unknown>).size_mib).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts real repo dirs and schedule worktrees while rejecting config, missing, and unrelated paths', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-roots-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'repos')
|
||||
const schedules = path.join(tmp, 'schedule-worktrees')
|
||||
mkdirSync(path.join(repos, 'org', 'repo', 'subdir'), { recursive: true })
|
||||
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
|
||||
mkdirSync(path.join(tmp, '.config', 'opencode'), { recursive: true })
|
||||
|
||||
process.env.WORKSPACE_PATH = tmp
|
||||
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
await expect(resolveSandboxWorkDirectory(repos)).resolves.toBe(repos)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'org', 'repo', 'subdir'))).resolves.toBe(
|
||||
path.join(repos, 'org', 'repo', 'subdir'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(schedules, 'job-1-run-2'))).resolves.toBe(
|
||||
path.join(schedules, 'job-1-run-2'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, '..', '.config', 'opencode'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(`${repos}-extra`)).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'missing'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory('/etc')).resolves.toBeNull()
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns canonical guest paths for symlinks inside the roots and null for escapes', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-escape-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'repos')
|
||||
const schedules = path.join(tmp, 'schedule-worktrees')
|
||||
mkdirSync(path.join(tmp, 'outside'), { recursive: true })
|
||||
mkdirSync(path.join(repos, 'repo'), { recursive: true })
|
||||
mkdirSync(path.join(repos, 'other-repo'), { recursive: true })
|
||||
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
|
||||
symlinkSync(path.join(tmp, 'outside'), path.join(repos, 'repo', 'escape'))
|
||||
symlinkSync(path.join(repos, 'other-repo'), path.join(repos, 'repo', 'inside-link'))
|
||||
symlinkSync(path.join(schedules, 'job-1-run-2'), path.join(repos, 'repo', 'cross-root-link'))
|
||||
|
||||
process.env.WORKSPACE_PATH = tmp
|
||||
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo'))).resolves.toBe(path.join(repos, 'repo'))
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape', 'nested'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'inside-link'))).resolves.toBe(
|
||||
path.join(repos, 'other-repo'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'cross-root-link'))).resolves.toBe(
|
||||
path.join(schedules, 'job-1-run-2'),
|
||||
)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('targets the shared sandbox with a per-command working directory and a verbatim guest payload', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-'))
|
||||
const msbPath = path.join(fakeBin, 'msb')
|
||||
const captureFile = path.join(fakeBin, 'payload.txt')
|
||||
writeFileSync(
|
||||
msbPath,
|
||||
[
|
||||
'#!/bin/sh',
|
||||
'payload=""',
|
||||
'prev=""',
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
|
||||
' prev="$arg"',
|
||||
'done',
|
||||
`printf '%s' "$payload" > "${captureFile}"`,
|
||||
'sh -c "$payload"',
|
||||
].join('\n'),
|
||||
{ mode: 0o755 },
|
||||
)
|
||||
process.env.MSB_PATH = msbPath
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
|
||||
|
||||
const directory = path.join(getReposPath(), 'foo')
|
||||
const command = 'echo "it\'s a test" && echo line2 | tr a-z A-Z\necho after-newline'
|
||||
const exec = buildSandboxExecCommandString(directory, command)
|
||||
|
||||
expect(exec).toBe(
|
||||
`${quoteForShell(msbPath)} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)}s -- sh -c ${quoteForShell(command)}`,
|
||||
)
|
||||
|
||||
const result = spawnSync('sh', ['-c', exec], {
|
||||
encoding: 'utf8',
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe("it's a test\nLINE2\nafter-newline\n")
|
||||
expect(readFileSync(captureFile, 'utf8')).toBe(command)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('passes MSB_PATH and the resolved exec identity to msb as single literal arguments', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-hostile-'))
|
||||
const captureFile = path.join(fakeBin, 'argv.txt')
|
||||
const msbPath = path.join(fakeBin, 'my msb')
|
||||
const hostileUser = 'node; echo hacked'
|
||||
writeFileSync(
|
||||
msbPath,
|
||||
[
|
||||
'#!/bin/sh',
|
||||
`printf '%s\\n' "$0" "$@" > "${captureFile}"`,
|
||||
'payload=""',
|
||||
'prev=""',
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
|
||||
' prev="$arg"',
|
||||
'done',
|
||||
'sh -c "$payload"',
|
||||
].join('\n'),
|
||||
{ mode: 0o755 },
|
||||
)
|
||||
|
||||
try {
|
||||
process.env.MSB_PATH = msbPath
|
||||
process.env.SANDBOX_EXEC_USER = hostileUser
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
|
||||
|
||||
const directory = path.join(getReposPath(), 'foo')
|
||||
const command = 'echo hostile-ok'
|
||||
const exec = buildSandboxExecCommandString(directory, command)
|
||||
|
||||
const result = spawnSync('sh', ['-c', exec], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH ?? ''}` },
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('hostile-ok\n')
|
||||
|
||||
const resolvedUser = resolveSandboxExecUser()
|
||||
expect(resolvedUser).toMatch(/^\d+:\d+$/)
|
||||
|
||||
const argv = readFileSync(captureFile, 'utf8').split('\n')
|
||||
expect(argv[0]).toBe(msbPath)
|
||||
expect(argv[argv.indexOf('-u') + 1]).toBe(resolvedUser)
|
||||
expect(argv[argv.indexOf('-w') + 1]).toBe(directory)
|
||||
expect(argv[argv.indexOf('-c') + 1]).toBe(command)
|
||||
expect(argv.join(' ')).not.toContain(hostileUser)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves the named exec user default to the manager uid:gid', () => {
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
|
||||
|
||||
expect(resolveSandboxExecUser()).toBe('1001:1002')
|
||||
expect(resolveSandboxExecUserUid()).toBe(1001)
|
||||
})
|
||||
|
||||
it('aligns a numeric exec user with the manager gid', async () => {
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
|
||||
process.env.SANDBOX_EXEC_USER = '1001'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
|
||||
expect(resolveSandboxExecUser()).toBe('1001:1002')
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps an explicit uid:gid exec user verbatim', async () => {
|
||||
process.env.SANDBOX_EXEC_USER = '1000:1000'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
|
||||
expect(resolveSandboxExecUser()).toBe('1000:1000')
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
}
|
||||
})
|
||||
|
||||
it('builds a blocked command that exits non-zero and writes the reason to stderr', () => {
|
||||
const reason = "KVM is unavailable (it's not a hypervisor host)"
|
||||
const command = buildBlockedCommand(reason)
|
||||
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
|
||||
|
||||
expect(SANDBOX_UNAVAILABLE_PREFIX).toBe('Sandbox enforcement is on but the sandbox is unavailable: ')
|
||||
expect(command).toBe(`printf '%s\n' ${quoteForShell(message)} >&2; exit 1`)
|
||||
|
||||
const result = spawnSync('sh', ['-c', command], { encoding: 'utf8' })
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toBe(`${message}\n`)
|
||||
expect(result.stdout).toBe('')
|
||||
})
|
||||
|
||||
it('resolves a relative MSB_PATH to one absolute executable found on PATH', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-resolve-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
|
||||
|
||||
expect(resolveSandboxExecutable()).toBe(path.join(fakeBin, 'msb'))
|
||||
expect(sandboxExecutablePath()).toBe(path.join(fakeBin, 'msb'))
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns null when a relative MSB_PATH has no executable candidate on PATH', async () => {
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = '/nonexistent-ocm-bin'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
})
|
||||
|
||||
it('returns an absolute MSB_PATH verbatim without consulting PATH', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-abs-'))
|
||||
const msbPath = path.join(fakeBin, 'my msb')
|
||||
writeFileSync(msbPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
process.env.MSB_PATH = msbPath
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
|
||||
|
||||
expect(resolveSandboxExecutable()).toBe(msbPath)
|
||||
expect(sandboxExecutablePath()).toBe(msbPath)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable located inside a mounted project root', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-mount-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
const originalPath = process.env.PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'workspace', 'repos')
|
||||
mkdirSync(path.join(repos, 'bin'), { recursive: true })
|
||||
writeFileSync(path.join(repos, 'bin', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
|
||||
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
|
||||
process.env.PATH = path.join(repos, 'bin')
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
process.env.PATH = originalPath
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable whose symlink resolves into a mounted project root', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-symlink-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
const originalPath = process.env.PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'workspace', 'repos')
|
||||
const bin = path.join(tmp, 'bin')
|
||||
mkdirSync(path.join(repos, 'evil'), { recursive: true })
|
||||
mkdirSync(bin)
|
||||
writeFileSync(path.join(repos, 'evil', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
symlinkSync(path.join(repos, 'evil', 'msb'), path.join(bin, 'msb'))
|
||||
|
||||
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
|
||||
process.env.PATH = bin
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
process.env.PATH = originalPath
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable writable by the manager user or a parent directory', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-writable-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox network policy attestation helpers', () => {
|
||||
const publicPolicy = {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
|
||||
it('resolves the public profile to the deny-by-default fixture policy', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public')).toEqual(publicPolicy)
|
||||
})
|
||||
|
||||
it('composes comma-separated profiles with a single DNS rule in profile order', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public,private,host')).toEqual({
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'host' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('deduplicates repeated profiles', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public, public')).toEqual(publicPolicy)
|
||||
})
|
||||
|
||||
it('returns null for terminal, unknown, or empty profiles', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('all')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('none')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public,unknown')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy(' ')).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts the source-faithful public policy fixture', () => {
|
||||
expect(sandboxNetworkPolicyMismatch(publicPolicy, resolveExpectedSandboxNetworkPolicy('public')!)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a policy with an allow-all wildcard rule', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
publicPolicy.rules[0],
|
||||
{ direction: 'egress', destination: { any: true }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy whose profile rule is broadened to specific protocols and ports', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
publicPolicy.rules[0],
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: ['tcp'], ports: [443], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy carrying stale rules from another profile', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
...publicPolicy.rules,
|
||||
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy missing a required rule', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [publicPolicy.rules[0]],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects an allow egress default with an unrestricted-egress reason', () => {
|
||||
const inspected = { default_egress: 'allow', default_ingress: 'allow', rules: [] }
|
||||
const mismatch = sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)
|
||||
expect(mismatch).toContain('unrestricted egress')
|
||||
})
|
||||
|
||||
it('rejects an altered ingress default', () => {
|
||||
const inspected = { ...publicPolicy, default_ingress: 'deny' }
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('default_ingress')
|
||||
})
|
||||
|
||||
it('rejects a missing or malformed policy', () => {
|
||||
const expected = resolveExpectedSandboxNetworkPolicy('public')!
|
||||
expect(sandboxNetworkPolicyMismatch(undefined, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch({ default_egress: 'deny' }, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch({ ...publicPolicy, rules: 'not-an-array' }, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch(
|
||||
{ ...publicPolicy, rules: [{ direction: 'egress', destination: { group: 'dns' }, action: 'allow' }] },
|
||||
expected,
|
||||
)).toContain('network policy')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DEFAULT_USER_PREFERENCES, UserPreferencesSchema } from '@opencode-manager/shared/schemas'
|
||||
|
||||
describe('sandbox config', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.SANDBOX_IMAGE
|
||||
})
|
||||
|
||||
it('defaults sandbox.enabled to false in the persisted preference contract', () => {
|
||||
const prefs = UserPreferencesSchema.parse(DEFAULT_USER_PREFERENCES)
|
||||
expect(prefs.sandbox?.enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('round-trips sandbox.enabled when set to true', () => {
|
||||
const prefs = UserPreferencesSchema.parse({
|
||||
...DEFAULT_USER_PREFERENCES,
|
||||
sandbox: { enabled: true },
|
||||
})
|
||||
expect(prefs.sandbox).toEqual({ enabled: true })
|
||||
})
|
||||
|
||||
it('falls back ENV.SANDBOX.IMAGE to the default when SANDBOX_IMAGE is unset', async () => {
|
||||
delete process.env.SANDBOX_IMAGE
|
||||
vi.resetModules()
|
||||
const { ENV } = await import('@opencode-manager/shared/config/env')
|
||||
const { DEFAULTS } = await import('@opencode-manager/shared/config/defaults')
|
||||
expect(ENV.SANDBOX.IMAGE).toBe(DEFAULTS.SANDBOX.IMAGE)
|
||||
})
|
||||
|
||||
it('honors SANDBOX_IMAGE when set before module import', async () => {
|
||||
process.env.SANDBOX_IMAGE = 'node:22-alpine'
|
||||
vi.resetModules()
|
||||
const { ENV } = await import('@opencode-manager/shared/config/env')
|
||||
expect(ENV.SANDBOX.IMAGE).toBe('node:22-alpine')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'
|
||||
import { execSync } from 'child_process'
|
||||
import { mkdtempSync, existsSync, mkdirSync, writeFileSync } from 'fs'
|
||||
import { mkdtempSync, existsSync, mkdirSync, writeFileSync, symlinkSync, unlinkSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import path from 'path'
|
||||
import { rm } from 'fs/promises'
|
||||
@@ -20,6 +20,14 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
const opencodeServerManagerMock = vi.hoisted(() => ({
|
||||
isSandboxEnforced: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: opencodeServerManagerMock,
|
||||
}))
|
||||
|
||||
describe('buildRepoEnvForRepo', () => {
|
||||
it('includes OCM_GIT_REPO_ID and OCM_GIT_REPO_CWD when id is provided', async () => {
|
||||
const { buildRepoEnvForRepo } = await import('../../src/services/schedule-worktree')
|
||||
@@ -85,6 +93,10 @@ describe('ScheduleWorktreeManager', () => {
|
||||
authenticateMcp: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(false)
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
|
||||
tmpRoot = tmpDir
|
||||
@@ -335,6 +347,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.postJson = mockPost
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
@@ -366,6 +379,116 @@ describe('ScheduleWorktreeManager', () => {
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when the workspace directory is outside the sandboxed project roots', async () => {
|
||||
const workspaceId = 'ws-outside-456'
|
||||
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-outside-workspace')
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: outsideDirectory,
|
||||
branch: null,
|
||||
})
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 31, branch: null }
|
||||
const runId = 6
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-31-run-6'))
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
expect(deleteMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${workspaceId}`,
|
||||
}),
|
||||
)
|
||||
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
it('uses an OpenCode workspace outside the mount roots as-is when sandboxing is not enforced', async () => {
|
||||
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-off-workspace')
|
||||
const workspaceId = 'ws-off-123'
|
||||
execSync(`git -C "${baseRepoPath}" worktree add --detach "${outsideDirectory}" origin/main`, { env })
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: outsideDirectory,
|
||||
branch: null,
|
||||
})
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 32, branch: null }
|
||||
const runId = 1
|
||||
|
||||
try {
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
expect(ctx!.directory).toBe(outsideDirectory)
|
||||
|
||||
const branch = execSync(`git -C "${outsideDirectory}" rev-parse --abbrev-ref HEAD`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branch).toBe('schedule/32/run-1')
|
||||
} finally {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, outsideDirectory).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to raw git when an enforced workspace directory is a symlink escaping the project roots', async () => {
|
||||
const escapeTarget = path.join(path.dirname(tmpDir), 'ocm-escape-target')
|
||||
const escapeLink = path.join(tmpDir, 'ocm-escape-link')
|
||||
mkdirSync(escapeTarget, { recursive: true })
|
||||
symlinkSync(escapeTarget, escapeLink)
|
||||
|
||||
const workspaceId = 'ws-escape-999'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: escapeLink,
|
||||
branch: null,
|
||||
})
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 33, branch: null }
|
||||
const runId = 1
|
||||
|
||||
try {
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-33-run-1'))
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
expect(deleteMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${workspaceId}`,
|
||||
}),
|
||||
)
|
||||
} finally {
|
||||
unlinkSync(escapeLink)
|
||||
rmSync(escapeTarget, { recursive: true, force: true })
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, path.join(scheduleWorktreesRoot, 'job-33-run-1')).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when postJson rejects', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
|
||||
describe('executeCommand signal handling', () => {
|
||||
it('reports a signal-terminated child as a non-zero exit code when exit codes are ignored', async () => {
|
||||
const result = await executeCommand(['sh', '-c', 'kill -KILL $$'], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
})
|
||||
const structured = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
expect(structured.exitCode).not.toBe(0)
|
||||
expect(structured.stderr).toContain('Command terminated by signal SIGKILL')
|
||||
})
|
||||
|
||||
it('rejects a signal-terminated child when exit codes are enforced', async () => {
|
||||
await expect(executeCommand(['sh', '-c', 'kill -KILL $$'], { silent: true })).rejects.toThrow(
|
||||
'Command failed with signal SIGKILL',
|
||||
)
|
||||
})
|
||||
|
||||
it('resolves a zero exit code as success when exit codes are ignored', async () => {
|
||||
const result = await executeCommand(['sh', '-c', 'true'], { ignoreExitCode: true, silent: true })
|
||||
|
||||
expect(result).toEqual({ exitCode: 0, stdout: '', stderr: '' })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user