mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(secrets): forward only planned variables into the sandbox and cache repo env resolution
The sandbox shim forwards only the plan's pinned names, so turning sandbox Git credentials off withholds tokens. Sandboxed shells resolve repo env once, terminals on linked servers get no local env, mapping keys cannot override git credentials, masks are kept per directory, and directory resolution is cached. A legacy gh-env alias keeps adopted OpenCode processes working for one release.
This commit is contained in:
1 parent
a0d1d91f18
commit
3e51280894
36 files changed
+1010
-259
No files matched your search
@@ -1,30 +1,53 @@
|
||||
export function buildGhEnvPluginSource(id: string): string {
|
||||
return `const TTL_MS = 5000
|
||||
let cache = new Map()
|
||||
const maskValues = new Set()
|
||||
import { SANDBOX_SHELL_MARKER_PREFIX, SANDBOX_SHELL_STATE_KEY, SECRET_MASK_STORE_SOURCE } from './opencode-plugin-state'
|
||||
|
||||
function rememberMasks(values) {
|
||||
if (!Array.isArray(values)) return
|
||||
for (const value of values) {
|
||||
if (typeof value === 'string' && value.length > 0) maskValues.add(value)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Builds the generated gh-env plugin source.
|
||||
*
|
||||
* The plugin keeps secret masks per cwd and replaces them on every successful
|
||||
* `/shell-env` fetch for that cwd, so a rotated or removed secret stops being
|
||||
* masked. A tool result is masked with the masks of the cwd the shell ran in
|
||||
* when the tool event exposes one (`cwd` or `workdir` on the input); a tool
|
||||
* result that exposes no cwd is masked with the union of the current per-cwd
|
||||
* mask sets, never with values that were already replaced.
|
||||
*
|
||||
* A spawn that belongs to a sandboxed shell asks `/shell-env` to skip the
|
||||
* repository env, because the sandbox plan resolves it once for the microVM and
|
||||
* registers its mask values through the shared mask store.
|
||||
*/
|
||||
export function buildGhEnvPluginSource(id: string): string {
|
||||
return `var TTL_MS = 5000
|
||||
var cache = new Map()
|
||||
var SHELL_STATE_KEY = Symbol.for(${JSON.stringify(SANDBOX_SHELL_STATE_KEY)})
|
||||
var SHELL_MARKER_PREFIX = ${JSON.stringify(SANDBOX_SHELL_MARKER_PREFIX)}
|
||||
|
||||
${SECRET_MASK_STORE_SOURCE}
|
||||
|
||||
function emptyBody() {
|
||||
return { env: {}, mask: [] }
|
||||
}
|
||||
|
||||
async function fetchShellEnv(cwd) {
|
||||
function isSandboxedShell(event) {
|
||||
var state = globalThis[SHELL_STATE_KEY]
|
||||
if (state === null || typeof state !== 'object') {
|
||||
return typeof event.command === 'string' && event.command.indexOf(SHELL_MARKER_PREFIX) === 0
|
||||
}
|
||||
var inFlight = state.inFlightSandboxedCommands
|
||||
if (!(inFlight instanceof Map)) return false
|
||||
return inFlight.has(event.command)
|
||||
}
|
||||
|
||||
async function fetchShellEnv(cwd, sandboxed) {
|
||||
const baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
const token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) return emptyBody()
|
||||
const now = Date.now()
|
||||
const cacheKey = cwd || ''
|
||||
const cacheKey = (cwd || '') + (sandboxed ? '\\u0000sandboxed' : '')
|
||||
const cached = cache.get(cacheKey)
|
||||
if (cached && now < cached.expiry) return cached
|
||||
try {
|
||||
const url = new URL(baseUrl + '/shell-env')
|
||||
if (cwd) url.searchParams.set('cwd', cwd)
|
||||
if (sandboxed) url.searchParams.set('sandboxed', '1')
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
})
|
||||
@@ -46,30 +69,43 @@ function isPlainObject(value) {
|
||||
return proto === Object.prototype || proto === null
|
||||
}
|
||||
|
||||
function containsMask(text) {
|
||||
for (const value of maskValues) {
|
||||
function resultCwd(event) {
|
||||
const input = event.input
|
||||
if (input === null || typeof input !== 'object') return null
|
||||
if (typeof input.cwd === 'string' && input.cwd.length > 0) return input.cwd
|
||||
if (typeof input.workdir === 'string' && input.workdir.length > 0) return input.workdir
|
||||
return null
|
||||
}
|
||||
|
||||
function masksForResult(event) {
|
||||
const cwd = resultCwd(event)
|
||||
if (cwd === null) return allCurrentMaskValues()
|
||||
return currentMaskValues(cwd) || allCurrentMaskValues()
|
||||
}
|
||||
|
||||
function containsMask(text, values) {
|
||||
for (const value of values) {
|
||||
if (text.indexOf(value) !== -1) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function applyMasks(text) {
|
||||
function applyMasks(text, values) {
|
||||
let result = text
|
||||
const ordered = Array.from(maskValues).sort(function (a, b) { return b.length - a.length })
|
||||
for (const value of ordered) {
|
||||
for (const value of values) {
|
||||
if (result.indexOf(value) !== -1) result = result.split(value).join('***')
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function maskValue(value) {
|
||||
function maskValue(value, values) {
|
||||
if (typeof value === 'string') {
|
||||
return containsMask(value) ? applyMasks(value) : value
|
||||
return containsMask(value, values) ? applyMasks(value, values) : value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
let copy = null
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const masked = maskValue(value[index])
|
||||
const masked = maskValue(value[index], values)
|
||||
if (masked !== value[index]) {
|
||||
if (copy === null) copy = value.slice()
|
||||
copy[index] = masked
|
||||
@@ -80,7 +116,7 @@ function maskValue(value) {
|
||||
if (isPlainObject(value)) {
|
||||
let copy = null
|
||||
for (const key of Object.keys(value)) {
|
||||
const masked = maskValue(value[key])
|
||||
const masked = maskValue(value[key], values)
|
||||
if (masked !== value[key]) {
|
||||
if (copy === null) copy = Object.assign({}, value)
|
||||
copy[key] = masked
|
||||
@@ -95,16 +131,18 @@ export default {
|
||||
id: '${id}',
|
||||
async setup(ctx) {
|
||||
await ctx.shell.hook('create.before', async (event) => {
|
||||
const body = await fetchShellEnv(event.cwd)
|
||||
rememberMasks(body.mask)
|
||||
const sandboxed = isSandboxedShell(event)
|
||||
const body = await fetchShellEnv(event.cwd, sandboxed)
|
||||
if (!sandboxed) replaceMaskValues(event.cwd, body.mask)
|
||||
Object.assign(event.env, body.env)
|
||||
})
|
||||
await ctx.tool.hook('execute.after', async (event) => {
|
||||
if (event.status !== 'completed') return
|
||||
if (maskValues.size === 0) return
|
||||
if (event.result === null || typeof event.result !== 'object') return
|
||||
const values = masksForResult(event)
|
||||
if (values.length === 0) return
|
||||
const source = { ...event.result }
|
||||
const masked = maskValue(source)
|
||||
const masked = maskValue(source, values)
|
||||
if (masked !== source) event.result = masked
|
||||
})
|
||||
},
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Process-wide global key under which the Managed OpenCode plugins share shell
|
||||
* sandbox state. Both plugins run inside the OpenCode process, so the key has to
|
||||
* be identical in their generated sources.
|
||||
*/
|
||||
export const SANDBOX_SHELL_STATE_KEY = 'ocm-sandbox.shell-state.v3'
|
||||
|
||||
/**
|
||||
* Prefix of the marker prepended to every command that must run in a sandboxed
|
||||
* shell. The sandbox plugin records a marked command as in flight, which is how
|
||||
* the gh-env plugin knows the spawn is sandboxed without a session identifier.
|
||||
*/
|
||||
export const SANDBOX_SHELL_MARKER_PREFIX = 'ocm-sandbox-required-'
|
||||
|
||||
/**
|
||||
* Generated JS for the process-wide secret-mask store. The gh-env plugin applies
|
||||
* the values it keeps and the sandbox plugin registers the values a sandbox plan
|
||||
* resolved, so both plugins interpolate this same source and share the state it
|
||||
* creates.
|
||||
*/
|
||||
export const SECRET_MASK_STORE_SOURCE = `var MASK_STATE_KEY = Symbol.for('ocm-secret-masks.v1')
|
||||
|
||||
function maskState() {
|
||||
var state = globalThis[MASK_STATE_KEY]
|
||||
if (state === undefined) {
|
||||
state = { byCwd: new Map(), version: 0, unionVersion: -1, union: [] }
|
||||
globalThis[MASK_STATE_KEY] = state
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
function replaceMaskValues(cwd, values) {
|
||||
var state = maskState()
|
||||
var seen = new Set()
|
||||
var sorted = []
|
||||
if (Array.isArray(values)) {
|
||||
for (var index = 0; index < values.length; index += 1) {
|
||||
var value = values[index]
|
||||
if (typeof value !== 'string' || value.length === 0 || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
sorted.push(value)
|
||||
}
|
||||
}
|
||||
sorted.sort(function (a, b) { return b.length - a.length })
|
||||
if (sorted.length === 0) state.byCwd.delete(cwd || '')
|
||||
else state.byCwd.set(cwd || '', sorted)
|
||||
state.version += 1
|
||||
}
|
||||
|
||||
function currentMaskValues(cwd) {
|
||||
return maskState().byCwd.get(cwd || '') || null
|
||||
}
|
||||
|
||||
function allCurrentMaskValues() {
|
||||
var state = maskState()
|
||||
if (state.unionVersion === state.version) return state.union
|
||||
var seen = new Set()
|
||||
var union = []
|
||||
for (var list of state.byCwd.values()) {
|
||||
for (var index = 0; index < list.length; index += 1) {
|
||||
if (seen.has(list[index])) continue
|
||||
seen.add(list[index])
|
||||
union.push(list[index])
|
||||
}
|
||||
}
|
||||
union.sort(function (a, b) { return b.length - a.length })
|
||||
state.unionVersion = state.version
|
||||
state.union = union
|
||||
return union
|
||||
}`
|
||||
@@ -1,17 +1,20 @@
|
||||
import { ENV_NAME_PATTERN, SANDBOX_CONTROL_ENV_PREFIXES } from '@opencode-manager/shared/schemas'
|
||||
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
|
||||
import {
|
||||
SANDBOX_FORWARDED_ENV_NAMES,
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
SANDBOX_SHELL_ENV_NAME,
|
||||
SANDBOX_SHELL_ENV_WORKDIR,
|
||||
} from './sandbox/shell-shim'
|
||||
import {
|
||||
SANDBOX_SHELL_MARKER_PREFIX,
|
||||
SANDBOX_SHELL_STATE_KEY,
|
||||
SECRET_MASK_STORE_SOURCE,
|
||||
} from './opencode-plugin-state'
|
||||
|
||||
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
|
||||
|
||||
export const SANDBOX_CLAIM_TIMEOUT_MS = 15000
|
||||
|
||||
export const SANDBOX_SHELL_STATE_KEY = 'ocm-sandbox.shell-state.v2'
|
||||
|
||||
const SANDBOX_DOCKER_HINT = '\n\nCommands run inside an isolated sandbox microVM that includes Docker (docker, docker compose, docker buildx). The Docker daemon is not started automatically: run `ocm-dockerd-start` once before your first docker command; it is safe to run again and exits immediately if the daemon is already running.'
|
||||
|
||||
export function buildSandboxPluginSource(id: string, shellShimPath: string, serviceSettingsPath: string): string {
|
||||
@@ -25,30 +28,52 @@ var CLAIM_TIMEOUT_MS = ${SANDBOX_CLAIM_TIMEOUT_MS}
|
||||
var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
|
||||
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
|
||||
var ENV_SANDBOX_NAME = ${JSON.stringify(SANDBOX_SHELL_ENV_NAME)}
|
||||
var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)}
|
||||
var ENV_FORWARD = ${JSON.stringify(SANDBOX_SHELL_ENV_FORWARD)}
|
||||
var ENV_NAME_PATTERN = new RegExp(${JSON.stringify(ENV_NAME_PATTERN.source)})
|
||||
var CONTROL_ENV_PREFIXES = ${JSON.stringify(SANDBOX_CONTROL_ENV_PREFIXES)}
|
||||
var SERVICE_SETTINGS_PATH = path.resolve(${JSON.stringify(serviceSettingsPath)})
|
||||
var SERVICE_SETTINGS_DIRECTORY = path.dirname(SERVICE_SETTINGS_PATH)
|
||||
var SERVICE_SETTINGS_DENIED = 'OpenCode Manager denies access to its service settings file (service.json), which holds the OpenCode server password.'
|
||||
var DOCKER_HINT = ${JSON.stringify(SANDBOX_DOCKER_HINT)}
|
||||
var SHELL_TOOL_NAME = 'shell'
|
||||
var SHELL_MARKER_PREFIX = 'ocm-sandbox-required-'
|
||||
var SHELL_MARKER_PATTERN = /^(ocm-sandbox-required-[0-9a-f-]{36}) && /
|
||||
var SHELL_MARKER_PREFIX = ${JSON.stringify(SANDBOX_SHELL_MARKER_PREFIX)}
|
||||
var SHELL_MARKER_PATTERN = /^(${SANDBOX_SHELL_MARKER_PREFIX}[0-9a-f-]{36}) && /
|
||||
var PLAN_NAME_PATTERN = /^ocm-session-[0-9a-f]{12}$/
|
||||
var ARBITER_KEY = Symbol.for('opencode.sandbox-arbiter.v1')
|
||||
var SHELL_STATE_KEY = Symbol.for(${JSON.stringify(SANDBOX_SHELL_STATE_KEY)})
|
||||
var OCM_PROVIDER_ID = 'ocm'
|
||||
var TIER_RANK = { workload: 3, explicit: 2, default: 1 }
|
||||
|
||||
${SECRET_MASK_STORE_SOURCE}
|
||||
|
||||
function isControlEnvName(name) {
|
||||
return CONTROL_ENV_PREFIXES.some(function (prefix) { return name.indexOf(prefix) === 0 })
|
||||
}
|
||||
|
||||
function shellSandboxState() {
|
||||
var state = globalThis[SHELL_STATE_KEY]
|
||||
if (state === undefined) {
|
||||
state = { pendingMarkers: new Map(), sandboxedCallIDs: new Set(), foreignOwners: new Map() }
|
||||
state = { pendingMarkers: new Map(), sandboxedCallIDs: new Set(), foreignOwners: new Map(), inFlightSandboxedCommands: new Map() }
|
||||
globalThis[SHELL_STATE_KEY] = state
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
function pinInFlightSandboxCommand(command, markedCommand) {
|
||||
var inFlight = shellState.inFlightSandboxedCommands
|
||||
inFlight.set(command, (inFlight.get(command) || 0) + 1)
|
||||
inFlight.set(markedCommand, (inFlight.get(markedCommand) || 0) + 1)
|
||||
}
|
||||
|
||||
function releaseInFlightSandboxCommand(command, markedCommand) {
|
||||
var inFlight = shellState.inFlightSandboxedCommands
|
||||
for (var key of [command, markedCommand]) {
|
||||
var count = inFlight.get(key) || 0
|
||||
if (count <= 1) inFlight.delete(key)
|
||||
else inFlight.set(key, count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
var shellState = shellSandboxState()
|
||||
|
||||
function sandboxArbiter() {
|
||||
@@ -319,12 +344,13 @@ async function pinSandboxShell(event, sessionID, locationDirectory) {
|
||||
for (var name of Object.keys(plan.env)) {
|
||||
var value = plan.env[name]
|
||||
if (typeof value !== 'string') continue
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue
|
||||
if (name.startsWith('OCM_') || name.startsWith('MSB_')) continue
|
||||
if (!ENV_NAME_PATTERN.test(name)) continue
|
||||
if (isControlEnvName(name)) continue
|
||||
event.env[name] = value
|
||||
forwardNames.push(name)
|
||||
}
|
||||
}
|
||||
replaceMaskValues(event.cwd, plan.mask)
|
||||
if (!lockAccessor(event, 'shell', SHELL_SHIM_PATH)) {
|
||||
throw unavailable('sandbox enforcement could not pin the sandbox shell; aborting before the command runs on the host')
|
||||
}
|
||||
@@ -357,11 +383,14 @@ async function wrapSandboxedShellTool(ctx) {
|
||||
throw unavailable('refusing to run a sandboxed shell call without a command')
|
||||
}
|
||||
var marker = SHELL_MARKER_PREFIX + randomUUID()
|
||||
var markedCommand = marker + ' && ' + input.command
|
||||
shellState.pendingMarkers.set(marker, { callID: context.id, sessionID: context.sessionID })
|
||||
shellState.sandboxedCallIDs.add(context.id)
|
||||
pinInFlightSandboxCommand(input.command, markedCommand)
|
||||
try {
|
||||
return await execute({ ...input, command: marker + ' && ' + input.command }, context)
|
||||
return await execute({ ...input, command: markedCommand }, context)
|
||||
} finally {
|
||||
releaseInFlightSandboxCommand(input.command, markedCommand)
|
||||
shellState.pendingMarkers.delete(marker)
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,24 +1,59 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { interpolateEnvExpressions, type EnvExpressionReference } from '@opencode-manager/shared/utils'
|
||||
import { getRepoByDirectory } from '../db/queries'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { logger } from '../utils/logger'
|
||||
import { resolveMainCheckoutPath, resolveRepoForDirectory } from './repo'
|
||||
import type { ProjectConfigService } from './project-config'
|
||||
import { repoEnvCacheEpoch } from '../utils/repo-env-cache'
|
||||
import { findGitRepoRoot, resolveRepoForDirectory } from './repo'
|
||||
import type { ProjectConfigService, RepoFileState } from './project-config'
|
||||
import type { SecretsService } from './secrets'
|
||||
|
||||
const DIRECTORY_CACHE_TTL_MS = 60_000
|
||||
const DIRECTORY_CACHE_LIMIT = 500
|
||||
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
|
||||
|
||||
export interface ResolvedRepoEnv {
|
||||
env: Record<string, string>
|
||||
maskValues: string[]
|
||||
missing: string[]
|
||||
}
|
||||
|
||||
interface DirectoryResolution {
|
||||
topLevel: string | null
|
||||
repo: Repo | null
|
||||
projectRepo: Repo | null
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
interface RepoFileResolution {
|
||||
signature: string
|
||||
state: RepoFileState
|
||||
}
|
||||
|
||||
function emptyResult(): ResolvedRepoEnv {
|
||||
return { env: {}, maskValues: [], missing: [] }
|
||||
return { env: {}, maskValues: [] }
|
||||
}
|
||||
|
||||
function entrySignature(target: string): string {
|
||||
try {
|
||||
const stats = fs.lstatSync(target)
|
||||
return `${stats.isSymbolicLink() ? 'link' : 'entry'}:${stats.mtimeMs}:${stats.size}`
|
||||
} catch {
|
||||
return 'missing'
|
||||
}
|
||||
}
|
||||
|
||||
function repoFileSignature(filePath: string): string {
|
||||
return `${entrySignature(path.dirname(filePath))}|${entrySignature(filePath)}`
|
||||
}
|
||||
|
||||
export class RepoEnvService {
|
||||
private readonly directoryCache = new Map<string, DirectoryResolution>()
|
||||
private readonly repoFileCache = new Map<string, RepoFileResolution>()
|
||||
private cacheEpoch = repoEnvCacheEpoch()
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly projectConfigService: ProjectConfigService,
|
||||
@@ -33,19 +68,14 @@ export class RepoEnvService {
|
||||
*/
|
||||
async resolveForDirectory(cwd: string): Promise<ResolvedRepoEnv> {
|
||||
try {
|
||||
const topLevel = await this.findTopLevel(cwd)
|
||||
if (!topLevel) {
|
||||
this.syncCacheEpoch()
|
||||
const directory = await this.resolveDirectory(cwd)
|
||||
if (!directory.topLevel || !directory.repo || !directory.projectRepo) {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
const repo = await this.findRepo(topLevel)
|
||||
if (!repo) {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
const projectRepo = await this.projectConfigService.resolveProjectRepo(repo)
|
||||
const repoFile = this.projectConfigService.readRepoFile(topLevel)
|
||||
if (!repoFile.file || !this.projectConfigService.isRepoFileTrusted(projectRepo, repoFile)) {
|
||||
const repoFile = this.readRepoFile(directory.topLevel)
|
||||
if (!repoFile.file || !this.projectConfigService.isRepoFileTrusted(directory.projectRepo, repoFile)) {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
@@ -54,15 +84,13 @@ export class RepoEnvService {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
const resolved = this.secretsService.resolveValues(projectRepo.id, repoFile.file.environment ?? null)
|
||||
const resolved = this.secretsService.resolveValues(directory.projectRepo.id, repoFile.file.environment ?? null)
|
||||
const maskValues = new Set<string>()
|
||||
const missing = new Set<string>()
|
||||
|
||||
const lookup = (reference: EnvExpressionReference): string | undefined => {
|
||||
const values = reference.context === 'secrets' ? resolved.secrets : resolved.vars
|
||||
const found = values[reference.name]
|
||||
if (found === undefined) {
|
||||
missing.add(`${reference.context}.${reference.name}`)
|
||||
return undefined
|
||||
}
|
||||
if (reference.context === 'secrets') {
|
||||
@@ -79,7 +107,6 @@ export class RepoEnvService {
|
||||
return {
|
||||
env,
|
||||
maskValues: [...maskValues].filter((value) => value.length >= 4).sort((a, b) => b.length - a.length),
|
||||
missing: [...missing],
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to resolve repository environment for ${cwd}`, error)
|
||||
@@ -87,30 +114,66 @@ export class RepoEnvService {
|
||||
}
|
||||
}
|
||||
|
||||
private async findTopLevel(cwd: string): Promise<string | null> {
|
||||
try {
|
||||
const output = await executeCommand(['git', '-C', cwd, 'rev-parse', '--show-toplevel'], { silent: true })
|
||||
const topLevel = output.trim()
|
||||
return topLevel.length > 0 ? topLevel : null
|
||||
} catch {
|
||||
return null
|
||||
private syncCacheEpoch(): void {
|
||||
const epoch = repoEnvCacheEpoch()
|
||||
if (epoch === this.cacheEpoch) {
|
||||
return
|
||||
}
|
||||
this.cacheEpoch = epoch
|
||||
this.directoryCache.clear()
|
||||
}
|
||||
|
||||
private async findRepo(topLevel: string): Promise<Repo | null> {
|
||||
const direct = getRepoByDirectory(this.db, topLevel)
|
||||
if (direct) {
|
||||
return direct
|
||||
private async resolveDirectory(cwd: string): Promise<DirectoryResolution> {
|
||||
const key = canonicalPathSync(path.resolve(cwd))
|
||||
const now = Date.now()
|
||||
const cached = this.directoryCache.get(key)
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached
|
||||
}
|
||||
|
||||
const mainCheckout = await resolveMainCheckoutPath(topLevel)
|
||||
if (mainCheckout) {
|
||||
const mainRepo = getRepoByDirectory(this.db, mainCheckout)
|
||||
if (mainRepo) {
|
||||
return mainRepo
|
||||
const topLevel = await findGitRepoRoot(cwd)
|
||||
const repo = topLevel
|
||||
? getRepoByDirectory(this.db, topLevel) ?? (await resolveRepoForDirectory(this.db, topLevel))
|
||||
: null
|
||||
const projectRepo = repo ? await this.projectConfigService.resolveProjectRepo(repo) : null
|
||||
|
||||
this.pruneDirectoryCache(now)
|
||||
const resolution: DirectoryResolution = {
|
||||
topLevel,
|
||||
repo,
|
||||
projectRepo,
|
||||
expiresAt: now + DIRECTORY_CACHE_TTL_MS,
|
||||
}
|
||||
this.directoryCache.set(key, resolution)
|
||||
return resolution
|
||||
}
|
||||
|
||||
private pruneDirectoryCache(now: number): void {
|
||||
if (this.directoryCache.size < DIRECTORY_CACHE_LIMIT) {
|
||||
return
|
||||
}
|
||||
for (const [key, resolution] of this.directoryCache) {
|
||||
if (resolution.expiresAt <= now) {
|
||||
this.directoryCache.delete(key)
|
||||
}
|
||||
}
|
||||
for (const key of this.directoryCache.keys()) {
|
||||
if (this.directoryCache.size < DIRECTORY_CACHE_LIMIT) {
|
||||
break
|
||||
}
|
||||
this.directoryCache.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
return resolveRepoForDirectory(this.db, topLevel)
|
||||
private readRepoFile(topLevel: string): RepoFileState {
|
||||
const signature = repoFileSignature(path.join(topLevel, REPO_FILE_RELATIVE_PATH))
|
||||
const cached = this.repoFileCache.get(topLevel)
|
||||
if (cached?.signature === signature) {
|
||||
return cached.state
|
||||
}
|
||||
|
||||
const state = this.projectConfigService.readRepoFile(topLevel)
|
||||
this.repoFileCache.set(topLevel, { signature, state })
|
||||
return state
|
||||
}
|
||||
}
|
||||
@@ -252,11 +252,12 @@ async function safeGetCurrentBranch(repoPath: string, env: Record<string, string
|
||||
}
|
||||
}
|
||||
|
||||
async function findGitRepoRoot(targetPath: string, env: Record<string, string>): Promise<string | null> {
|
||||
export async function findGitRepoRoot(targetPath: string, env: Record<string, string> = {}): Promise<string | null> {
|
||||
try {
|
||||
const resolvedPath = normalizeAbsolutePath(targetPath)
|
||||
const repoRoot = await executeCommand(['git', '-C', resolvedPath, 'rev-parse', '--show-toplevel'], { env, silent: true })
|
||||
return normalizeAbsolutePath(repoRoot.trim())
|
||||
const trimmed = repoRoot.trim()
|
||||
return trimmed ? normalizeAbsolutePath(trimmed) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ export type SandboxShellTarget = {
|
||||
|
||||
export type SandboxShellPlan =
|
||||
| { mode: 'host' }
|
||||
| { mode: 'sandbox'; name: string; workdir: string; env?: Record<string, string> }
|
||||
| { mode: 'sandbox'; name: string; workdir: string; env?: Record<string, string>; mask?: string[] }
|
||||
| { mode: 'blocked'; reason: string }
|
||||
|
||||
export type SandboxStatus = {
|
||||
@@ -1123,13 +1123,19 @@ export class SandboxRuntimeService {
|
||||
...new CredentialProvider(this.db).getSandboxGitEnv({ cwd: directory }),
|
||||
...await getGitIdentityEnvForDirectory(directory, this.db),
|
||||
}
|
||||
let mask: string[] = []
|
||||
if (this.repoEnvService) {
|
||||
const repoEnv = await this.repoEnvService.resolveForDirectory(directory)
|
||||
Object.assign(env, repoEnv.env)
|
||||
mask = repoEnv.maskValues
|
||||
}
|
||||
return {
|
||||
mode: 'sandbox',
|
||||
name: spec.name,
|
||||
workdir: workDirectory,
|
||||
...(Object.keys(env).length > 0 ? { env } : {}),
|
||||
...(mask.length > 0 ? { mask } : {}),
|
||||
}
|
||||
return Object.keys(env).length > 0
|
||||
? { mode: 'sandbox', name: spec.name, workdir: workDirectory, env }
|
||||
: { mode: 'sandbox', name: spec.name, workdir: workDirectory }
|
||||
} catch (error) {
|
||||
logger.error('Failed to prepare the session sandbox', error)
|
||||
return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import path from 'path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { SANDBOX_CONTROL_ENV_PREFIXES } from '@opencode-manager/shared/schemas'
|
||||
import { isPathWithinRoot, writeFileAtomic } from '../../utils/fs-safe'
|
||||
import {
|
||||
quoteForShell,
|
||||
@@ -29,26 +30,7 @@ export const SANDBOX_SHELL_ENV_FORWARD = 'OCM_SANDBOX_FORWARD_ENV'
|
||||
*/
|
||||
export const SANDBOX_MAX_FORWARDED_GIT_CONFIGS = 16
|
||||
|
||||
/**
|
||||
* Variables the shim always copies from its own environment into the microVM
|
||||
* with `msb exec -e`, independent of the plan-approved allow-list. The guest
|
||||
* environment is otherwise empty, so anything absent from this list and from
|
||||
* the allow-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',
|
||||
]
|
||||
const SANDBOX_CONTROL_ENV_CASE_PATTERN = SANDBOX_CONTROL_ENV_PREFIXES.map((prefix) => `${prefix}*`).join('|')
|
||||
|
||||
/**
|
||||
* Drops `http.<host>.extraheader` pairs beyond the forwarding cap, so the
|
||||
@@ -94,13 +76,10 @@ export function buildSandboxShellShimScript(): string {
|
||||
`${timeoutSeconds}s`,
|
||||
].join(' ')
|
||||
const forwardEnv = [
|
||||
...SANDBOX_FORWARDED_ENV_NAMES.map(
|
||||
(name) => `if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`,
|
||||
),
|
||||
'set -f',
|
||||
`for OCM_SHIM_NAME in \${${SANDBOX_SHELL_ENV_FORWARD}}; do`,
|
||||
` case "$OCM_SHIM_NAME" in`,
|
||||
` ''|[0-9]*|*[!A-Za-z0-9_]*|OCM_*|MSB_*|${SANDBOX_FORWARDED_ENV_NAMES.join('|')}) continue ;;`,
|
||||
` ''|[0-9]*|*[!A-Za-z0-9_]*|${SANDBOX_CONTROL_ENV_CASE_PATTERN}) continue ;;`,
|
||||
' esac',
|
||||
` eval "OCM_SHIM_SET=\\\${$OCM_SHIM_NAME+x}"`,
|
||||
` [ -n "$OCM_SHIM_SET" ] || continue`,
|
||||
|
||||
@@ -19,13 +19,7 @@ interface SecretRow {
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
interface SecretValueRow {
|
||||
kind: SecretKind
|
||||
repo_id: number | null
|
||||
environment: string
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
type SecretValueRow = Omit<SecretRow, 'updated_at'>
|
||||
|
||||
export interface ResolvedSecretValues {
|
||||
secrets: Record<string, string>
|
||||
@@ -97,17 +91,9 @@ export class SecretsService {
|
||||
}
|
||||
|
||||
private selectRows(kind: SecretKind, repoId: number | null): SecretRow[] {
|
||||
if (repoId === null) {
|
||||
return this.db
|
||||
.prepare(
|
||||
'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id IS NULL ORDER BY name',
|
||||
)
|
||||
.all(kind) as SecretRow[]
|
||||
}
|
||||
|
||||
return this.db
|
||||
.prepare(
|
||||
'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id = ? ORDER BY name',
|
||||
'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id IS ? ORDER BY name',
|
||||
)
|
||||
.all(kind, repoId) as SecretRow[]
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface TerminalSize {
|
||||
export interface TerminalTarget {
|
||||
client: OpenCodeClient
|
||||
baseUrl: () => string
|
||||
includeLocalCredentials: boolean
|
||||
includeLocalEnv: boolean
|
||||
}
|
||||
|
||||
export class TerminalNotFoundError extends Error {
|
||||
@@ -84,7 +84,12 @@ export class TerminalService {
|
||||
input.command !== undefined && DEFERRED_START_KINDS.has(input.kind) && process.platform !== 'win32'
|
||||
? deferCommandStart(input.command, input.args ?? [])
|
||||
: undefined
|
||||
const repoEnv = (await this.repoEnvService.resolveForDirectory(directory)).env
|
||||
const localEnv = this.target.includeLocalEnv
|
||||
? {
|
||||
...this.credentialProvider.getGhCliEnv({ cwd: directory }),
|
||||
...(await this.repoEnvService.resolveForDirectory(directory)).env,
|
||||
}
|
||||
: {}
|
||||
const result = await this.target.client.api.pty.create({
|
||||
location: { directory },
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
|
||||
@@ -95,8 +100,7 @@ export class TerminalService {
|
||||
...(input.args !== undefined ? { args: input.args } : {}),
|
||||
}),
|
||||
env: {
|
||||
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
|
||||
...repoEnv,
|
||||
...localEnv,
|
||||
...input.env,
|
||||
},
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user