mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +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
@@ -1,6 +1,7 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './upstream'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
@@ -35,12 +36,12 @@ export interface OpenCodeClient {
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
startMcpAuth(serverName: string, directory?: string): Promise<Response>
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export type OpenCodeClientHost = string | (() => string)
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
baseUrl: OpenCodeClientHost
|
||||
basicAuth: string | null
|
||||
passwordResolver?: OpenCodePasswordResolver
|
||||
fetchFn?: typeof fetch
|
||||
@@ -53,6 +54,10 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private resolveBaseUrl(): string {
|
||||
return typeof this.config.baseUrl === 'function' ? this.config.baseUrl() : this.config.baseUrl
|
||||
}
|
||||
|
||||
private async getBasicAuth(): Promise<string> {
|
||||
if (!this.config.passwordResolver) {
|
||||
return this.config.basicAuth ?? ''
|
||||
@@ -62,7 +67,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
const url = new URL(this.resolveBaseUrl() + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
@@ -228,29 +233,14 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async startMcpAuth(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async authenticateMcp(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
|
||||
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
|
||||
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
|
||||
export function createOpenCodeClient(
|
||||
passwordOverride?: string | OpenCodePasswordResolver,
|
||||
host?: OpenCodeClientHost,
|
||||
): OpenCodeClient {
|
||||
const resolveConfiguredHost = typeof host === 'function' ? host : () => (host ?? ENV.OPENCODE.HOST)
|
||||
const baseUrl: OpenCodeClientHost = () => getOpenCodeUpstreamBaseUrl(resolveConfiguredHost())
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
export type EnforcementRemovedSections = Record<string, unknown>
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function mergeRecordSections(target: Record<string, unknown>, key: string, value: Record<string, unknown>): void {
|
||||
const current = isRecord(target[key]) ? { ...(target[key] as Record<string, unknown>) } : {}
|
||||
for (const [name, entry] of Object.entries(value)) {
|
||||
if (current[name] === undefined) {
|
||||
current[name] = entry
|
||||
}
|
||||
}
|
||||
target[key] = current
|
||||
}
|
||||
|
||||
export function restoreEnforcementSections(
|
||||
config: Record<string, unknown>,
|
||||
removed: EnforcementRemovedSections,
|
||||
): Record<string, unknown> {
|
||||
const restored: Record<string, unknown> = { ...config }
|
||||
|
||||
for (const [key, value] of Object.entries(removed)) {
|
||||
if (key === 'plugin') {
|
||||
if (Array.isArray(value) && value.length > 0 && restored.plugin === undefined) {
|
||||
restored.plugin = value
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (key === 'mcp' && isRecord(value)) {
|
||||
mergeRecordSections(restored, 'mcp', value)
|
||||
continue
|
||||
}
|
||||
if (key === 'provider' && isRecord(value)) {
|
||||
mergeRecordSections(restored, 'provider', value)
|
||||
continue
|
||||
}
|
||||
if (key === 'experimentalHook') {
|
||||
const experimental = isRecord(restored.experimental)
|
||||
? { ...(restored.experimental as Record<string, unknown>) }
|
||||
: {}
|
||||
if (experimental.hook === undefined) {
|
||||
experimental.hook = value
|
||||
restored.experimental = experimental
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (restored[key] === undefined) {
|
||||
restored[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return restored
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { join } from 'path'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
|
||||
import { buildManagerToolPluginSource } from '../opencode-manager-tool-plugin'
|
||||
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
|
||||
import { ensureSandboxShellShim } from '../sandbox/shell-shim'
|
||||
|
||||
type ManagedOpenCodePlugin = {
|
||||
filename: string
|
||||
buildSource: (context: { shellShimPath: string }) => string
|
||||
}
|
||||
|
||||
const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
|
||||
{ filename: 'ocm-gh-env.js', buildSource: () => buildGhEnvPluginSource() },
|
||||
{ filename: 'ocm-manager.js', buildSource: () => buildManagerToolPluginSource() },
|
||||
{ filename: 'ocm-sandbox.js', buildSource: ({ shellShimPath }) => buildSandboxPluginSource(shellShimPath) },
|
||||
]
|
||||
|
||||
export function getOpenCodePluginDir(configHome: string): string {
|
||||
return join(configHome, 'opencode', 'plugin')
|
||||
}
|
||||
|
||||
export async function installManagedPlugins(configHome: string): Promise<void> {
|
||||
const shellShimPath = await ensureSandboxShellShim(configHome)
|
||||
const dir = getOpenCodePluginDir(configHome)
|
||||
for (const plugin of MANAGED_OPENCODE_PLUGINS) {
|
||||
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ shellShimPath }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { readFileSync, readdirSync } from 'fs'
|
||||
|
||||
export type ProcessStat = {
|
||||
pgrp: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessGroupMember = {
|
||||
pid: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessIdentityProvider = {
|
||||
attested: boolean
|
||||
readProcessStat(pid: number): ProcessStat | null
|
||||
readProcessGroupMembers(pgid: number): ProcessGroupMember[]
|
||||
}
|
||||
|
||||
function parseProcessStat(stat: string): ProcessStat | null {
|
||||
const commEnd = stat.lastIndexOf(')')
|
||||
if (commEnd === -1) return null
|
||||
const fields = stat.slice(commEnd + 2).split(' ')
|
||||
const pgrp = Number(fields[2])
|
||||
const startToken = fields[19]
|
||||
if (!Number.isInteger(pgrp) || pgrp <= 0) return null
|
||||
if (startToken === undefined || startToken === '') return null
|
||||
return { pgrp, startToken }
|
||||
}
|
||||
|
||||
const LINUX_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: true,
|
||||
readProcessStat(pid) {
|
||||
try {
|
||||
return parseProcessStat(readFileSync(`/proc/${pid}/stat`, 'utf-8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
readProcessGroupMembers(pgid) {
|
||||
const members: ProcessGroupMember[] = []
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = readdirSync('/proc')
|
||||
} catch {
|
||||
return members
|
||||
}
|
||||
if (!Array.isArray(entries)) return members
|
||||
for (const entry of entries) {
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const pid = Number(entry)
|
||||
const stat = this.readProcessStat(pid)
|
||||
if (stat !== null && stat.pgrp === pgid) {
|
||||
members.push({ pid, startToken: stat.startToken })
|
||||
}
|
||||
}
|
||||
return members
|
||||
},
|
||||
}
|
||||
|
||||
const DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: false,
|
||||
readProcessStat() {
|
||||
return null
|
||||
},
|
||||
readProcessGroupMembers() {
|
||||
return []
|
||||
},
|
||||
}
|
||||
|
||||
let cachedProvider: ProcessIdentityProvider | null = null
|
||||
let forcedProvider: ProcessIdentityProvider | null = null
|
||||
|
||||
export function resolveProcessIdentityProvider(): ProcessIdentityProvider {
|
||||
if (cachedProvider !== null) return cachedProvider
|
||||
cachedProvider = forcedProvider ??
|
||||
(process.platform === 'linux' ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER)
|
||||
return cachedProvider
|
||||
}
|
||||
|
||||
export function resetProcessIdentityProvider(): void {
|
||||
cachedProvider = null
|
||||
}
|
||||
|
||||
export function forceProcessAttestation(attested: boolean | null): void {
|
||||
forcedProvider = attested === null ? null : attested ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER
|
||||
cachedProvider = null
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
if (host.startsWith('[') && host.endsWith(']')) return host
|
||||
return host.includes(':') ? `[${host}]` : host
|
||||
}
|
||||
|
||||
export function getOpenCodeUpstreamBaseUrl(hostOverride?: string | (() => string)): string {
|
||||
const configuredHost = typeof hostOverride === 'function' ? hostOverride() : (hostOverride ?? ENV.OPENCODE.HOST)
|
||||
const normalizedHost = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
|
||||
return `http://${formatOpenCodeHostForUrl(normalizedHost)}:${ENV.OPENCODE.PORT}`
|
||||
}
|
||||
Reference in new issue
Block a user