mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(sandbox): add KVM-backed agent sandboxing via microsandbox (#338)
* feat(sandbox): add KVM-backed agent sandboxing via microsandbox * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * fix(sandbox): harden enforcement validation and backup handling * fix(sandbox): bound lifecycle queue and harden install/backup paths Bound the OpenCode supervisor lifecycle queue to one running plus one pending operation so repeated restarts cannot stack unbounded HTTP requests, while exempting stop() so shutdown is never dropped. Reject enforcement backups that carry no recoverable removed sections, matching the existing fail-closed handling of unparseable backups. Install OpenCode through a private mktemp staging directory instead of the predictable /tmp/opencode path. Use named path/os imports in the files added by this branch. * refactor(sandbox): remove OpenCode version allowlist gating under enforcement * fix(settings): use resolved opencode binary and verify installed version * refactor(sandbox): scope enforcement to agent bash tool only * fix(sandbox): plan bash against factory directory and attest runtime tmpfs; align permission reply API * fix(sandbox): pin neutral entrypoint and persist opencode upgrades across rebuilds * fix(sandbox): align canonical spec with msb 0.6.8 runtime defaults * feat(sandbox): show unwrapped sandboxed bash commands in message UI * refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands * feat(sandbox): route notifications through a host-side manager tool * feat(sandbox): route all assistant capabilities through the ocm tool Add an allow-listed request action to the generated ocm plugin so agents reach settings, assistant reload, repos, git-info, workspaces, and schedules through the tool instead of curling the internal API with a bearer token, which is impossible under sandboxing. Rewrite the curl-based skills to use the ocm request action and drop the apiBaseUrl plumbing. Remove the now-unread .opencode/internal-token file and the sandbox tmpfs mask that hid it; attestation now rejects any tmpfs other than the runtime /tmp mount. * fix(sidebar): wire new-session and new-schedule actions to every page AssistantRedirect never registered a listener for the sidebar's new-session event, so the desktop sidebar CTA on /assistant was a no-op; the Schedules pages had the same gap for new-schedule. Make useSidebarAction the single source of truth for action keys and event dispatch, and warn when an action is dispatched with no mounted handler so an unhandled CTA fails loudly instead of silently. Wire the missing listeners to the existing per-page handlers. * feat(sandbox): forward git credentials into the microVM and add sandbox guest image * feat(sandbox): add git credential forwarding toggle to settings
This commit is contained in:
1 parent
411fee52f3
commit
90a3c29c12
122 files changed
+16946
-883
No files matched your search
@@ -49,6 +49,21 @@ describe('entrypoint library wiring', () => {
|
||||
expect(warnIndex).toBeLessThan(chownIndex)
|
||||
})
|
||||
|
||||
it('grants node access to /dev/kvm before dropping privileges without aborting startup', () => {
|
||||
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(alignIndex, 'entrypoint must align the container user').toBeGreaterThan(-1)
|
||||
expect(grantCallIndex, 'entrypoint must call grant_kvm_access').toBeGreaterThan(-1)
|
||||
expect(grantCallIndex).toBeGreaterThan(alignIndex)
|
||||
expect(runuserIndex).toBeGreaterThan(grantCallIndex)
|
||||
const grantBlock = entrypoint.slice(grantCallIndex, grantCallIndex + 200)
|
||||
expect(grantBlock).toMatch(/WARNING: continuing without \/dev\/kvm access/)
|
||||
expect(grantBlock.slice(0, grantBlock.indexOf('fi'))).not.toMatch(/exit 1/)
|
||||
})
|
||||
|
||||
it('does not re-chown /app when ids change', () => {
|
||||
const entrypoint = read(entrypointPath)
|
||||
|
||||
@@ -66,6 +81,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)
|
||||
@@ -88,6 +152,22 @@ describe('workspace ownership configuration', () => {
|
||||
expect(compose).toMatch(/^volumes:\n(?:.*\n)*?\s+opencode-workspace:/m)
|
||||
})
|
||||
|
||||
it('mounts a dedicated named volume at /home/node/.opencode/bin with a top-level declaration', () => {
|
||||
const compose = read(composePath)
|
||||
expect(compose).toContain('opencode-bin:/home/node/.opencode/bin')
|
||||
expect(compose).toMatch(/^volumes:\n(?:.*\n)*?\s+opencode-bin:/m)
|
||||
})
|
||||
|
||||
it('persists only the opencode bin directory, not the whole ~/.opencode home', () => {
|
||||
const compose = read(composePath)
|
||||
expect(compose).not.toMatch(/:\/home\/node\/\.opencode(?:\s|$)/)
|
||||
})
|
||||
|
||||
it('lists the opencode-bin volume in the installation docs table', () => {
|
||||
const docs = read(join(repoRoot, 'docs/getting-started/installation.md'))
|
||||
expect(docs).toContain('| `opencode-bin` | `/home/node/.opencode/bin` |')
|
||||
})
|
||||
|
||||
it('keeps the docker docs compose snippet in sync with docker-compose.yml', () => {
|
||||
const compose = read(composePath)
|
||||
const docs = read(dockerDocsPath)
|
||||
@@ -124,6 +204,70 @@ describe('workspace ownership configuration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('docker lifecycle scripts', () => {
|
||||
it('keeps docker:down non-destructive and docker:reset destructive', () => {
|
||||
const pkg = read(join(repoRoot, 'package.json'))
|
||||
expect(pkg).toContain('"docker:down": "docker-compose down"')
|
||||
expect(pkg).toContain('"docker:reset": "docker-compose down -v"')
|
||||
})
|
||||
|
||||
it('documents the preserved-volume shutdown and the destructive reset', () => {
|
||||
const docs = read(dockerDocsPath)
|
||||
expect(docs).toContain('named volumes are preserved')
|
||||
expect(docs).toContain('docker-compose down -v')
|
||||
})
|
||||
|
||||
it('documents a targeted opencode-bin volume reset that preserves the other volumes', () => {
|
||||
const docs = read(join(repoRoot, 'docs/troubleshooting.md'))
|
||||
expect(docs).toContain('docker volume rm <project>_opencode-bin')
|
||||
expect(docs).toContain('without touching the workspace or database volumes')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox compose overlay', () => {
|
||||
const overlayPath = join(repoRoot, 'docker-compose.sandbox.yml')
|
||||
const overlay = read(overlayPath)
|
||||
const overlayDirectives = overlay
|
||||
.split('\n')
|
||||
.filter((line) => line.trim() !== '' && !line.trimStart().startsWith('#'))
|
||||
|
||||
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('"/dev/kvm:/dev/kvm"')
|
||||
expect(overlay).toContain('"/dev/net/tun:/dev/net/tun"')
|
||||
expect(overlay).toContain('- NET_ADMIN')
|
||||
expect(overlay).toContain('microsandbox-data:/home/node/.microsandbox')
|
||||
expect(overlay).toMatch(/^volumes:\n(?:.*\n)*?\s+microsandbox-data:/m)
|
||||
})
|
||||
|
||||
it('grants only the devices and capability msb needs, never full container privilege', () => {
|
||||
expect(overlayDirectives.join('\n')).not.toContain('privileged')
|
||||
})
|
||||
|
||||
it('keeps the sandbox overlay docs snippet in sync with docker-compose.sandbox.yml', () => {
|
||||
const docs = read(dockerDocsPath)
|
||||
const docsOverlay = [...docs.matchAll(/```yaml\n([\s\S]*?)\n```/g)]
|
||||
.map((match) => match[1]!)
|
||||
.find((block) => block.includes('microsandbox-data'))
|
||||
|
||||
expect(docsOverlay, 'docs must contain the sandbox overlay yaml block').toBeDefined()
|
||||
|
||||
const significantLines = (source: string[]) =>
|
||||
source.filter((line) => line.trim() !== '').map((line) => line.replace(/\s+$/, '')).join('\n')
|
||||
|
||||
expect(significantLines(docsOverlay!.split('\n'))).toBe(significantLines(overlayDirectives))
|
||||
})
|
||||
})
|
||||
|
||||
describe('named-volume migration recipe', () => {
|
||||
const runMigrationShell = (src: string, dst: string) => {
|
||||
const scriptDir = mkdtempSync(join(tmpdir(), 'migrate-script-'))
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
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 extractShellFunction = (name: string) => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const match = entrypoint.match(new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?\\n\\}`, 'm'))
|
||||
if (!match) throw new Error(`${name}() not found in docker-entrypoint.sh`)
|
||||
return match[0]
|
||||
}
|
||||
|
||||
const extractMinOpenCodeVersion = () => {
|
||||
const match = readFileSync(entrypointPath, 'utf-8').match(/^MIN_OPENCODE_VERSION="[^"]+"$/m)
|
||||
if (!match) throw new Error('MIN_OPENCODE_VERSION not found in docker-entrypoint.sh')
|
||||
return match[0]
|
||||
}
|
||||
|
||||
const installPrelude = () => [
|
||||
extractMinOpenCodeVersion(),
|
||||
extractShellFunction('version_gte'),
|
||||
extractShellFunction('read_opencode_version'),
|
||||
extractShellFunction('install_opencode'),
|
||||
extractShellFunction('reconcile_persisted_opencode'),
|
||||
].join('\n')
|
||||
|
||||
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"
|
||||
if [ "${'${OCM_STUB_RUNUSER_EXEC:-0}'}" = "1" ]; then
|
||||
while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do shift; done
|
||||
[ "$#" -gt 0 ] && shift
|
||||
OCM_EXECUTED_AS_NODE=1 "$@"
|
||||
exit $?
|
||||
fi
|
||||
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${extractShellFunction('grant_kvm_access')}\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 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,
|
||||
OCM_STUB_RUNUSER_EXEC: '1',
|
||||
HOME: homeDir,
|
||||
OPENCODE_BUNDLED_VERSION: '1.18.16',
|
||||
...env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stubInstallTools = () => {
|
||||
writeStub('curl', `echo "curl $*" >> "$OCM_STUB_LOG"
|
||||
out=""
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = "-o" ]; then out="$2"; fi
|
||||
shift
|
||||
done
|
||||
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' > "$(dirname "$out")/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(`${installPrelude()}\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/')
|
||||
expect(urls).not.toContain('/tmp/opencode.tar.gz')
|
||||
})
|
||||
|
||||
it('refuses to guess the pinned build when OPENCODE_BUNDLED_VERSION is unset', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '',
|
||||
})
|
||||
expect(res.status).not.toBe(0)
|
||||
expect(res.stderr).toContain('OPENCODE_BUNDLED_VERSION is not set')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('refuses to download an OPENCODE_BUNDLED_VERSION below the supported minimum', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '1.0.136',
|
||||
})
|
||||
expect(res.status).not.toBe(0)
|
||||
expect(res.stderr).toContain('below the minimum supported')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('refuses to download a malformed OPENCODE_BUNDLED_VERSION', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '1.18',
|
||||
})
|
||||
expect(res.status).not.toBe(0)
|
||||
expect(res.stderr).toContain('is not an X.Y.Z version')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('honors an OPENCODE_BUNDLED_VERSION override for the download URL', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${installPrelude()}\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(`${installPrelude()}\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(`${installPrelude()}\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/')
|
||||
})
|
||||
})
|
||||
|
||||
const writeBinary = (dir: string, version: string) => {
|
||||
const binPath = join(dir, 'opencode')
|
||||
writeFileSync(binPath, `#!/bin/bash\necho "opencode version ${version}"\n`)
|
||||
chmodSync(binPath, 0o755)
|
||||
return binPath
|
||||
}
|
||||
|
||||
const homeBinPath = () => join(stubDir, 'home/.opencode/bin/opencode')
|
||||
const bundledBinPath = () => join(stubDir, 'bundled/opencode')
|
||||
const bundledFirstPath = () => `${join(stubDir, 'home/.opencode/bin')}:${join(stubDir, 'bundled')}:${stubDir}:/usr/bin:/bin`
|
||||
|
||||
describe('persisted opencode reconciliation', () => {
|
||||
it('probes the persisted binary version through runuser, never directly', () => {
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeFileSync(homeBinPath(), `#!/bin/bash
|
||||
if [ -z "$OCM_EXECUTED_AS_NODE" ]; then
|
||||
echo "persisted binary executed outside runuser" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "opencode version 1.22.0"`)
|
||||
chmodSync(homeBinPath(), 0o755)
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(stubCalls()).toContain(`runuser -u node -- ${homeBinPath()} --version`)
|
||||
expect(res.stdout).toContain('retaining it')
|
||||
expect(existsSync(homeBinPath())).toBe(true)
|
||||
})
|
||||
|
||||
it('retains a persisted home binary equal to the bundled version', () => {
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'home/.opencode/bin'), '1.18.16')
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('retaining it')
|
||||
expect(existsSync(homeBinPath())).toBe(true)
|
||||
expect(res.stdout).toContain('OpenCode is installed (version: 1.18.16)')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('retains a persisted home binary newer than the bundled version', () => {
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'home/.opencode/bin'), '1.22.0')
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('retaining it')
|
||||
expect(existsSync(homeBinPath())).toBe(true)
|
||||
expect(res.stdout).toContain('OpenCode is installed (version: 1.22.0)')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('retains a persisted home binary older than the bundled version but above the minimum', () => {
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'home/.opencode/bin'), '1.10.0')
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('retaining it')
|
||||
expect(existsSync(homeBinPath())).toBe(true)
|
||||
expect(res.stdout).toContain('OpenCode is installed (version: 1.10.0)')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('replaces a persisted home binary below the minimum version with the bundled version', () => {
|
||||
stubInstallTools()
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'home/.opencode/bin'), '1.0.0')
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('retaining it')
|
||||
expect(res.stdout).toContain('below minimum required version')
|
||||
expect(res.stdout).toContain('Reinstalling bundled OpenCode version 1.18.16...')
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('removes a malformed persisted home binary and selects the bundled binary without downloading', () => {
|
||||
mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'home/.opencode/bin'), 'garbage')
|
||||
mkdirSync(join(stubDir, 'bundled'), { recursive: true })
|
||||
writeBinary(join(stubDir, 'bundled'), '1.18.16')
|
||||
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`, {
|
||||
PATH: bundledFirstPath(),
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('malformed or unversioned')
|
||||
expect(existsSync(homeBinPath())).toBe(false)
|
||||
expect(existsSync(bundledBinPath())).toBe(true)
|
||||
expect(res.stdout).toContain('OpenCode is installed (version: 1.18.16)')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user