mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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
Reference in new issue
Block a user