mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(sandbox): harden enforcement validation and backup handling
This commit is contained in:
1 parent
f315dda3f3
commit
0481160f5e
13 files changed
+180
-101
No files matched your search
+20
-16
@@ -323,23 +323,27 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'Failed to create workspace' }, 500)
|
||||
}
|
||||
|
||||
const workspaceRecord = workspace as { id?: unknown; directory?: unknown } | null
|
||||
if (
|
||||
workspaceRecord &&
|
||||
typeof workspaceRecord.directory === 'string' &&
|
||||
opencodeServerManager.isSandboxEnforced() &&
|
||||
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) === null
|
||||
) {
|
||||
if (typeof workspaceRecord.id === 'string' && workspaceRecord.id.length > 0) {
|
||||
await openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
const workspaceRecord = workspace && typeof workspace === 'object'
|
||||
? workspace as { id?: unknown; directory?: unknown }
|
||||
: null
|
||||
if (opencodeServerManager.isSandboxEnforced()) {
|
||||
const directoryAllowed =
|
||||
typeof workspaceRecord?.directory === 'string' &&
|
||||
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) !== null
|
||||
if (!directoryAllowed) {
|
||||
if (typeof workspaceRecord?.id === 'string' && workspaceRecord.id.length > 0) {
|
||||
await openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
} else {
|
||||
logger.warn(`Rejected an OpenCode workspace for repo ${id} that could not be validated against the sandbox roots; it reported no usable id, so it may need manual cleanup`)
|
||||
}
|
||||
return c.json({
|
||||
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
|
||||
}, 400)
|
||||
}
|
||||
return c.json({
|
||||
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
|
||||
}, 400)
|
||||
}
|
||||
|
||||
return c.json(workspace)
|
||||
|
||||
@@ -376,13 +376,11 @@ async function readPluginConfigBackup(backupPath: string): Promise<PluginConfigB
|
||||
return null
|
||||
}
|
||||
|
||||
function backupRemovedSections(backup: PluginConfigBackup | null): EnforcementRemovedSections {
|
||||
if (backup !== null && backup.removedSections !== undefined && isRecord(backup.removedSections)) {
|
||||
function backupRemovedSections(backup: PluginConfigBackup): EnforcementRemovedSections {
|
||||
if (isRecord(backup.removedSections)) {
|
||||
return backup.removedSections as EnforcementRemovedSections
|
||||
}
|
||||
const legacyPlugins = backup !== null && Array.isArray(backup.originalPlugins)
|
||||
? backup.originalPlugins
|
||||
: backup?.plugin
|
||||
const legacyPlugins = Array.isArray(backup.originalPlugins) ? backup.originalPlugins : backup.plugin
|
||||
return Array.isArray(legacyPlugins) ? { plugin: legacyPlugins } : {}
|
||||
}
|
||||
|
||||
@@ -509,13 +507,14 @@ async function sanitizeEnforcementConfigSections(configPath: string): Promise<vo
|
||||
let effectiveRemoved = removed
|
||||
if (hasBackup) {
|
||||
const backup = await readPluginConfigBackup(backupPath)
|
||||
if (backup !== null) {
|
||||
const priorRemoved = backupRemovedSections(backup)
|
||||
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
|
||||
effectiveRemoved = priorRemoved
|
||||
} else {
|
||||
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
|
||||
}
|
||||
if (backup === null) {
|
||||
throw new Error(`cannot read OpenCode enforcement backup ${backupPath}; refusing to overwrite it because the config sections it holds would be lost`)
|
||||
}
|
||||
const priorRemoved = backupRemovedSections(backup)
|
||||
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
|
||||
effectiveRemoved = priorRemoved
|
||||
} else {
|
||||
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,13 +68,6 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts OpenCode for callers that have already persisted their change. A
|
||||
* failed restart must not be reported as a failed write, so the failure is
|
||||
* logged and returned as a flag instead of thrown; the caller returns the
|
||||
* persisted entity so the client can distinguish "saved but needs a restart"
|
||||
* from "nothing was saved".
|
||||
*/
|
||||
export async function restartOpenCodeAfterCommit(
|
||||
supervisor?: OpenCodeSupervisor,
|
||||
): Promise<{ restartFailed: boolean; restartError?: string }> {
|
||||
|
||||
@@ -14,10 +14,10 @@ function guardCommand(reason) {
|
||||
return "printf '%s\\\\n' '" + safe + "' >&2; exit 1"
|
||||
}
|
||||
|
||||
function lockArgsReference(output, args) {
|
||||
function lockAccessor(target, key, value) {
|
||||
try {
|
||||
Object.defineProperty(output, 'args', {
|
||||
get: function () { return args },
|
||||
Object.defineProperty(target, key, {
|
||||
get: function () { return value },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
@@ -25,29 +25,11 @@ function lockArgsReference(output, args) {
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
var descriptor = Object.getOwnPropertyDescriptor(output, 'args')
|
||||
return !!descriptor && descriptor.configurable === false && typeof descriptor.get === 'function'
|
||||
}
|
||||
|
||||
function lockCommand(args, command) {
|
||||
var current = null
|
||||
try {
|
||||
Object.defineProperty(args, 'command', {
|
||||
get: function () { return command },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
})
|
||||
current = args.command
|
||||
} catch (error) {
|
||||
try {
|
||||
args.command = command
|
||||
current = args.command
|
||||
} catch (ignored) {
|
||||
current = null
|
||||
}
|
||||
}
|
||||
return current === command
|
||||
var descriptor = Object.getOwnPropertyDescriptor(target, key)
|
||||
return !!descriptor
|
||||
&& descriptor.configurable === false
|
||||
&& typeof descriptor.get === 'function'
|
||||
&& target[key] === value
|
||||
}
|
||||
|
||||
var wrappedCommands = new Map()
|
||||
@@ -64,10 +46,10 @@ function rememberWrapped(callID, command) {
|
||||
}
|
||||
|
||||
function replaceCommand(output, command, callID) {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
if (!lockAccessor(output, 'args', output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
if (!lockCommand(output.args, command)) {
|
||||
if (!lockAccessor(output.args, 'command', command)) {
|
||||
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
|
||||
}
|
||||
rememberWrapped(callID, command)
|
||||
@@ -79,7 +61,7 @@ export default async function ({ directory, worktree }) {
|
||||
if (input.tool !== 'bash') return
|
||||
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
|
||||
if (typeof output.args?.command !== 'string') {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
if (!lockAccessor(output, 'args', output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1195,8 +1195,8 @@ class OpenCodeServerManager {
|
||||
async fetchVersion(): Promise<string | null> {
|
||||
try {
|
||||
const executable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
const result = execSync(`${executable} --version 2>&1`, { encoding: 'utf8' })
|
||||
const match = result.match(/(\d+\.\d+\.\d+)/)
|
||||
const result = spawnSync(executable, ['--version'], { encoding: 'utf8' })
|
||||
const match = `${result.stdout ?? ''}${result.stderr ?? ''}`.match(/(\d+\.\d+\.\d+)/)
|
||||
if (match && match[1]) {
|
||||
this.version = match[1]
|
||||
return this.version
|
||||
|
||||
@@ -48,9 +48,16 @@ export function sanitizeConfigForEnforcementResult(
|
||||
return { sanitized, removed }
|
||||
}
|
||||
|
||||
export function isProvablyRemoteMcpEntry(entry: unknown): boolean {
|
||||
return isRecord(entry)
|
||||
&& entry.type === 'remote'
|
||||
&& typeof entry.url === 'string'
|
||||
&& entry.command === undefined
|
||||
&& entry.environment === undefined
|
||||
}
|
||||
|
||||
export function isLocalMcpServerEntry(entry: unknown): boolean {
|
||||
if (!isRecord(entry)) return false
|
||||
return entry.type === 'local' || Array.isArray(entry.command)
|
||||
return !isProvablyRemoteMcpEntry(entry)
|
||||
}
|
||||
|
||||
export function isCustomProviderEntry(entry: unknown): boolean {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
|
||||
import { isProvablyRemoteMcpEntry, isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
|
||||
|
||||
export type SandboxProxyDecision = { blocked: true; reason: string } | { blocked: false }
|
||||
|
||||
@@ -158,14 +158,7 @@ export function decideSandboxMcpAddBody(
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
const config = parsed.config
|
||||
if (
|
||||
!isRecord(config) ||
|
||||
config.type !== 'remote' ||
|
||||
typeof config.url !== 'string' ||
|
||||
config.command !== undefined ||
|
||||
config.environment !== undefined
|
||||
) {
|
||||
if (!isProvablyRemoteMcpEntry(parsed.config)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}only remote MCP servers can be added while enforcement is active`,
|
||||
|
||||
Reference in new issue
Block a user