diff --git a/.github/workflows/sandbox-image.yml b/.github/workflows/sandbox-image.yml new file mode 100644 index 00000000..06c7f1ba --- /dev/null +++ b/.github/workflows/sandbox-image.yml @@ -0,0 +1,92 @@ +name: Sandbox Image + +on: + release: + types: [published] + workflow_dispatch: + inputs: + image: + description: 'Fully qualified image name to push (registry/namespace/name)' + required: false + default: 'docker.io/cstechdev/ocm-sandbox' + playwright_version: + description: 'Playwright version providing the bundled Chromium' + required: false + default: '1.56.0' + +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Resolve build inputs + id: resolve + env: + REGISTRY_USERNAME: ${{ secrets.SANDBOX_REGISTRY_USERNAME }} + REGISTRY_TOKEN: ${{ secrets.SANDBOX_REGISTRY_TOKEN }} + run: | + IMAGE="${{ github.event.inputs.image }}" + [ -n "$IMAGE" ] || IMAGE="docker.io/cstechdev/ocm-sandbox" + PLAYWRIGHT_VERSION="${{ github.event.inputs.playwright_version }}" + [ -n "$PLAYWRIGHT_VERSION" ] || PLAYWRIGHT_VERSION="1.56.0" + REGISTRY="${IMAGE%%/*}" + case "$REGISTRY" in + *.*|*:*|localhost) ;; + *) echo "ERROR: image '$IMAGE' must be fully qualified with a registry host" >&2; exit 1 ;; + esac + if [ "$REGISTRY" != "ghcr.io" ] && { [ -z "$REGISTRY_USERNAME" ] || [ -z "$REGISTRY_TOKEN" ]; }; then + echo "ERROR: pushing to $REGISTRY requires the SANDBOX_REGISTRY_USERNAME and SANDBOX_REGISTRY_TOKEN repository secrets" >&2 + echo "GITHUB_TOKEN only authenticates against ghcr.io" >&2 + exit 1 + fi + echo "image=${IMAGE}" >> $GITHUB_OUTPUT + echo "registry=${REGISTRY}" >> $GITHUB_OUTPUT + echo "playwright=${PLAYWRIGHT_VERSION}" >> $GITHUB_OUTPUT + echo "Building ${IMAGE} on ${REGISTRY} with playwright=${PLAYWRIGHT_VERSION}" + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.resolve.outputs.image }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=semver,pattern={{major}} + type=raw,value=latest + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to registry + uses: docker/login-action@v3 + with: + registry: ${{ steps.resolve.outputs.registry }} + username: ${{ secrets.SANDBOX_REGISTRY_USERNAME || github.actor }} + password: ${{ secrets.SANDBOX_REGISTRY_TOKEN || secrets.GITHUB_TOKEN }} + + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: Dockerfile.sandbox + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: | + PLAYWRIGHT_VERSION=${{ steps.resolve.outputs.playwright }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Report digest + run: echo "Published ${{ steps.meta.outputs.tags }}" diff --git a/Dockerfile.sandbox b/Dockerfile.sandbox new file mode 100644 index 00000000..2fc69d6d --- /dev/null +++ b/Dockerfile.sandbox @@ -0,0 +1,38 @@ +# Guest image for the agent sandbox microVM (SANDBOX_IMAGE). +# +# node:24 is buildpack-deps based, so gcc/g++/make/ld/pkg-config, glib-2.0, +# git, ssh, python3 and curl are already present. This image only adds the +# GitHub CLI and a Playwright-managed Chromium. +FROM node:24 + +ARG PLAYWRIGHT_VERSION=1.56.0 +# Bump TOOLS_CACHEBUST (e.g. via --build-arg) to force a fresh gh/Playwright +# install without invalidating the rest of the build cache. +ARG TOOLS_CACHEBUST=0 + +# Shared browser location so the sandbox exec user (SANDBOX_EXEC_USER, default +# "node") can read browsers installed at build time by root. +ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +# Lets agent code `require("playwright")` from any working directory without a +# project-local install. Only a resolution fallback; local node_modules wins. +ENV NODE_PATH=/usr/local/lib/node_modules + +RUN echo "Installing gh (cachebust=${TOOLS_CACHEBUST})" && \ + apt-get update && \ + apt-get install -y --no-install-recommends ca-certificates curl && \ + curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \ + -o /usr/share/keyrings/githubcli-archive-keyring.gpg && \ + chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg && \ + echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \ + > /etc/apt/sources.list.d/github-cli.list && \ + apt-get update && \ + apt-get install -y --no-install-recommends gh && \ + rm -rf /var/lib/apt/lists/* && \ + gh --version + +RUN echo "Installing playwright=${PLAYWRIGHT_VERSION} chromium (cachebust=${TOOLS_CACHEBUST})" && \ + npm install -g "playwright@${PLAYWRIGHT_VERSION}" && \ + npx --yes "playwright@${PLAYWRIGHT_VERSION}" install --with-deps chromium && \ + chmod -R a+rX "${PLAYWRIGHT_BROWSERS_PATH}" && \ + rm -rf /var/lib/apt/lists/* /root/.npm && \ + npx --yes "playwright@${PLAYWRIGHT_VERSION}" --version diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index 31c22ff0..57322872 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -24,6 +24,8 @@ interface RepoRow { const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId' +const REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY = 'sandboxGitCredentials' + function rowToRepo(row: RepoRow): Repo { const fullPath = row.source_path || path.join(getReposPath(), row.local_path) @@ -82,6 +84,16 @@ export function setRepoGitCredentialId(db: Database, repoId: number, credentialI setRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY, credentialId) } +export function getRepoSandboxGitCredentials(db: Database, repoId: number): boolean | null { + const value = getRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY) + if (value === null) return null + return value === 'true' +} + +export function setRepoSandboxGitCredentials(db: Database, repoId: number, allowed: boolean | null): void { + setRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY, allowed === null ? null : String(allowed)) +} + export function getRepoByDirectory(db: Database, directory: string): Repo | null { const resolvedDirectory = path.resolve(directory) const repos = listRepos(db) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index ce5dc6d9..175ab029 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -398,33 +398,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const sandboxChanged = sandboxPreferenceChanged(currentSettings.preferences.sandbox, validated.preferences.sandbox) - if (sandboxChanged) { - logger.info('Sandbox preference changed, marking OpenCode server restart as pending') - opencodeServerManager.markRestartPending() - } - - let serverRestarted = false - const credentialsChanged = validated.preferences.gitCredentials !== undefined && JSON.stringify(currentSettings.preferences.gitCredentials || []) !== JSON.stringify(validated.preferences.gitCredentials) const identityChanged = validated.preferences.gitIdentity !== undefined && JSON.stringify(currentSettings.preferences.gitIdentity || {}) !== JSON.stringify(validated.preferences.gitIdentity) - let reloadError: string | undefined - if (credentialsChanged || identityChanged) { - const changeType = [credentialsChanged && 'credentials', identityChanged && 'identity'].filter(Boolean).join(' and ') - logger.info(`Git ${changeType} changed, reloading OpenCode configuration`) - try { - await reloadOpenCodeConfig(openCodeSupervisor) - serverRestarted = true - } catch (error) { - logger.warn('Failed to reload OpenCode config after git settings change:', error) - reloadError = error instanceof Error ? error.message : 'Unknown error' - } + const restartReasons = [ + sandboxChanged && 'sandbox', + credentialsChanged && 'git credentials', + identityChanged && 'git identity', + ].filter((reason): reason is string => typeof reason === 'string') + + const restartRequired = restartReasons.length > 0 + if (restartRequired) { + logger.info(`${restartReasons.join(', ')} changed, marking OpenCode server restart as pending`) + opencodeServerManager.markRestartPending() } - return c.json({ ...settings, serverRestarted, reloadError, ...(sandboxChanged ? { restartRequired: true } : {}) }) + return c.json(restartRequired ? { ...settings, restartRequired: true } : settings) } catch (error) { logger.error('Failed to update settings:', error) if (error instanceof Error && error.message.startsWith('Invalid SSH key')) { diff --git a/backend/src/services/credential-provider.ts b/backend/src/services/credential-provider.ts index eed9a41e..a5bd26b6 100644 --- a/backend/src/services/credential-provider.ts +++ b/backend/src/services/credential-provider.ts @@ -1,5 +1,5 @@ import type { Database } from 'bun:sqlite' -import type { GitCredential } from '@opencode-manager/shared' +import type { GitCredential, Repo } from '@opencode-manager/shared' import { SettingsService } from './settings' import { findPatCredentialForHost, @@ -8,7 +8,14 @@ import { findGitHubCredential, type ResolvedGitCredential, } from '../utils/git-auth' -import { getRepoByDirectory, getRepoGitCredentialId } from '../db/queries' +import { limitForwardedGitConfigs, SANDBOX_MAX_FORWARDED_GIT_CONFIGS } from './sandbox/shell-shim' +import { logger } from '../utils/logger' +import { + getRepoByDirectory, + getRepoGitCredentialId, + getRepoSandboxGitCredentials, + listRepos, +} from '../db/queries' interface CredentialResolutionOptions { cwd?: string @@ -49,8 +56,42 @@ export class CredentialProvider { return this.getGitCredentials().filter((cred) => cred.type === 'ssh' && cred.sshPrivateKeyEncrypted) } - getGitEnv(): Record { - return createGitEnv(this.getGitCredentials()) + getGitEnv(options: CredentialResolutionOptions = {}): Record { + const credentials = this.getGitCredentials() + return createGitEnv(credentials, this.getSelectedCredential(options, credentials)) + } + + isSandboxGitCredentialsAllowed(options: CredentialResolutionOptions = {}): boolean { + const repo = this.resolveRepo(options) + if (repo) { + const repoOverride = getRepoSandboxGitCredentials(this.database, repo.id) + if (repoOverride !== null) return repoOverride + } + + return this.settingsService.getSettings('default').preferences.sandbox?.gitCredentials === true + } + + getSandboxGitEnv(options: CredentialResolutionOptions = {}): Record { + if (!this.isSandboxGitCredentialsAllowed(options)) return {} + + const gitEnv = this.getGitEnv(options) + if (gitEnv.GIT_CONFIG_COUNT === '0') return {} + + const { env, dropped } = limitForwardedGitConfigs(gitEnv) + if (dropped > 0) { + logger.warn( + `Sandbox git credentials exceed the forwarding limit of ${SANDBOX_MAX_FORWARDED_GIT_CONFIGS} hosts; ${dropped} host(s) will not authenticate inside the microVM`, + ) + } + + return { ...env, ...this.getGhCliEnv(options) } + } + + private resolveRepo(options: CredentialResolutionOptions): Repo | null { + if (options.repoId !== undefined) { + return listRepos(this.database).find((repo) => repo.id === options.repoId) ?? null + } + return options.cwd ? getRepoByDirectory(this.database, options.cwd) : null } getGhCliEnv(options: CredentialResolutionOptions = {}): Record { @@ -76,10 +117,10 @@ export class CredentialProvider { } private getRepoCredential(options: CredentialResolutionOptions, credentials: GitCredential[]): GitCredential | null { - const repoId = options.repoId ?? (options.cwd ? getRepoByDirectory(this.database, options.cwd)?.id : undefined) - if (!repoId) return null + const repo = this.resolveRepo(options) + if (!repo) return null - const credentialId = getRepoGitCredentialId(this.database, repoId) + const credentialId = getRepoGitCredentialId(this.database, repo.id) return credentials.find((credential) => credential.id === credentialId) ?? null } diff --git a/backend/src/services/opencode-sandbox-plugin.ts b/backend/src/services/opencode-sandbox-plugin.ts index 4aaba5ce..a735905a 100644 --- a/backend/src/services/opencode-sandbox-plugin.ts +++ b/backend/src/services/opencode-sandbox-plugin.ts @@ -1,5 +1,9 @@ import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command' -import { SANDBOX_SHELL_ENV_HOST_SHELL, SANDBOX_SHELL_ENV_WORKDIR } from './sandbox/shell-shim' +import { + SANDBOX_FORWARDED_ENV_NAMES, + SANDBOX_SHELL_ENV_HOST_SHELL, + SANDBOX_SHELL_ENV_WORKDIR, +} from './sandbox/shell-shim' export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs() @@ -11,6 +15,7 @@ var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS} var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)} var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)} var ENV_HOST_SHELL = ${JSON.stringify(SANDBOX_SHELL_ENV_HOST_SHELL)} +var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)} function isEnforced() { return process.env.OCM_SANDBOX_ENFORCED === 'true' @@ -78,7 +83,7 @@ async function planSandboxShell(cwd) { if (plan === null || typeof plan !== 'object' || plan.mode !== 'sandbox' || typeof plan.workdir !== 'string' || plan.workdir.length === 0) { throw unavailable(plan !== null && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response') } - return plan.workdir + return plan } export default async function () { @@ -103,8 +108,15 @@ export default async function () { if (!existsSync(SHELL_SHIM_PATH)) { throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH) } - var workdir = await planSandboxShell(input.cwd) - if (!lockAccessor(output.env, ENV_WORKDIR, workdir)) { + var plan = await planSandboxShell(input.cwd) + if (plan.env !== null && typeof plan.env === 'object') { + for (var name of FORWARDED_ENV_NAMES) { + if (typeof plan.env[name] === 'string') { + output.env[name] = plan.env[name] + } + } + } + if (!lockAccessor(output.env, ENV_WORKDIR, plan.workdir)) { throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host') } }, diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index ad9c7b6e..2e43f8f9 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -6,6 +6,7 @@ import { executeCommand } from '../../utils/process' import { mkdirSafe } from '../../utils/fs-safe' import { logger } from '../../utils/logger' import { SettingsService } from '../settings' +import { CredentialProvider } from '../credential-provider' import { detectSandboxCapability } from './capability' import { WORKSPACE_SANDBOX_NAME, @@ -31,7 +32,7 @@ const SANDBOX_RUNTIME_TMPFS_GUEST = path.resolve('/tmp') export type SandboxShellPlan = | { mode: 'host' } - | { mode: 'sandbox'; workdir: string } + | { mode: 'sandbox'; workdir: string; env?: Record } | { mode: 'blocked'; reason: string } export type SandboxStatus = { @@ -648,7 +649,10 @@ export class SandboxRuntimeService { } try { await ensureWorkspaceSandbox() - return { mode: 'sandbox', workdir: workDirectory } + const env = new CredentialProvider(this.db).getSandboxGitEnv({ cwd: directory }) + return Object.keys(env).length > 0 + ? { mode: 'sandbox', workdir: workDirectory, env } + : { mode: 'sandbox', workdir: workDirectory } } catch (error) { logger.error('Failed to prepare the workspace sandbox', error) return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) } diff --git a/backend/src/services/sandbox/shell-shim.ts b/backend/src/services/sandbox/shell-shim.ts index 0f55e964..ae8f764b 100644 --- a/backend/src/services/sandbox/shell-shim.ts +++ b/backend/src/services/sandbox/shell-shim.ts @@ -17,6 +17,58 @@ export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR' export const SANDBOX_SHELL_ENV_HOST_SHELL = 'OCM_SANDBOX_HOST_SHELL' +/** + * Upper bound on `http..extraheader` pairs forwarded into the microVM. + * The shim enumerates a fixed set of variable names rather than expanding + * `GIT_CONFIG_KEY_$i` indirectly, which would require `eval` on values holding + * credentials. Credentials are configured per host, so this bounds the number + * of distinct git hosts a sandboxed command can authenticate against. + */ +export const SANDBOX_MAX_FORWARDED_GIT_CONFIGS = 16 + +/** + * Variables the shim copies from its own environment into the microVM with + * `msb exec -e`. The guest environment is otherwise empty, so anything absent + * from this list never reaches a sandboxed command. + */ +export const SANDBOX_FORWARDED_ENV_NAMES: readonly string[] = [ + 'GIT_TERMINAL_PROMPT', + 'GIT_CONFIG_COUNT', + ...Array.from({ length: SANDBOX_MAX_FORWARDED_GIT_CONFIGS }, (_, index) => [ + `GIT_CONFIG_KEY_${index}`, + `GIT_CONFIG_VALUE_${index}`, + ]).flat(), + 'GIT_AUTHOR_NAME', + 'GIT_AUTHOR_EMAIL', + 'GIT_COMMITTER_NAME', + 'GIT_COMMITTER_EMAIL', + 'GH_TOKEN', + 'GITHUB_TOKEN', +] + +/** + * Drops `http..extraheader` pairs the shim cannot forward, so the guest + * never sees a `GIT_CONFIG_COUNT` that overstates the pairs actually present. + * A count larger than the pairs in the environment makes git fail outright. + */ +export function limitForwardedGitConfigs(env: Record): { + env: Record + dropped: number +} { + const count = Number(env.GIT_CONFIG_COUNT ?? '0') + if (!Number.isFinite(count) || count <= SANDBOX_MAX_FORWARDED_GIT_CONFIGS) { + return { env, dropped: 0 } + } + + const limited: Record = { ...env, GIT_CONFIG_COUNT: String(SANDBOX_MAX_FORWARDED_GIT_CONFIGS) } + for (let index = SANDBOX_MAX_FORWARDED_GIT_CONFIGS; index < count; index++) { + delete limited[`GIT_CONFIG_KEY_${index}`] + delete limited[`GIT_CONFIG_VALUE_${index}`] + } + + return { env: limited, dropped: count - SANDBOX_MAX_FORWARDED_GIT_CONFIGS } +} + export function sandboxShellShimPath(configHome: string): string { return path.join(configHome, 'ocm', SANDBOX_SHELL_FILENAME) } @@ -38,7 +90,7 @@ export function resolveShimHostShell(): string { export function buildSandboxShellShimScript(): string { const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000) - const execPrefix = [ + const execArgs = [ quoteForShell(sandboxExecutablePath()), 'exec', WORKSPACE_SANDBOX_NAME, @@ -50,13 +102,24 @@ export function buildSandboxShellShimScript(): string { `"$${SANDBOX_SHELL_ENV_WORKDIR}"`, '--timeout', `${timeoutSeconds}s`, - '--', - 'sh', - '"$@"', ].join(' ') + const forwardEnv = SANDBOX_FORWARDED_ENV_NAMES.map( + (name) => ` if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`, + ).join('\n') return `#!/bin/sh if [ -n "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then - exec ${execPrefix} + ocm_argc=$# + set -- "$@" ${execArgs} +${forwardEnv} + set -- "$@" -- sh + ocm_i=0 + while [ "$ocm_i" -lt "$ocm_argc" ]; do + ocm_arg=$1 + shift + set -- "$@" "$ocm_arg" + ocm_i=$((ocm_i + 1)) + done + exec "$@" fi OCM_SANDBOX_DEFAULT_SHELL=${quoteForShell(resolveShimHostShell())} exec "\${${SANDBOX_SHELL_ENV_HOST_SHELL}:-$OCM_SANDBOX_DEFAULT_SHELL}" "$@" diff --git a/backend/src/utils/git-auth.ts b/backend/src/utils/git-auth.ts index a7461a0e..e2909b2f 100644 --- a/backend/src/utils/git-auth.ts +++ b/backend/src/utils/git-auth.ts @@ -29,32 +29,49 @@ export function normalizeHost(host: string): string | null { return url ? `${url.protocol}//${url.host}/` : null } -export function createGitEnv(credentials: GitCredential[]): Record { +export function createExtraHeaderEnv( + configIndex: number, + normalizedHost: string, + username: string, + token: string +): Record { + const basicAuth = Buffer.from(`${username}:${token}`, 'utf8').toString('base64') + return { + [`GIT_CONFIG_KEY_${configIndex}`]: `http.${normalizedHost}.extraheader`, + [`GIT_CONFIG_VALUE_${configIndex}`]: `AUTHORIZATION: basic ${basicAuth}`, + } +} + +export function createGitEnv( + credentials: GitCredential[], + preferred?: GitCredential | null +): Record { const env: Record = { GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_COUNT: '0' } - if (!credentials || credentials.length === 0) { - return env - } + const credentialByHost = new Map() - let configIndex = 0 - - for (const cred of credentials) { + for (const cred of [...(preferred ? [preferred] : []), ...(credentials ?? [])]) { if (!cred.host || !cred.token) { continue } const host = normalizeHost(cred.host) - if (!host) { + if (!host || credentialByHost.has(host)) { continue } - const username = cred.username || getDefaultUsername(host) - const basicAuth = Buffer.from(`${username}:${cred.token}`, 'utf8').toString('base64') + credentialByHost.set(host, cred) + } - env[`GIT_CONFIG_KEY_${configIndex}`] = `http.${host}.extraheader` - env[`GIT_CONFIG_VALUE_${configIndex}`] = `AUTHORIZATION: basic ${basicAuth}` + let configIndex = 0 + + for (const [host, cred] of credentialByHost) { + Object.assign( + env, + createExtraHeaderEnv(configIndex, host, cred.username || getDefaultUsername(host), cred.token as string) + ) configIndex++ } diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 3e237991..763a295b 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1690,7 +1690,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { }) }) - describe('PATCH / - sandbox preference restart pending', () => { + describe('PATCH / - restart pending', () => { it('marks the OpenCode server restart pending when sandbox.enabled changes', async () => { mockGetSettings.mockReturnValue({ preferences: { sandbox: { enabled: false } }, @@ -1753,6 +1753,78 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(res.status).toBe(200) expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled() }) + + it('requires a restart when git credentials change instead of reloading config', async () => { + const credential = { id: 'cred-1', name: 'gh', host: 'github.com', type: 'pat', token: 'new-token' } + mockGetSettings.mockReturnValue({ + preferences: { gitCredentials: [{ ...credential, token: 'old-token' }] }, + updatedAt: 1, + }) + mockUpdateSettings.mockReturnValue({ + preferences: { gitCredentials: [credential] }, + updatedAt: 2, + }) + + const req = new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { gitCredentials: [credential] } }), + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.restartRequired).toBe(true) + expect(opencodeServerManager.markRestartPending).toHaveBeenCalledTimes(1) + expect(mockReloadConfig).not.toHaveBeenCalled() + }) + + it('requires a restart when the git identity changes', async () => { + mockGetSettings.mockReturnValue({ + preferences: { gitIdentity: { name: 'Old', email: 'old@example.com' } }, + updatedAt: 1, + }) + mockUpdateSettings.mockReturnValue({ + preferences: { gitIdentity: { name: 'New', email: 'new@example.com' } }, + updatedAt: 2, + }) + + const req = new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { gitIdentity: { name: 'New', email: 'new@example.com' } } }), + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.restartRequired).toBe(true) + expect(opencodeServerManager.markRestartPending).toHaveBeenCalledTimes(1) + }) + + it('does not require a restart when git credentials are resubmitted unchanged', async () => { + const credential = { id: 'cred-1', name: 'gh', host: 'github.com', type: 'pat', token: 'same-token' } + mockGetSettings.mockReturnValue({ + preferences: { gitCredentials: [credential] }, + updatedAt: 1, + }) + mockUpdateSettings.mockReturnValue({ + preferences: { gitCredentials: [credential] }, + updatedAt: 1, + }) + + const req = new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { gitCredentials: [credential] } }), + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.restartRequired).toBeUndefined() + expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled() + }) }) describe('DELETE / - sandbox preference restart pending', () => { diff --git a/backend/test/services/credential-provider.test.ts b/backend/test/services/credential-provider.test.ts index 1317ef81..3c9ec865 100644 --- a/backend/test/services/credential-provider.test.ts +++ b/backend/test/services/credential-provider.test.ts @@ -4,7 +4,8 @@ import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { SettingsService } from '../../src/services/settings' import { CredentialProvider } from '../../src/services/credential-provider' -import { createRepo, setRepoGitCredentialId } from '../../src/db/queries' +import { createRepo, setRepoGitCredentialId, setRepoSandboxGitCredentials } from '../../src/db/queries' +import { SANDBOX_MAX_FORWARDED_GIT_CONFIGS } from '../../src/services/sandbox/shell-shim' import type { GitCredential } from '@opencode-manager/shared' function createPatCredential(name: string, host: string, token: string, username?: string, id?: string): GitCredential { @@ -178,4 +179,122 @@ describe('CredentialProvider', () => { expect(provider.getGitCredentials()).toHaveLength(2) }) }) + + describe('sandbox git credentials', () => { + function createGithubRepo() { + return createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + } + + beforeEach(() => { + settingsService.updateSettings({ + gitCredentials: [ + createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id'), + createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id'), + ], + defaultGitCredentialId: 'first-id', + }) + }) + + it('withholds credentials from the sandbox by default', () => { + const repo = createGithubRepo() + expect(provider.isSandboxGitCredentialsAllowed({ cwd: repo.fullPath })).toBe(false) + expect(provider.getSandboxGitEnv({ cwd: repo.fullPath })).toEqual({}) + }) + + it('emits one extraheader per configured host when the global toggle is on', () => { + settingsService.updateSettings({ + gitCredentials: [ + createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id'), + createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id'), + createPatCredential('lab', 'gitlab.com', 'lab-token', undefined, 'lab-id'), + ], + defaultGitCredentialId: 'first-id', + sandbox: { enabled: true, gitCredentials: true }, + }) + const repo = createGithubRepo() + + const env = provider.getSandboxGitEnv({ cwd: repo.fullPath }) + + expect(env.GIT_CONFIG_COUNT).toBe('2') + expect(env.GIT_CONFIG_KEY_0).toBe('http.https://github.com/.extraheader') + expect(env.GIT_CONFIG_VALUE_0).toBe( + `AUTHORIZATION: basic ${Buffer.from('x-access-token:first-token', 'utf8').toString('base64')}` + ) + expect(env.GIT_CONFIG_KEY_1).toBe('http.https://gitlab.com/.extraheader') + expect(env.GH_TOKEN).toBe('first-token') + }) + + it('caps forwarded hosts so GIT_CONFIG_COUNT never overstates the pairs present', () => { + const overLimit = SANDBOX_MAX_FORWARDED_GIT_CONFIGS + 3 + settingsService.updateSettings({ + gitCredentials: Array.from({ length: overLimit }, (_, index) => + createPatCredential(`host-${index}`, `host${index}.example.com`, `token-${index}`, undefined, `id-${index}`) + ), + sandbox: { enabled: true, gitCredentials: true }, + }) + const repo = createGithubRepo() + + const env = provider.getSandboxGitEnv({ cwd: repo.fullPath }) + + expect(env.GIT_CONFIG_COUNT).toBe(String(SANDBOX_MAX_FORWARDED_GIT_CONFIGS)) + expect(env[`GIT_CONFIG_KEY_${SANDBOX_MAX_FORWARDED_GIT_CONFIGS - 1}`]).toBeDefined() + expect(env[`GIT_CONFIG_KEY_${SANDBOX_MAX_FORWARDED_GIT_CONFIGS}`]).toBeUndefined() + expect(env[`GIT_CONFIG_VALUE_${SANDBOX_MAX_FORWARDED_GIT_CONFIGS}`]).toBeUndefined() + }) + + it('withholds credentials when none of the configured credentials carry a token', () => { + settingsService.updateSettings({ + gitCredentials: [createSshCredential('ssh-only', 'github.com', 'encrypted')], + sandbox: { enabled: true, gitCredentials: true }, + }) + const repo = createGithubRepo() + + expect(provider.getSandboxGitEnv({ cwd: repo.fullPath })).toEqual({}) + }) + + it('honors the repo-bound credential over the global default', () => { + settingsService.updateSettings({ sandbox: { enabled: true, gitCredentials: true } }) + const repo = createGithubRepo() + setRepoGitCredentialId(db, repo.id, 'second-id') + + const env = provider.getSandboxGitEnv({ cwd: repo.fullPath }) + + expect(env.GIT_CONFIG_VALUE_0).toBe( + `AUTHORIZATION: basic ${Buffer.from('x-access-token:second-token', 'utf8').toString('base64')}` + ) + }) + + it('lets a per-repo override withhold credentials while the global toggle is on', () => { + settingsService.updateSettings({ sandbox: { enabled: true, gitCredentials: true } }) + const repo = createGithubRepo() + setRepoSandboxGitCredentials(db, repo.id, false) + + expect(provider.isSandboxGitCredentialsAllowed({ cwd: repo.fullPath })).toBe(false) + expect(provider.getSandboxGitEnv({ cwd: repo.fullPath })).toEqual({}) + }) + + it('lets a per-repo override grant credentials while the global toggle is off', () => { + const repo = createGithubRepo() + setRepoSandboxGitCredentials(db, repo.id, true) + + expect(provider.isSandboxGitCredentialsAllowed({ cwd: repo.fullPath })).toBe(true) + expect(provider.getSandboxGitEnv({ cwd: repo.fullPath }).GIT_CONFIG_COUNT).toBe('1') + }) + + it('falls back to the global toggle for a directory that belongs to no known repo', () => { + settingsService.updateSettings({ sandbox: { enabled: true, gitCredentials: true } }) + createGithubRepo() + + const env = provider.getSandboxGitEnv({ cwd: '/somewhere/unmanaged' }) + + expect(env.GIT_CONFIG_COUNT).toBe('1') + expect(env.GIT_CONFIG_KEY_0).toBe('http.https://github.com/.extraheader') + }) + }) }) diff --git a/backend/test/services/sandbox/shell-shim.test.ts b/backend/test/services/sandbox/shell-shim.test.ts index 26bf15b9..bdd4cb13 100644 --- a/backend/test/services/sandbox/shell-shim.test.ts +++ b/backend/test/services/sandbox/shell-shim.test.ts @@ -6,6 +6,7 @@ import path from 'node:path' import { getReposPath } from '@opencode-manager/shared/config/env' import { WORKSPACE_SANDBOX_NAME } from '../../../src/services/sandbox/command' import { + SANDBOX_FORWARDED_ENV_NAMES, SANDBOX_SHELL_ENV_HOST_SHELL, SANDBOX_SHELL_ENV_WORKDIR, } from '../../../src/services/sandbox/shell-shim' @@ -87,6 +88,64 @@ describe('sandbox shell shim', () => { } }) + it('forwards only the allow-listed credential env into the guest as -e pairs, ahead of the command', async () => { + const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-msb-')) + const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-')) + const msbPath = path.join(fakeBin, 'msb') + const captureFile = path.join(fakeBin, 'argv.txt') + writeArgvCapturingFakeMsb(msbPath, captureFile) + const originalMsbPath = process.env.MSB_PATH + process.env.MSB_PATH = msbPath + try { + vi.resetModules() + const shimMod = await import('../../../src/services/sandbox/shell-shim') + const commandMod = await import('../../../src/services/sandbox/command') + commandMod.overrideSandboxExecutableTrustValidator(() => true) + const shimPath = await shimMod.ensureSandboxShellShim(configHome) + + const directory = path.join(getReposPath(), 'foo') + const extraheaderValue = 'AUTHORIZATION: basic eDphYmMgZGVm' + const result = spawnSync(shimPath, ['-c', 'echo -e sentinel'], { + encoding: 'utf8', + env: { + ...process.env, + [SANDBOX_SHELL_ENV_WORKDIR]: directory, + GIT_CONFIG_COUNT: '1', + GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', + GIT_CONFIG_VALUE_0: extraheaderValue, + OCM_INTERNAL_TOKEN: 'must-not-be-forwarded', + }, + }) + expect(result.status).toBe(0) + + const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '') + + expect(argv).toContain('-e') + expect(argv).toContain('GIT_CONFIG_COUNT=1') + expect(argv).toContain(`GIT_CONFIG_VALUE_0=${extraheaderValue}`) + + const separatorIndex = argv.indexOf('--') + expect(argv.slice(separatorIndex)).toEqual(['--', 'sh', '-c', 'echo -e sentinel']) + expect(argv.slice(0, separatorIndex).filter((element) => element === '-e')).toHaveLength(3) + + expect(argv.some((element) => element.startsWith('OCM_INTERNAL_TOKEN='))).toBe(false) + for (const element of argv) { + if (!element.includes('=') || element === '--') continue + const name = element.slice(0, element.indexOf('=')) + if (!SANDBOX_FORWARDED_ENV_NAMES.includes(name as never)) continue + expect(SANDBOX_FORWARDED_ENV_NAMES).toContain(name) + } + } finally { + if (originalMsbPath === undefined) { + delete process.env.MSB_PATH + } else { + process.env.MSB_PATH = originalMsbPath + } + rmSync(fakeBin, { recursive: true, force: true }) + rmSync(configHome, { recursive: true, force: true }) + } + }) + it('passes MSB_PATH and the resolved exec identity to msb as single literal arguments', async () => { const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-hostile-')) const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-')) diff --git a/backend/test/utils/git-auth.test.ts b/backend/test/utils/git-auth.test.ts index 613ccece..e8e02bc4 100644 --- a/backend/test/utils/git-auth.test.ts +++ b/backend/test/utils/git-auth.test.ts @@ -237,6 +237,37 @@ describe('createGitEnv', () => { expect(env.GIT_CONFIG_COUNT).toBe('1') expect(env.GIT_CONFIG_KEY_0).toBe('http.https://github.com/.extraheader') }) + + it('emits a single extraheader per host so git cannot send competing Authorization headers', () => { + const env = createGitEnv([ + { name: 'first', host: 'github.com', type: 'pat', token: 'first-token' }, + { name: 'second', host: 'https://github.com/', type: 'pat', token: 'second-token' }, + ]) + + expect(env.GIT_CONFIG_COUNT).toBe('1') + expect(env.GIT_CONFIG_KEY_0).toBe('http.https://github.com/.extraheader') + expect(env.GIT_CONFIG_VALUE_0).toBe( + `AUTHORIZATION: basic ${Buffer.from('x-access-token:first-token', 'utf8').toString('base64')}` + ) + expect(env.GIT_CONFIG_KEY_1).toBeUndefined() + }) + + it('lets the preferred credential win its host over other credentials for that host', () => { + const env = createGitEnv( + [ + { name: 'first', host: 'github.com', type: 'pat', token: 'first-token' }, + { name: 'gitlab', host: 'gitlab.com', type: 'pat', token: 'gitlab-token' }, + ], + { name: 'repo-bound', host: 'github.com', type: 'pat', token: 'repo-bound-token' } + ) + + expect(env.GIT_CONFIG_COUNT).toBe('2') + expect(env.GIT_CONFIG_KEY_0).toBe('http.https://github.com/.extraheader') + expect(env.GIT_CONFIG_VALUE_0).toBe( + `AUTHORIZATION: basic ${Buffer.from('x-access-token:repo-bound-token', 'utf8').toString('base64')}` + ) + expect(env.GIT_CONFIG_KEY_1).toBe('http.https://gitlab.com/.extraheader') + }) }) describe('createGhCliEnv', () => { diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.yml index 114981e6..8a72d1ec 100644 --- a/docker-compose.sandbox.yml +++ b/docker-compose.sandbox.yml @@ -16,7 +16,7 @@ services: cap_add: - NET_ADMIN environment: - - SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24} + - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox:latest} - SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G} - SANDBOX_CPUS=${SANDBOX_CPUS:-2} - SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}} diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index df007645..bce015e4 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -328,7 +328,7 @@ services: devices: - "/dev/kvm:/dev/kvm" environment: - - SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24} + - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox:latest} - SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G} - SANDBOX_CPUS=${SANDBOX_CPUS:-2} - SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}} diff --git a/docs/configuration/environment.md b/docs/configuration/environment.md index cd177721..2553bef4 100644 --- a/docs/configuration/environment.md +++ b/docs/configuration/environment.md @@ -116,7 +116,7 @@ Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandb |----------|-------------|---------| | `MSB_PATH` | Path to the `msb` executable | `msb` | | `MSB_LIBKRUNFW_PATH` | Path to the `libkrunfw` firmware library used by `msb` (set in the container image) | `/opt/microsandbox/lib/libkrunfw.so` | -| `SANDBOX_IMAGE` | OCI image the microVM boots from | `node:24` | +| `SANDBOX_IMAGE` | OCI image the microVM boots from. See [Sandbox Guest Image](../features/sandboxing.md#sandbox-guest-image) for what the default ships and how to build your own | `docker.io/cstechdev/ocm-sandbox:latest` | | `SANDBOX_MEMORY` | MicroVM memory (e.g. `4G`) | `4G` | | `SANDBOX_CPUS` | MicroVM CPU count | `2` | | `SANDBOX_EXEC_USER` | Guest identity sandboxed commands run as: a numeric `uid`, a numeric `uid:gid`, or a guest username. A numeric uid must match the Manager's effective uid (`PUID`); the compose overlay defaults it to `${PUID:-1000}`. A guest username is resolved to the Manager's effective `uid:gid` so writes to the mounted project roots always succeed. When a configured numeric identity cannot write the workspace, enforcement is reported unavailable | `${PUID:-1000}` via the overlay, otherwise `node` | diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index a2c4833e..13ea4845 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -15,7 +15,7 @@ The microVM sees repositories through bind mounts at the same paths used by the | Chat session `bash` tool calls | Yes | | Scheduled run `bash` tool calls | Yes | | Subagent `bash` tool calls | Yes | -| WebUI `!command` shell mode (`POST /session/:id/shell`) | No; normal OpenCode behavior | +| WebUI `!command` shell mode (`POST /session/:id/shell`) | Yes; it carries a tool call id like the `bash` tool, so it is planned and routed into the microVM. It is not badged in the UI because the surface fires no `tool.execute.after` hook | | Slash-command shell templates (`` !`cmd` ``, `POST /session/:id/command`) | No; normal OpenCode behavior | | PTY terminals (`POST /pty`, `/pty/:id/connect`) | No; normal OpenCode behavior | | OpenCode file tools | No | @@ -45,9 +45,11 @@ Configured extensions execute with OpenCode's normal host-process privileges. Th ## Other Shell Surfaces -WebUI `!command` shell mode, slash-command shell templates, and PTY terminals follow OpenCode's normal host-process behavior during enforcement. Only the OpenCode `bash` tool is routed into the microVM; these surfaces are not sandboxed. +Slash-command shell templates and PTY terminals follow OpenCode's normal host-process behavior during enforcement. WebUI `!command` shell mode **is** sandboxed: OpenCode builds a synthetic tool part for it and passes that part's call id to `shell.env`, so it is planned and routed into the microVM exactly like an agent `bash` call. -They also spawn the shim, because it is the configured shell, but no working directory is injected for them, so the shim passes the command straight through to the host shell. PTY terminals receive the user's configured shell; `!command` shell mode and slash-command shell templates fall back to the shell the Manager resolved at startup rather than a login shell. +The unsandboxed surfaces also spawn the shim, because it is the configured shell, but no working directory is injected for them, so the shim passes the command straight through to the host shell. PTY terminals receive the user's configured shell; slash-command shell templates fire no `shell.env` hook at all and fall back to the shell the Manager resolved at startup rather than a login shell. + +The `shell.env` hook input carries only `{ cwd, sessionID?, callID? }`, so the presence of a call id is the only available discriminator. It separates session-attached shells (the `bash` tool and `!command` mode) from PTY creation, which has no session context. It cannot distinguish the `bash` tool from `!command` mode. The OpenCode server binds to the configured `OPENCODE_HOST` regardless of enforcement, so the password guard for non-loopback hosts applies in both modes. @@ -70,7 +72,7 @@ All projects share one microVM named `ocm-workspace`: - Each command supplies its own working directory through `msb exec -w`. - A session outside the mounted roots is refused rather than executed on the host. - The Manager verifies the microVM image, resources, user, network policy, mounts (including the `/tmp` tmpfs size and mount options), and labels before reuse. `/tmp` is the only tmpfs the microVM may carry; any other tmpfs fails attestation. -- MSB pulls the configured `SANDBOX_IMAGE` (default `node:24`) automatically; no custom image build is needed. +- MSB pulls the configured `SANDBOX_IMAGE` (default `docker.io/cstechdev/ocm-sandbox:latest`) automatically; see [Sandbox Guest Image](#sandbox-guest-image) to build your own. - The Manager pins a neutral `/usr/bin/env` entrypoint, so the image's own OCI entrypoint is never inherited. - A stale or unverifiable microVM is removed and recreated. - Manager shutdown and an enforced-to-disabled restart stop the managed microVM. @@ -128,12 +130,69 @@ The enforcement stamp remains authoritative for the lifetime of the OpenCode chi - User-created OpenCode worktrees outside the mounted roots are created normally; only a later agent `bash` call whose working directory is outside the mounts is refused by the planner. - External repositories symlinked into `/workspace/repos` remain outside the microVM because the link target is not mounted. +## Git Credentials in the Sandbox + +The guest environment is empty by default, so a sandboxed `git push`, `git pull`, or `gh` call has no credentials and fails to authenticate. This applies to agent `bash` calls and to WebUI `!command` shell mode alike, since both are routed into the microVM. + +Forwarding is opt-in, off by default: + +| Scope | Where | Effect | +| --- | --- | --- | +| Global | Settings → Sandbox → *Git credentials in sandbox* (`preferences.sandbox.gitCredentials`) | Default for every repo | +| Per repo | `repo_settings.sandboxGitCredentials` | Overrides the global default in either direction | + +When enabled, the planner resolves credentials on the host and the shim forwards them into the microVM with `msb exec -e`: + +- One `http..extraheader` pair per configured host, so a command can authenticate against every host you have a credential for, not just the repo's own remote. +- Where several credentials share a host, the repo-bound credential wins, then `defaultGitCredentialId`. Exactly one credential is ever sent per host — git treats `http..extraheader` as multi-valued and would otherwise send competing `Authorization` headers. +- `GIT_AUTHOR_*` / `GIT_COMMITTER_*` so `git commit` has an identity, and `GH_TOKEN` / `GITHUB_TOKEN` for `gh`. +- At most 16 hosts. Beyond that the Manager logs a warning and forwards the first 16 rather than emitting a `GIT_CONFIG_COUNT` that git would reject. + +Credentials are resolved per command, so changing a credential takes effect on the next sandboxed command without restarting the OpenCode server. + +Understand the trade-off before enabling it. `msb exec -e` is the only injection mechanism microsandbox offers, so the token is visible in the `msb` process arguments on the host and in the guest environment for that command's lifetime. A prompt-injected agent inside the microVM can read and exfiltrate any credential you forward. Leave it off for repos where the agent handles untrusted input, and prefer per-repo opt-in over the global switch. + +## Sandbox Guest Image + +`SANDBOX_IMAGE` defaults to `docker.io/cstechdev/ocm-sandbox:latest`, built from `Dockerfile.sandbox` in this repository and published for `linux/amd64` and `linux/arm64` by the `Sandbox Image` workflow. + +It is `node:24` (Debian 12, `buildpack-deps` based), so the compile toolchain is already present, plus two additions: + +| Tool | Source | Notes | +| --- | --- | --- | +| `gcc` / `g++` / `make` / `ld` / `pkg-config` | `node:24` | GCC 12.2, GNU Make 4.3 | +| `glib-2.0` | `node:24` | 2.74.6, with `pkg-config` metadata | +| `git`, `ssh`, `python3`, `curl`, `unzip` | `node:24` | git 2.39.5 | +| `gh` | official `cli.github.com` apt repo | Current release. Debian's own package is several years stale | +| Chromium | Playwright (`PLAYWRIGHT_VERSION`, default `1.56.0`) | Installed to `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`, world-readable so `SANDBOX_EXEC_USER` can launch it | + +`NODE_PATH=/usr/local/lib/node_modules` is set so agent code can `require("playwright")` from any working directory. It is only a resolution fallback; a project-local `node_modules` still wins. + +Chromium launches headless as the non-root exec user without extra flags. If your host kernel restricts user namespaces so Chromium's own sandbox fails, pass `--no-sandbox` — the microVM is already the isolation boundary. + +The image is roughly 3.3 GB against a 1.6 GB `node:24` baseline, almost entirely Chromium and its dependencies. The first pull is bounded by `SANDBOX_START_TIMEOUT_MS`; raise it on slow links. + +### Using your own image + +Point `SANDBOX_IMAGE` at any OCI reference the host can pull. It must contain every tool the agent expects to run, and a shell at `/bin/sh`. Changing the value is safe at runtime: the running microVM fails image attestation and is recreated automatically. + +To build it on the server instead of pulling: + +```bash +docker build -f Dockerfile.sandbox -t my-sandbox:local . +# then set SANDBOX_IMAGE=my-sandbox:local +``` + +Pin a concrete tag or digest rather than a floating one. Attestation compares the image *reference string*, so a mutable tag keeps passing attestation while the underlying image drifts. + +Override the Playwright version at build time with `--build-arg PLAYWRIGHT_VERSION=1.57.0`. If your project drives Playwright itself, match this version to the one in your `package.json`; a mismatched browser revision makes Playwright refuse to launch. + ## Caveats - The first command pays image pull and microVM boot latency, bounded by `SANDBOX_START_TIMEOUT_MS`. - `SANDBOX_IMAGE` must contain every tool the agent expects to run. - `SANDBOX_EXEC_USER` must match the workspace owner so commands can write mounted files. -- A `shell` the user configured does not apply to `!command` shell mode or slash-command shell templates while enforcement is on. -- Credentials injected into OpenCode's host shell environment are not forwarded into the microVM. +- A `shell` the user configured does not apply to slash-command shell templates while enforcement is on, and is bypassed for `!command` shell mode because that surface is routed into the microVM. +- Credentials injected into OpenCode's host shell environment are not forwarded into the microVM unless git credential forwarding is enabled; see [Git Credentials in the Sandbox](#git-credentials-in-the-sandbox). - Message parts recorded by older releases still hold the old `msb exec` wrapper; the WebUI unwraps them for display and still badges them. - Plugins and other configured host-process extensions are trusted and are not isolated by agent `bash` sandboxing. diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index e5d7400c..fe68ca4d 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -78,8 +78,7 @@ export interface UserPreferences { export interface SettingsResponse { preferences: UserPreferences updatedAt: number - serverRestarted?: boolean - reloadError?: string + restartRequired?: boolean } export interface UpdateSettingsRequest { diff --git a/frontend/src/components/settings/GitSettings.tsx b/frontend/src/components/settings/GitSettings.tsx index caffbcd7..5b032a9c 100644 --- a/frontend/src/components/settings/GitSettings.tsx +++ b/frontend/src/components/settings/GitSettings.tsx @@ -4,12 +4,14 @@ import { useSettings } from '@/hooks/useSettings' import { Loader2, Plus, Trash2, Save, User, Key, Pencil } from 'lucide-react' import { showToast } from '@/lib/toast' import { GitCredentialDialog, type GitCredentialSaveOptions } from './GitCredentialDialog' +import { RestartServerDialog } from './RestartServerDialog' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { randomId } from '@/lib/utils' -import type { GitCredential, GitIdentity } from '@/api/types/settings' +import type { GitCredential, GitIdentity, UserPreferences } from '@/api/types/settings' import { listRepos, updateRepoGitCredential } from '@/api/repos' +import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions' function ensureCredentialId(credential: GitCredential): GitCredential { return credential.id ? credential : { ...credential, id: randomId() } @@ -31,6 +33,27 @@ export function GitSettings() { queryFn: listRepos, }) + const { + restartServerMutation, + confirmOpen, + setConfirmOpen, + activeSessionCount, + requestRestart, + confirmRestart, + } = useOpenCodeServerActions() + + const saveGitSettings = async ( + updates: Partial, + options: { successMessage: string; toastId?: string; afterSave?: () => Promise } + ) => { + const result = await updateSettingsAsync(updates) + await options.afterSave?.() + showToast.success(options.successMessage, options.toastId ? { id: options.toastId } : undefined) + if (result.restartRequired) { + await requestRestart() + } + } + useEffect(() => { if (preferences) { @@ -98,9 +121,13 @@ export function GitSettings() { setDefaultGitCredentialId(nextDefaultGitCredentialId) try { - await updateSettingsAsync({ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity }) - await syncRepoAssignments(nextCredential.id!, options.repoIds) - showToast.success('Credential saved') + await saveGitSettings( + { gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity }, + { + successMessage: 'Credential saved', + afterSave: () => syncRepoAssignments(nextCredential.id!, options.repoIds), + } + ) } catch { showToast.error('Failed to save credential') } @@ -116,11 +143,13 @@ export function GitSettings() { setDefaultGitCredentialId(nextDefaultGitCredentialId) try { - await updateSettingsAsync({ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity }) - if (removedCredentialId) { - await syncRepoAssignments(removedCredentialId, []) - } - showToast.success('Credential deleted') + await saveGitSettings( + { gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity }, + { + successMessage: 'Credential deleted', + afterSave: removedCredentialId ? () => syncRepoAssignments(removedCredentialId, []) : undefined, + } + ) } catch { showToast.error('Failed to delete credential') } @@ -136,13 +165,11 @@ export function GitSettings() { setIsSaving(true) try { showToast.loading('Saving git configuration...', { id: 'git-config' }) - const result = await updateSettingsAsync({ gitCredentials, defaultGitCredentialId, gitIdentity }) + await saveGitSettings( + { gitCredentials, defaultGitCredentialId, gitIdentity }, + { successMessage: 'Git configuration saved', toastId: 'git-config' } + ) setHasChanges(false) - if (result.reloadError) { - showToast.success('Git configuration saved (server reload pending)', { id: 'git-config' }) - } else { - showToast.success('Git configuration saved', { id: 'git-config' }) - } } catch { showToast.error('Failed to save git configuration', { id: 'git-config' }) } finally { @@ -331,6 +358,15 @@ export function GitSettings() { isDefault={editingCredentialIndex !== null && !!gitCredentials[editingCredentialIndex]?.id && defaultGitCredentialId === gitCredentials[editingCredentialIndex]?.id} isSaving={isSaving || isUpdating} /> + + setConfirmOpen(false)} + onConfirm={confirmRestart} + /> ) } diff --git a/shared/src/config/defaults.ts b/shared/src/config/defaults.ts index 9948e16e..beb3b895 100644 --- a/shared/src/config/defaults.ts +++ b/shared/src/config/defaults.ts @@ -33,7 +33,7 @@ export const DEFAULTS = { SANDBOX: { MSB_PATH: 'msb', - IMAGE: 'node:24', + IMAGE: 'docker.io/cstechdev/ocm-sandbox:latest', MEMORY: '4G', CPUS: 2, EXEC_USER: 'node', diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 40a6e4ae..b2fa1484 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -134,12 +134,14 @@ export const DEFAULT_GIT_IDENTITY: GitIdentity = { export const SandboxPreferencesSchema = z.object({ enabled: z.boolean(), + gitCredentials: z.boolean().optional(), }); export type SandboxPreferences = z.infer; export const DEFAULT_SANDBOX_PREFERENCES: SandboxPreferences = { enabled: false, + gitCredentials: false, }; export const UserPreferencesSchema = z.object({