mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
@@ -4,6 +4,7 @@ import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { invalidateRepoEnvCache } from '../utils/repo-env-cache'
|
||||
import path from 'path'
|
||||
|
||||
interface RepoRow {
|
||||
@@ -185,6 +186,7 @@ export function ensureAssistantRepo(db: Database): Repo {
|
||||
}
|
||||
|
||||
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
|
||||
invalidateRepoEnvCache()
|
||||
const normalizedPath = repo.localPath.trim().replace(/\/+$/, '')
|
||||
|
||||
const existing = repo.isLocal
|
||||
@@ -358,4 +360,5 @@ export function deleteRepo(db: Database, id: number): void {
|
||||
db.prepare('DELETE FROM repos WHERE id = ?').run(id)
|
||||
})
|
||||
remove()
|
||||
invalidateRepoEnvCache()
|
||||
}
|
||||
@@ -264,7 +264,7 @@ const terminalService = new TerminalService(
|
||||
{
|
||||
client: openCodeClient,
|
||||
baseUrl: () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
includeLocalCredentials: true,
|
||||
includeLocalEnv: true,
|
||||
},
|
||||
new CredentialProvider(db),
|
||||
repoEnvService,
|
||||
@@ -274,7 +274,7 @@ const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
return terminalService.forTarget({
|
||||
client: opencodeServerRegistry.getClient(serverId),
|
||||
baseUrl: () => connection.baseUrl,
|
||||
includeLocalCredentials: false,
|
||||
includeLocalEnv: false,
|
||||
})
|
||||
}
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { CredentialProvider } from '../../services/credential-provider'
|
||||
|
||||
/**
|
||||
* Legacy GitHub CLI environment route, kept for one release for OpenCode
|
||||
* processes that were adopted before the upgrade: those processes still run the
|
||||
* removed gh-env plugin and keep calling this path, so it answers with the same
|
||||
* flat env a fresh install fetches from `/shell-env`.
|
||||
*/
|
||||
export function createInternalGitCredentialsRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/gh-env', (c) => {
|
||||
const provider = new CredentialProvider(db)
|
||||
const cwd = c.req.query('cwd')
|
||||
return c.json(provider.getGhCliEnv({ cwd }))
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
|
||||
import { createInternalSessionRoutes } from './sessions'
|
||||
import { createInternalAssistantRoutes } from './assistant'
|
||||
import { createInternalShellEnvRoutes } from './shell-env'
|
||||
import { createInternalGitCredentialsRoutes } from './git-credentials'
|
||||
import { createInternalSandboxRoutes } from './sandbox'
|
||||
import { createInternalSessionArtifactRoutes } from './session-artifacts'
|
||||
import { createSessionGoalRoutes } from '../session-goals'
|
||||
@@ -67,6 +68,7 @@ export function createInternalRoutes(
|
||||
app.route('/walkthrough-sessions', createInternalWalkthroughSessionRoutes(changeWalkthroughService))
|
||||
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
|
||||
app.route('/shell-env', createInternalShellEnvRoutes(db, repoEnvService))
|
||||
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
|
||||
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox, repoEnvService))
|
||||
return app
|
||||
}
|
||||
@@ -10,7 +10,7 @@ export function createInternalShellEnvRoutes(db: Database, repoEnvService: RepoE
|
||||
const provider = new CredentialProvider(db)
|
||||
const cwd = c.req.query('cwd')
|
||||
const ghEnv = provider.getGhCliEnv({ cwd })
|
||||
if (!cwd) {
|
||||
if (!cwd || c.req.query('sandboxed') === '1') {
|
||||
return c.json({ env: ghEnv, mask: [] })
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { EnvironmentNameSchema, SecretNameSchema, SetSecretRequestSchema, type S
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { SecretsService, SecretsServiceError } from '../services/secrets'
|
||||
import type { ProjectConfigService } from '../services/project-config'
|
||||
import { handleServiceError } from '../utils/route-helpers'
|
||||
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
function readName(c: Context): { name: string } | Response {
|
||||
const parsed = SecretNameSchema.safeParse(c.req.param('name'))
|
||||
@@ -29,28 +29,32 @@ function readEnvironmentQuery(c: Context): { environment: string | null } | Resp
|
||||
return { environment: parsed.data }
|
||||
}
|
||||
|
||||
async function putEntry(
|
||||
c: Context,
|
||||
secretsService: SecretsService,
|
||||
kind: SecretKind,
|
||||
repoId: number | null,
|
||||
): Promise<Response> {
|
||||
const name = readName(c)
|
||||
if (name instanceof Response) return name
|
||||
|
||||
const body = await parseJsonBody(c, SetSecretRequestSchema)
|
||||
if (!body.ok) return body.response
|
||||
|
||||
try {
|
||||
secretsService.set(kind, repoId, body.data.environment ?? null, name.name, body.data.value)
|
||||
return c.body(null, 204)
|
||||
} catch (error: unknown) {
|
||||
return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError)
|
||||
}
|
||||
}
|
||||
|
||||
export function createGlobalSecretRoutes(secretsService: SecretsService, kind: SecretKind) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => c.json({ items: secretsService.list(kind, null) }))
|
||||
|
||||
app.put('/:name', async (c) => {
|
||||
const name = readName(c)
|
||||
if (name instanceof Response) return name
|
||||
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = SetSecretRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
secretsService.set(kind, null, parsed.data.environment ?? null, name.name, parsed.data.value)
|
||||
return c.body(null, 204)
|
||||
} catch (error: unknown) {
|
||||
return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError)
|
||||
}
|
||||
})
|
||||
app.put('/:name', (c) => putEntry(c, secretsService, kind, null))
|
||||
|
||||
app.delete('/:name', (c) => {
|
||||
const name = readName(c)
|
||||
@@ -98,24 +102,10 @@ export function createRepoSecretRoutes(deps: RepoSecretRouteDeps, kind: SecretKi
|
||||
})
|
||||
|
||||
app.put(`/:id/${segment}/:name`, async (c) => {
|
||||
const name = readName(c)
|
||||
if (name instanceof Response) return name
|
||||
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = SetSecretRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
const repo = await resolveProjectRepo(c)
|
||||
if (repo instanceof Response) return repo
|
||||
|
||||
try {
|
||||
secretsService.set(kind, repo.id, parsed.data.environment ?? null, name.name, parsed.data.value)
|
||||
return c.body(null, 204)
|
||||
} catch (error: unknown) {
|
||||
return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError)
|
||||
}
|
||||
return putEntry(c, secretsService, kind, repo.id)
|
||||
})
|
||||
|
||||
app.delete(`/:id/${segment}/:name`, async (c) => {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
let cacheEpoch = 0
|
||||
|
||||
/**
|
||||
* Marks every cached repository lookup as stale so the next resolution sees the
|
||||
* current set of registered repositories.
|
||||
*/
|
||||
export function invalidateRepoEnvCache(): void {
|
||||
cacheEpoch += 1
|
||||
}
|
||||
|
||||
export function repoEnvCacheEpoch(): number {
|
||||
return cacheEpoch
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { createStubOpenCodeClient } from './stub-opencode-client'
|
||||
import { createStubRepoEnvService } from './stub-repo-env-service'
|
||||
|
||||
type CreateInternalRoutesParams = Parameters<typeof createInternalRoutes>
|
||||
|
||||
@@ -18,12 +19,6 @@ type InternalTestAppOverrides = Partial<{
|
||||
repoEnvService: CreateInternalRoutesParams[12]
|
||||
}>
|
||||
|
||||
function createStubRepoEnvService(): CreateInternalRoutesParams[12] {
|
||||
return {
|
||||
resolveForDirectory: async () => ({ env: {}, maskValues: [], missing: [] }),
|
||||
} as unknown as CreateInternalRoutesParams[12]
|
||||
}
|
||||
|
||||
export function createInternalTestApp(
|
||||
db: CreateInternalRoutesParams[0],
|
||||
overrides: InternalTestAppOverrides = {},
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { vi } from 'vitest'
|
||||
import type { RepoEnvService } from '../../src/services/repo-env'
|
||||
|
||||
/**
|
||||
* Creates a RepoEnvService stub that resolves a fixed environment.
|
||||
*/
|
||||
export function createStubRepoEnvService(env: Record<string, string> = {}): RepoEnvService {
|
||||
return {
|
||||
resolveForDirectory: vi.fn(async () => ({ env, maskValues: [] })),
|
||||
} as unknown as RepoEnvService
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../../src/db/migrations'
|
||||
import { SettingsService } from '../../../src/services/settings'
|
||||
import { createInternalGitCredentialsRoutes } from '../../../src/routes/internal/git-credentials'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
describe('legacy internal git-credentials routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
})
|
||||
|
||||
it('answers the adopted-process gh-env path with the flat GitHub CLI env', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_legacy_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
const app = createInternalGitCredentialsRoutes(db)
|
||||
|
||||
const res = await app.request('/gh-env')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_legacy_token', GITHUB_TOKEN: 'ghp_legacy_token' })
|
||||
})
|
||||
|
||||
it('accepts the legacy cwd query parameter', async () => {
|
||||
const app = createInternalGitCredentialsRoutes(db)
|
||||
|
||||
const res = await app.request('/gh-env?cwd=/tmp/any-repo')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -31,7 +31,7 @@ describe('internal shell-env routes', () => {
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
const repoEnvService = createRepoEnvService(async () => ({ env: {}, maskValues: [], missing: [] }))
|
||||
const repoEnvService = createRepoEnvService(async () => ({ env: {}, maskValues: [] }))
|
||||
const app = appWith(repoEnvService)
|
||||
|
||||
const res = await app.request('/')
|
||||
@@ -42,7 +42,7 @@ describe('internal shell-env routes', () => {
|
||||
})
|
||||
|
||||
it('returns an empty GH env when no GitHub credential exists', async () => {
|
||||
const app = appWith(createRepoEnvService(async () => ({ env: {}, maskValues: [], missing: [] })))
|
||||
const app = appWith(createRepoEnvService(async () => ({ env: {}, maskValues: [] })))
|
||||
|
||||
const res = await app.request('/')
|
||||
|
||||
@@ -60,7 +60,6 @@ describe('internal shell-env routes', () => {
|
||||
const repoEnvService = createRepoEnvService(async () => ({
|
||||
env: { API_URL: 'https://internal.example', GITHUB_TOKEN: 'mapped' },
|
||||
maskValues: ['super-secret'],
|
||||
missing: [],
|
||||
}))
|
||||
const app = appWith(repoEnvService)
|
||||
|
||||
@@ -73,4 +72,26 @@ describe('internal shell-env routes', () => {
|
||||
})
|
||||
expect(repoEnvService.resolveForDirectory).toHaveBeenCalledWith('/tmp/any-repo')
|
||||
})
|
||||
|
||||
it('skips the repository env resolution when the shell is sandboxed', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_repo_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
const repoEnvService = createRepoEnvService(async () => ({
|
||||
env: { API_URL: 'https://internal.example' },
|
||||
maskValues: ['super-secret'],
|
||||
}))
|
||||
const app = appWith(repoEnvService)
|
||||
|
||||
const res = await app.request('/?cwd=/tmp/any-repo&sandboxed=1')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
env: { GH_TOKEN: 'ghp_repo_token', GITHUB_TOKEN: 'ghp_repo_token' },
|
||||
mask: [],
|
||||
})
|
||||
expect(repoEnvService.resolveForDirectory).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -10,16 +10,12 @@ import { TerminalService } from '../../src/services/terminal'
|
||||
import { OpenCodeServerNotFoundError } from '../../src/services/opencode-server-registry'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import type { RepoEnvService } from '../../src/services/repo-env'
|
||||
import { createStubRepoEnvService } from '../helpers/stub-repo-env-service'
|
||||
import { startWebSocketServer, type WebSocketTestServer } from '../helpers/websocket-server'
|
||||
import { rawWebSocketHandshake } from '../helpers/raw-websocket-handshake'
|
||||
|
||||
const TRUSTED_ORIGIN = 'http://localhost:5003'
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
function stubRepoEnvService(): RepoEnvService {
|
||||
return { resolveForDirectory: async () => ({ env: {}, maskValues: [], missing: [] }) } as unknown as RepoEnvService
|
||||
}
|
||||
|
||||
const UNKNOWN_SERVER_ID = 'srv_missing'
|
||||
const DIRECTORY = '/home/me/app'
|
||||
|
||||
@@ -64,9 +60,9 @@ const managerApp = new Hono()
|
||||
const managerWs = createNodeWebSocket({ app: managerApp })
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
{ client: remoteClient, baseUrl: () => `http://127.0.0.1:${upstream.port}`, includeLocalCredentials: false },
|
||||
{ client: remoteClient, baseUrl: () => `http://127.0.0.1:${upstream.port}`, includeLocalEnv: false },
|
||||
credentialProvider,
|
||||
stubRepoEnvService(),
|
||||
createStubRepoEnvService(),
|
||||
)
|
||||
|
||||
const resolveTerminalService: ServerTerminalServiceResolver = (serverId) => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { TerminalService } from '../../src/services/terminal'
|
||||
import { OpenCodeServerNotFoundError } from '../../src/services/opencode-server-registry'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import type { RepoEnvService } from '../../src/services/repo-env'
|
||||
import { createStubRepoEnvService } from '../helpers/stub-repo-env-service'
|
||||
|
||||
const DIRECTORY = '/home/me/app'
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
@@ -44,19 +44,15 @@ function createRemoteClient(terminals: Array<Record<string, unknown>> = [createP
|
||||
return { client, list, create, update, remove }
|
||||
}
|
||||
|
||||
function stubRepoEnvService(): RepoEnvService {
|
||||
return { resolveForDirectory: async () => ({ env: {}, maskValues: [], missing: [] }) } as unknown as RepoEnvService
|
||||
}
|
||||
|
||||
function createService(includeLocalCredentials = false, terminals?: Array<Record<string, unknown>>) {
|
||||
function createService(includeLocalEnv = false, terminals?: Array<Record<string, unknown>>) {
|
||||
const remote = createRemoteClient(terminals)
|
||||
const credentialProvider = {
|
||||
getGhCliEnv: vi.fn(() => ({ GH_TOKEN: 'local-token' })),
|
||||
} as unknown as CredentialProvider
|
||||
const service = new TerminalService(
|
||||
{ client: remote.client, baseUrl: () => 'https://remote.internal', includeLocalCredentials },
|
||||
{ client: remote.client, baseUrl: () => 'https://remote.internal', includeLocalEnv },
|
||||
credentialProvider,
|
||||
stubRepoEnvService(),
|
||||
createStubRepoEnvService(),
|
||||
)
|
||||
return { service, credentialProvider, ...remote }
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ import { TerminalService } from '../../src/services/terminal'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import type { RepoEnvService } from '../../src/services/repo-env'
|
||||
import { startWebSocketServer, type WebSocketTestServer } from '../helpers/websocket-server'
|
||||
import { rawWebSocketHandshake } from '../helpers/raw-websocket-handshake'
|
||||
import { createStubRepoEnvService } from '../helpers/stub-repo-env-service'
|
||||
|
||||
vi.mock('../../src/services/repo', () => ({
|
||||
resolveRepoOrAssistant: vi.fn(),
|
||||
@@ -80,9 +80,9 @@ upstreamApp.get(
|
||||
)
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
{ client: openCodeClient, baseUrl: () => upstreamBase, includeLocalCredentials: true },
|
||||
{ client: openCodeClient, baseUrl: () => upstreamBase, includeLocalEnv: true },
|
||||
credentialProvider,
|
||||
{ resolveForDirectory: async () => ({ env: {}, maskValues: [], missing: [] }) } as unknown as RepoEnvService,
|
||||
createStubRepoEnvService(),
|
||||
)
|
||||
|
||||
const managerApp = new Hono()
|
||||
|
||||
@@ -145,6 +145,35 @@ describe('secret routes', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects an invalid JSON body', async () => {
|
||||
const global = await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: '{not json',
|
||||
})
|
||||
expect(global.status).toBe(400)
|
||||
expect(await global.json()).toEqual({ error: 'Invalid JSON' })
|
||||
|
||||
const repoId = seedRepo(db)
|
||||
const repo = await app.request(`/repos/${repoId}/secrets/token`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: '{not json',
|
||||
})
|
||||
expect(repo.status).toBe(400)
|
||||
expect(await repo.json()).toEqual({ error: 'Invalid JSON' })
|
||||
})
|
||||
|
||||
it('rejects a body that fails validation', async () => {
|
||||
const res = await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: '' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
expect(await res.json()).toMatchObject({ error: expect.any(String) })
|
||||
})
|
||||
|
||||
it('deletes a global secret and returns 404 when missing', async () => {
|
||||
await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
|
||||
@@ -36,6 +36,22 @@ describe('RepoProjectFileSchema env', () => {
|
||||
expect(parseEnv({ OPENCODE_TOKEN: 'x' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects git authentication names with an actionable message', () => {
|
||||
for (const name of ['GH_TOKEN', 'GITHUB_TOKEN', 'GIT_AUTHOR_NAME', 'git_committer_email']) {
|
||||
const result = parseEnv({ [name]: 'x' })
|
||||
|
||||
expect(result.success, name).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toBe(
|
||||
`${name} is reserved for git authentication; map the value in a local env file or use a secret instead`,
|
||||
)
|
||||
expect(result.error.issues[0]?.path).toEqual(['env', name])
|
||||
}
|
||||
}
|
||||
expect(parseEnv({ GITHUB_ACTIONS_SUMMARY: 'x' }).success).toBe(false)
|
||||
expect(parseEnv({ GITLAB_TOKEN: 'x' }).success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an invalid environment variable name with an actionable message', () => {
|
||||
const result = parseEnv({ '1BAD': 'x' })
|
||||
|
||||
|
||||
@@ -3,9 +3,41 @@ import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
import { loadGeneratedPlugin, type ToolExecuteAfterEvent } from '../helpers/opencode-plugin-context'
|
||||
import { SANDBOX_SHELL_STATE_KEY } from '../../src/services/opencode-plugin-state'
|
||||
import {
|
||||
loadGeneratedPlugin,
|
||||
type GeneratedPlugin,
|
||||
type GeneratedTool,
|
||||
type GeneratedToolExecuteContext,
|
||||
type ShellCreateBeforeEvent,
|
||||
type ToolExecuteAfterEvent,
|
||||
} from '../helpers/opencode-plugin-context'
|
||||
|
||||
const INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
const MASK_STATE_KEY = Symbol.for('ocm-secret-masks.v1')
|
||||
const PLAN_NAME = 'ocm-session-0123456789ab'
|
||||
|
||||
type MaskState = { byCwd: Map<string, string[]>; version: number; unionVersion: number; union: string[] }
|
||||
|
||||
type ShellSandboxState = { inFlightSandboxedCommands: Map<string, number> }
|
||||
|
||||
function maskStateForTests(): MaskState | undefined {
|
||||
return (globalThis as Record<symbol, unknown>)[MASK_STATE_KEY] as MaskState | undefined
|
||||
}
|
||||
|
||||
function shellSandboxStateForTests(): ShellSandboxState | undefined {
|
||||
return (globalThis as Record<symbol, unknown>)[Symbol.for(SANDBOX_SHELL_STATE_KEY)] as ShellSandboxState | undefined
|
||||
}
|
||||
|
||||
function shellTool(plugin: GeneratedPlugin, execute: (input: unknown, context: GeneratedToolExecuteContext) => Promise<unknown>): GeneratedTool {
|
||||
const tool = plugin.applyToolTransforms([{ name: 'shell', execute }]).find((candidate) => candidate.name === 'shell')
|
||||
if (!tool) throw new Error('the shell tool was not found after transforms')
|
||||
return tool
|
||||
}
|
||||
|
||||
function shellCreateEvent(command: string, cwd: string): ShellCreateBeforeEvent {
|
||||
return { command, cwd, env: {} }
|
||||
}
|
||||
|
||||
describe('ocm-gh-env plugin', () => {
|
||||
let configHome: string
|
||||
@@ -41,6 +73,9 @@ describe('ocm-gh-env plugin', () => {
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
delete (globalThis as Record<symbol, unknown>)[MASK_STATE_KEY]
|
||||
delete (globalThis as Record<symbol, unknown>)[Symbol.for(SANDBOX_SHELL_STATE_KEY)]
|
||||
delete process.env.OCM_SANDBOX_ENFORCED
|
||||
delete process.env.OCM_INTERNAL_API_URL
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
await fs.rm(configHome, { recursive: true, force: true })
|
||||
@@ -215,18 +250,6 @@ describe('ocm-gh-env plugin', () => {
|
||||
expect(event.result).toEqual({ output: 'token ***' })
|
||||
})
|
||||
|
||||
it('replaces overlapping mask values longest first', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['abc', 'abcdef'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result: { output: 'abcdef' } }
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: '***' })
|
||||
})
|
||||
|
||||
it('leaves error results untouched', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['s3cret-value'] })
|
||||
const plugin = await loadPlugin()
|
||||
@@ -253,7 +276,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
expect(event.result).toBe(result)
|
||||
})
|
||||
|
||||
it('keeps masking values learned earlier even after they rotate out of the response', async () => {
|
||||
it('replaces the masks for a cwd instead of keeping values that rotated out', async () => {
|
||||
const realNow = Date.now
|
||||
const fetchMock = stubShellEnvFetch({ env: {}, mask: ['first-secret'] })
|
||||
const plugin = await loadPlugin()
|
||||
@@ -267,9 +290,112 @@ describe('ocm-gh-env plugin', () => {
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: 'first-secret and ***' })
|
||||
expect(maskStateForTests()?.byCwd.get('/repo')).toEqual(['second-secret'])
|
||||
})
|
||||
|
||||
it('keeps masks per cwd and masks a result with the masks of the cwd its shell ran in', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((url: URL) => {
|
||||
const mask = String(url).includes('%2Frepo-a') ? ['a-secret'] : ['b-secret']
|
||||
return Promise.resolve({ ok: true, json: async () => ({ env: {}, mask }) })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo-a', env: {} })
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo-b', env: {} })
|
||||
|
||||
const fromA: ToolExecuteAfterEvent = {
|
||||
tool: 'shell',
|
||||
status: 'completed',
|
||||
input: { command: 'ls', workdir: '/repo-a' },
|
||||
result: { output: 'a-secret and b-secret' },
|
||||
}
|
||||
await plugin.triggerToolExecuteAfter(fromA)
|
||||
|
||||
expect(fromA.result).toEqual({ output: '*** and b-secret' })
|
||||
})
|
||||
|
||||
it('masks a result without a cwd with the union of the current per-cwd masks', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((url: URL) => {
|
||||
const mask = String(url).includes('%2Frepo-a') ? ['a-secret'] : ['b-secret']
|
||||
return Promise.resolve({ ok: true, json: async () => ({ env: {}, mask }) })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo-a', env: {} })
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo-b', env: {} })
|
||||
|
||||
const event: ToolExecuteAfterEvent = {
|
||||
tool: 'read',
|
||||
status: 'completed',
|
||||
result: { output: 'a-secret and b-secret' },
|
||||
}
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: '*** and ***' })
|
||||
})
|
||||
|
||||
it('masks overlapping values longest first without sorting per string', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['abc', 'abcdef', 'abc'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
expect(maskStateForTests()?.byCwd.get('/repo')).toEqual(['abcdef', 'abc'])
|
||||
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result: { output: 'abcdef' } }
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: '***' })
|
||||
})
|
||||
|
||||
for (const order of ['gh-env first', 'sandbox first'] as const) {
|
||||
it(`lets a sandboxed shell register the plan masks and skips the repository env (${order})`, async () => {
|
||||
process.env.OCM_SANDBOX_ENFORCED = 'true'
|
||||
const shellEnvCalls: string[] = []
|
||||
vi.stubGlobal('fetch', vi.fn().mockImplementation((url: string) => {
|
||||
const target = String(url)
|
||||
if (target.includes('/sandbox/sessions/')) {
|
||||
return Promise.resolve({ ok: true, status: 200, json: async () => ({ sandboxed: true, source: 'default', since: 1 }) })
|
||||
}
|
||||
if (target.endsWith('/sandbox/shell')) {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ mode: 'sandbox', workdir: '/repo', name: PLAN_NAME, mask: ['plan-secret'] }),
|
||||
})
|
||||
}
|
||||
shellEnvCalls.push(target)
|
||||
return Promise.resolve({ ok: true, json: async () => ({ env: { GH_TOKEN: 'ghp' }, mask: ['repo-secret'] }) })
|
||||
}))
|
||||
const ghEnv = await loadPlugin()
|
||||
const sandbox = await loadGeneratedPlugin(path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js'))
|
||||
const base = vi.fn().mockImplementation(async (input: { command: string }) => {
|
||||
const event = shellCreateEvent(input.command, '/repo')
|
||||
if (order === 'gh-env first') {
|
||||
await ghEnv.triggerShellCreateBefore(event)
|
||||
await sandbox.triggerShellCreateBefore(event)
|
||||
} else {
|
||||
await sandbox.triggerShellCreateBefore(event)
|
||||
await ghEnv.triggerShellCreateBefore(event)
|
||||
}
|
||||
return { output: 'ok' }
|
||||
})
|
||||
const shell = shellTool(sandbox, base)
|
||||
|
||||
await shell.execute!({ command: 'git push' }, { signal: new AbortController().signal, sessionID: 'ses_test', id: 'call_test' })
|
||||
|
||||
expect(shellEnvCalls).toHaveLength(1)
|
||||
expect(shellEnvCalls[0]).toContain('sandboxed=1')
|
||||
expect(maskStateForTests()?.byCwd.get('/repo')).toEqual(['plan-secret'])
|
||||
expect(shellSandboxStateForTests()?.inFlightSandboxedCommands.size).toBe(0)
|
||||
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result: { output: 'plan-secret and repo-secret' } }
|
||||
await ghEnv.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: '*** and repo-secret' })
|
||||
})
|
||||
}
|
||||
|
||||
it('fails loudly when the generated module does not match the V2 plugin contract', async () => {
|
||||
const modulePath = path.join(configHome, 'not-a-plugin.js')
|
||||
await fs.writeFile(modulePath, 'export default async function () { return {} }')
|
||||
|
||||
@@ -9,8 +9,8 @@ import os from 'os'
|
||||
import {
|
||||
SANDBOX_CLAIM_TIMEOUT_MS,
|
||||
SANDBOX_PLAN_TIMEOUT_MS,
|
||||
SANDBOX_SHELL_STATE_KEY,
|
||||
} from '../../src/services/opencode-sandbox-plugin'
|
||||
import { SANDBOX_SHELL_STATE_KEY } from '../../src/services/opencode-plugin-state'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
import {
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
@@ -138,6 +138,7 @@ type ShellSandboxState = {
|
||||
pendingMarkers: Map<string, { callID: string; sessionID?: string }>
|
||||
sandboxedCallIDs: Set<string>
|
||||
foreignOwners: Map<string, string>
|
||||
inFlightSandboxedCommands: Map<string, number>
|
||||
}
|
||||
|
||||
function shellSandboxState(): ShellSandboxState | undefined {
|
||||
@@ -148,6 +149,18 @@ function clearShellSandboxState(): void {
|
||||
delete (globalThis as Record<symbol, unknown>)[Symbol.for(SANDBOX_SHELL_STATE_KEY)]
|
||||
}
|
||||
|
||||
type MaskState = { byCwd: Map<string, string[]>; version: number; unionVersion: number; union: string[] }
|
||||
|
||||
const MASK_STATE_KEY = Symbol.for('ocm-secret-masks.v1')
|
||||
|
||||
function maskStateForTests(): MaskState | undefined {
|
||||
return (globalThis as Record<symbol, unknown>)[MASK_STATE_KEY] as MaskState | undefined
|
||||
}
|
||||
|
||||
function clearMaskState(): void {
|
||||
delete (globalThis as Record<symbol, unknown>)[MASK_STATE_KEY]
|
||||
}
|
||||
|
||||
type TestClaim = { tier: 'workload' | 'explicit' | 'default'; since: number }
|
||||
type TestProvider = { id: string; claim: (request: { sessionID?: string; directory?: string }) => Promise<TestClaim | null> }
|
||||
type TestDecision = { owner: string | null }
|
||||
@@ -264,6 +277,7 @@ describe('ocm-sandbox plugin', () => {
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
clearShellSandboxState()
|
||||
clearMaskState()
|
||||
clearArbiterRegistry()
|
||||
delete process.env.OCM_INTERNAL_API_URL
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
@@ -457,6 +471,64 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent.env, SANDBOX_SHELL_ENV_FORWARD)?.configurable).toBe(false)
|
||||
})
|
||||
|
||||
it('registers the plan mask values for the spawned cwd', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const fetchMock = managerFetch({
|
||||
session: { sandboxed: true },
|
||||
plan: { body: { mode: 'sandbox', workdir: WORKDIR, name: PLAN_NAME, mask: ['s3cret-value', 'other-value'] } },
|
||||
})
|
||||
const { shell } = await runSandboxedShellCall(plugin, fetchMock)
|
||||
|
||||
await shell.execute!({ command: 'echo sentinel' }, toolContext())
|
||||
|
||||
expect(maskStateForTests()?.byCwd.get(WORKDIR)).toEqual(['s3cret-value', 'other-value'])
|
||||
})
|
||||
|
||||
it('clears the registered masks for the cwd when the plan carries none', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const masked = await runSandboxedShellCall(
|
||||
plugin,
|
||||
managerFetch({
|
||||
session: { sandboxed: true },
|
||||
plan: { body: { mode: 'sandbox', workdir: WORKDIR, name: PLAN_NAME, mask: ['s3cret-value'] } },
|
||||
}),
|
||||
)
|
||||
await masked.shell.execute!({ command: 'echo sentinel' }, toolContext())
|
||||
expect(maskStateForTests()?.byCwd.get(WORKDIR)).toEqual(['s3cret-value'])
|
||||
|
||||
const unmasked = await runSandboxedShellCall(
|
||||
plugin,
|
||||
managerFetch({ session: { sandboxed: true }, plan: { body: { mode: 'sandbox', workdir: WORKDIR, name: PLAN_NAME } } }),
|
||||
)
|
||||
await unmasked.shell.execute!({ command: 'echo other' }, toolContext())
|
||||
|
||||
expect(maskStateForTests()?.byCwd.get(WORKDIR)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('pins the forward list only from the plan instead of a static env list', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const source = await fs.readFile(path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js'), 'utf-8')
|
||||
let pinned: ShellCreateBeforeEvent | undefined
|
||||
const { shell } = await runSandboxedShellCall(
|
||||
plugin,
|
||||
managerFetch({ session: { sandboxed: true }, plan: { body: { mode: 'sandbox', workdir: WORKDIR, name: PLAN_NAME } } }),
|
||||
(marked) => {
|
||||
pinned = shellCreateEvent({
|
||||
command: marked,
|
||||
env: { PATH: '/usr/bin', GH_TOKEN: 'spawn-token', GIT_CONFIG_COUNT: '1' },
|
||||
})
|
||||
return pinned
|
||||
},
|
||||
)
|
||||
|
||||
await shell.execute!({ command: 'echo sentinel' }, toolContext())
|
||||
|
||||
expect(source).not.toContain('FORWARDED_ENV_NAMES')
|
||||
expect(pinned?.env[SANDBOX_SHELL_ENV_FORWARD]).toBe('')
|
||||
expect(pinned?.env.GH_TOKEN).toBe('spawn-token')
|
||||
expect(pinned?.env.GIT_CONFIG_COUNT).toBe('1')
|
||||
})
|
||||
|
||||
it('leaves an unmarked spawn on the host without planning', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const fetchMock = vi.fn()
|
||||
@@ -710,6 +782,22 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(marked).toMatch(/^ocm-sandbox-required-[0-9a-f-]{36} && echo sentinel$/)
|
||||
})
|
||||
|
||||
it('records the sandboxed command as in flight for the duration of the spawn', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const inFlightDuringSpawn: string[][] = []
|
||||
vi.stubGlobal('fetch', managerFetch({ session: { sandboxed: true } }))
|
||||
const shell = shellTool(plugin, vi.fn().mockImplementation(async () => {
|
||||
inFlightDuringSpawn.push([...(shellSandboxState()?.inFlightSandboxedCommands.keys() ?? [])])
|
||||
return { output: 'ok' }
|
||||
}))
|
||||
|
||||
await shell.execute!({ command: 'echo sentinel' }, toolContext())
|
||||
|
||||
expect(inFlightDuringSpawn[0]).toContain('echo sentinel')
|
||||
expect(inFlightDuringSpawn[0]?.some((command) => command.endsWith(' && echo sentinel'))).toBe(true)
|
||||
expect(shellSandboxState()?.inFlightSandboxedCommands.size).toBe(0)
|
||||
})
|
||||
|
||||
it('refuses to run a sandboxed shell call without a command', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const original = vi.fn()
|
||||
|
||||
@@ -11,13 +11,25 @@ import { createGitService } from '../../src/services/git/GitService'
|
||||
import { ProjectConfigService } from '../../src/services/project-config'
|
||||
import { SecretsService } from '../../src/services/secrets'
|
||||
import { RepoEnvService } from '../../src/services/repo-env'
|
||||
import { deleteRepoFiles } from '../../src/services/repo'
|
||||
import { invalidateRepoEnvCache } from '../../src/utils/repo-env-cache'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
import { logger } from '../../src/utils/logger'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
|
||||
vi.mock('../../src/utils/process', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/process')>()
|
||||
return { ...actual, executeCommand: vi.fn(actual.executeCommand) }
|
||||
})
|
||||
|
||||
const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService
|
||||
|
||||
const EMPTY = { env: {}, maskValues: [], missing: [] }
|
||||
const EMPTY = { env: {}, maskValues: [] }
|
||||
|
||||
function topLevelProbes(): number {
|
||||
return vi.mocked(executeCommand).mock.calls.filter(([args]) => args.includes('--show-toplevel')).length
|
||||
}
|
||||
|
||||
describe('RepoEnvService', () => {
|
||||
let db: Database
|
||||
@@ -62,6 +74,7 @@ describe('RepoEnvService', () => {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(executeCommand).mockClear()
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
|
||||
@@ -101,7 +114,6 @@ describe('RepoEnvService', () => {
|
||||
PLAIN: 'literal',
|
||||
})
|
||||
expect(result.maskValues).toEqual(['prod-token'])
|
||||
expect(result.missing).toEqual([])
|
||||
})
|
||||
|
||||
it('returns an empty result for an untrusted mapping', async () => {
|
||||
@@ -161,7 +173,7 @@ describe('RepoEnvService', () => {
|
||||
expect(await repoEnvService.resolveForDirectory(plain)).toEqual(EMPTY)
|
||||
})
|
||||
|
||||
it('reports missing references and resolves them to an empty string', async () => {
|
||||
it('resolves missing references to an empty string', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
@@ -174,7 +186,6 @@ describe('RepoEnvService', () => {
|
||||
const result = await repoEnvService.resolveForDirectory(root)
|
||||
|
||||
expect(result.env).toEqual({ MISSING: '-' })
|
||||
expect(result.missing).toEqual(['secrets.NOPE', 'vars.NOPE2'])
|
||||
})
|
||||
|
||||
it('excludes vars and short secret values from maskValues', async () => {
|
||||
@@ -215,4 +226,111 @@ describe('RepoEnvService', () => {
|
||||
|
||||
warn.mockRestore()
|
||||
})
|
||||
|
||||
describe('caching', () => {
|
||||
async function createTrustedRepo(env: Record<string, string>): Promise<{ root: string; repo: Repo }> {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, env })
|
||||
await trust(root, repo)
|
||||
return { root, repo }
|
||||
}
|
||||
|
||||
it('reuses the directory resolution within the TTL without spawning git', async () => {
|
||||
const { root } = await createTrustedRepo({ PLAIN: 'literal' })
|
||||
|
||||
await repoEnvService.resolveForDirectory(root)
|
||||
const probes = topLevelProbes()
|
||||
expect(probes).toBeGreaterThan(0)
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(root)
|
||||
|
||||
expect(result.env).toEqual({ PLAIN: 'literal' })
|
||||
expect(topLevelProbes()).toBe(probes)
|
||||
})
|
||||
|
||||
it('caches misses for directories without a repository', async () => {
|
||||
const plain = createTempDir('ocm-repo-env-plain-')
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(plain)).toEqual(EMPTY)
|
||||
const probes = topLevelProbes()
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(plain)).toEqual(EMPTY)
|
||||
expect(topLevelProbes()).toBe(probes)
|
||||
})
|
||||
|
||||
it('re-reads the project file when it changes', async () => {
|
||||
const { root, repo } = await createTrustedRepo({ PLAIN: 'first' })
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'first' })
|
||||
const probes = topLevelProbes()
|
||||
|
||||
writeProjectFile(root, { version: 1, env: { PLAIN: 'second-value' } })
|
||||
await trust(root, repo)
|
||||
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'second-value' })
|
||||
expect(topLevelProbes()).toBe(probes)
|
||||
})
|
||||
|
||||
it('applies a trust decision made after the file was cached', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { PLAIN: 'literal' } })
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
|
||||
await trust(root, repo)
|
||||
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'literal' })
|
||||
})
|
||||
|
||||
it('applies secret edits made after the directory was cached', async () => {
|
||||
const { root, repo } = await createTrustedRepo({ TOKEN: '${{ secrets.TOKEN }}' })
|
||||
secretsService.set('secret', repo.id, null, 'TOKEN', 'first-token')
|
||||
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ TOKEN: 'first-token' })
|
||||
|
||||
secretsService.set('secret', repo.id, null, 'TOKEN', 'second-token')
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(root)
|
||||
expect(result.env).toEqual({ TOKEN: 'second-token' })
|
||||
expect(result.maskValues).toEqual(['second-token'])
|
||||
})
|
||||
|
||||
it('invalidates the cached miss when the repository is registered', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { PLAIN: 'literal' } })
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
|
||||
const repo = registerRepo(root)
|
||||
await trust(root, repo)
|
||||
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'literal' })
|
||||
})
|
||||
|
||||
it('invalidates the cached resolution when the repository is deleted', async () => {
|
||||
const { root, repo } = await createTrustedRepo({ PLAIN: 'literal' })
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'literal' })
|
||||
const probes = topLevelProbes()
|
||||
|
||||
await deleteRepoFiles(db, repo.id)
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
expect(topLevelProbes()).toBeGreaterThan(probes)
|
||||
})
|
||||
|
||||
it('invalidates the cached resolution when the repo environment cache is reset', async () => {
|
||||
const { root } = await createTrustedRepo({ PLAIN: 'literal' })
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'literal' })
|
||||
const probes = topLevelProbes()
|
||||
|
||||
invalidateRepoEnvCache()
|
||||
|
||||
expect((await repoEnvService.resolveForDirectory(root)).env).toEqual({ PLAIN: 'literal' })
|
||||
expect(topLevelProbes()).toBeGreaterThan(probes)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { ENV, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import { migrate } from '../../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../../src/db/migrations'
|
||||
import { SettingsService } from '../../../src/services/settings'
|
||||
@@ -526,6 +527,29 @@ describe('SandboxRuntimeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards the sandbox git credentials from the plan only when the toggle allows them', async () => {
|
||||
enableEnforcement()
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_plan_token' } as GitCredential],
|
||||
sandbox: { enabled: true, gitCredentials: true },
|
||||
})
|
||||
installFakeMsb(new Map([[VM_NAME, vm()]]))
|
||||
|
||||
const withCredentials = await service.planShell(repoADir, shellTarget(repoADir))
|
||||
|
||||
expect(withCredentials).toMatchObject({
|
||||
mode: 'sandbox',
|
||||
env: { GIT_CONFIG_COUNT: '1', GH_TOKEN: 'ghp_plan_token' },
|
||||
})
|
||||
|
||||
settingsService.updateSettings({ sandbox: { enabled: true, gitCredentials: false } })
|
||||
const withoutCredentials = await service.planShell(repoADir, shellTarget(repoADir))
|
||||
|
||||
expect(withoutCredentials.mode).toBe('sandbox')
|
||||
expect(withoutCredentials).not.toHaveProperty('env.GH_TOKEN')
|
||||
expect(withoutCredentials).not.toHaveProperty('env.GIT_CONFIG_COUNT')
|
||||
})
|
||||
|
||||
it('includes the repository env in the sandbox plan env after the git env', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
@@ -542,7 +566,6 @@ describe('SandboxRuntimeService', () => {
|
||||
resolveForDirectory: vi.fn(async () => ({
|
||||
env: { REPO_SECRET: 's3cret', GIT_AUTHOR_NAME: 'Repo User' },
|
||||
maskValues: ['s3cret'],
|
||||
missing: [],
|
||||
})),
|
||||
} as unknown as RepoEnvService
|
||||
const withRepoEnv = new SandboxRuntimeService(db, repoEnvService)
|
||||
@@ -560,6 +583,7 @@ describe('SandboxRuntimeService', () => {
|
||||
GIT_COMMITTER_EMAIL: 'local@example.com',
|
||||
REPO_SECRET: 's3cret',
|
||||
},
|
||||
mask: ['s3cret'],
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from 'node:path'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { sessionSandboxName } from '../../../src/services/sandbox/command'
|
||||
import {
|
||||
SANDBOX_FORWARDED_ENV_NAMES,
|
||||
SANDBOX_MAX_FORWARDED_GIT_CONFIGS,
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
SANDBOX_SHELL_ENV_NAME,
|
||||
SANDBOX_SHELL_ENV_WORKDIR,
|
||||
@@ -38,8 +38,22 @@ function writeArgvCapturingFakeMsb(msbPath: string, captureFile: string): void {
|
||||
|
||||
function sandboxShellEnv(overrides: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env }
|
||||
for (const name of SANDBOX_FORWARDED_ENV_NAMES) delete env[name]
|
||||
delete env[SANDBOX_SHELL_ENV_FORWARD]
|
||||
const inherited = [
|
||||
'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',
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
]
|
||||
for (const name of inherited) delete env[name]
|
||||
return { ...env, ...overrides }
|
||||
}
|
||||
|
||||
@@ -98,7 +112,7 @@ describe('sandbox shell shim', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards the planned names and the always-forwarded git names as -e pairs, ahead of the command', async () => {
|
||||
it('forwards exactly the plan-approved names 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')
|
||||
@@ -125,6 +139,7 @@ describe('sandbox shell shim', () => {
|
||||
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
|
||||
GIT_CONFIG_VALUE_0: extraheaderValue,
|
||||
GH_TOKEN: 'inherited-must-not-be-forwarded',
|
||||
GIT_AUTHOR_NAME: 'Inherited Author',
|
||||
OCM_INTERNAL_TOKEN: 'must-not-be-forwarded',
|
||||
}),
|
||||
})
|
||||
@@ -139,9 +154,10 @@ describe('sandbox shell shim', () => {
|
||||
|
||||
const separatorIndex = argv.indexOf('--')
|
||||
expect(argv.slice(separatorIndex)).toEqual(['--', 'sh', '-c', 'echo -e sentinel'])
|
||||
expect(argv.slice(0, separatorIndex).filter((element) => element === '-e')).toHaveLength(4)
|
||||
expect(argv.slice(0, separatorIndex).filter((element) => element === '-e')).toHaveLength(3)
|
||||
|
||||
expect(argv).toContain('GH_TOKEN=inherited-must-not-be-forwarded')
|
||||
expect(argv.some((element) => element.startsWith('GH_TOKEN='))).toBe(false)
|
||||
expect(argv.some((element) => element.startsWith('GIT_AUTHOR_NAME='))).toBe(false)
|
||||
expect(argv.some((element) => element.startsWith('OCM_INTERNAL_TOKEN='))).toBe(false)
|
||||
} finally {
|
||||
if (originalMsbPath === undefined) {
|
||||
@@ -154,6 +170,55 @@ describe('sandbox shell shim', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards nothing but the plan-approved names when the spawn env carries git and GitHub credentials', 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 result = spawnSync(shimPath, ['-c', 'echo sentinel'], {
|
||||
encoding: 'utf8',
|
||||
env: sandboxShellEnv({
|
||||
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
|
||||
[SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME,
|
||||
GH_TOKEN: 'inherited-gh-token',
|
||||
GITHUB_TOKEN: 'inherited-github-token',
|
||||
GIT_CONFIG_COUNT: '1',
|
||||
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
|
||||
GIT_CONFIG_VALUE_0: 'AUTHORIZATION: basic inherited',
|
||||
GIT_AUTHOR_NAME: 'Inherited Author',
|
||||
GIT_COMMITTER_EMAIL: 'inherited@example.com',
|
||||
}),
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
|
||||
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
|
||||
|
||||
expect(argv.filter((element) => element === '-e')).toHaveLength(0)
|
||||
expect(argv).not.toContain('GH_TOKEN=inherited-gh-token')
|
||||
expect(argv).not.toContain('GITHUB_TOKEN=inherited-github-token')
|
||||
expect(argv).not.toContain('GIT_CONFIG_COUNT=1')
|
||||
} 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('skips reserved and invalid forward names without executing anything', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-names-'))
|
||||
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, vi } from 'vitest'
|
||||
import { TerminalService, TerminalNotFoundError } from '../../src/services/terminal'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import type { RepoEnvService } from '../../src/services/repo-env'
|
||||
import { createStubRepoEnvService } from '../helpers/stub-repo-env-service'
|
||||
|
||||
interface PtyRecord {
|
||||
id: string
|
||||
@@ -46,23 +46,17 @@ function createCredentialProvider(shellEnv: Record<string, string> = {}): Creden
|
||||
return { getGhCliEnv: vi.fn(() => shellEnv) } as unknown as CredentialProvider
|
||||
}
|
||||
|
||||
function createRepoEnvService(env: Record<string, string> = {}): RepoEnvService {
|
||||
return {
|
||||
resolveForDirectory: vi.fn(async () => ({ env, maskValues: [], missing: [] })),
|
||||
} as unknown as RepoEnvService
|
||||
}
|
||||
|
||||
function createTerminalService(
|
||||
client: OpenCodeClient,
|
||||
provider: CredentialProvider,
|
||||
openSocket: (url: string) => WebSocket = createSocketFactory().openSocket,
|
||||
baseUrl = 'http://127.0.0.1:5551',
|
||||
includeLocalCredentials = true,
|
||||
includeLocalEnv = true,
|
||||
): TerminalService {
|
||||
return new TerminalService(
|
||||
{ client, baseUrl: () => baseUrl, includeLocalCredentials },
|
||||
{ client, baseUrl: () => baseUrl, includeLocalEnv },
|
||||
provider,
|
||||
createRepoEnvService(),
|
||||
createStubRepoEnvService(),
|
||||
openSocket,
|
||||
)
|
||||
}
|
||||
@@ -239,9 +233,9 @@ describe('TerminalService', () => {
|
||||
data: createPty({ id: 'pty-new', title: 'Terminal' }),
|
||||
}))
|
||||
const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh', SHARED: 'gh' })
|
||||
const repoEnvService = createRepoEnvService({ REPO_VAR: 'repo', SHARED: 'repo' })
|
||||
const repoEnvService = createStubRepoEnvService({ REPO_VAR: 'repo', SHARED: 'repo' })
|
||||
const service = new TerminalService(
|
||||
{ client: createClient({ create }), baseUrl: () => 'http://127.0.0.1:5551', includeLocalCredentials: true },
|
||||
{ client: createClient({ create }), baseUrl: () => 'http://127.0.0.1:5551', includeLocalEnv: true },
|
||||
credentialProvider,
|
||||
repoEnvService,
|
||||
)
|
||||
@@ -445,23 +439,23 @@ describe('TerminalService', () => {
|
||||
})
|
||||
|
||||
describe('remote target', () => {
|
||||
it('does not inject local GitHub credentials when creating a terminal', async () => {
|
||||
it('does not inject local GitHub credentials or repository environment when creating a terminal', async () => {
|
||||
const create = vi.fn(async () => ({
|
||||
location: { directory: '/repo' },
|
||||
data: createPty({ id: 'pty-remote', title: 'Terminal' }),
|
||||
}))
|
||||
const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh' })
|
||||
const service = createTerminalService(
|
||||
createClient({ create }),
|
||||
const repoEnvService = createStubRepoEnvService({ REPO_VAR: 'repo' })
|
||||
const service = new TerminalService(
|
||||
{ client: createClient({ create }), baseUrl: () => 'https://remote.internal', includeLocalEnv: false },
|
||||
credentialProvider,
|
||||
undefined,
|
||||
'https://remote.internal',
|
||||
false,
|
||||
repoEnvService,
|
||||
)
|
||||
|
||||
await service.create('/repo', { kind: 'shell', name: 'Terminal', env: { FOO: 'bar' } })
|
||||
|
||||
expect(credentialProvider.getGhCliEnv).not.toHaveBeenCalled()
|
||||
expect(repoEnvService.resolveForDirectory).not.toHaveBeenCalled()
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({ env: { FOO: 'bar' } }))
|
||||
})
|
||||
|
||||
@@ -507,7 +501,7 @@ describe('TerminalService', () => {
|
||||
const remote = service.forTarget({
|
||||
client: remoteClient,
|
||||
baseUrl: () => 'https://remote.internal',
|
||||
includeLocalCredentials: false,
|
||||
includeLocalEnv: false,
|
||||
})
|
||||
|
||||
await remote.connect('/repo', 'pty-1', undefined, createPeer())
|
||||
|
||||
@@ -68,25 +68,28 @@ describe('interpolateEnvExpressions', () => {
|
||||
it('replaces references and interpolates inside a larger string', () => {
|
||||
expect(interpolateEnvExpressions('https://${{ vars.HOST }}/${{ secrets.TOKEN }}', lookup)).toEqual({
|
||||
value: 'https://example.com/super-secret',
|
||||
missing: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves a missing reference to an empty string and reports it', () => {
|
||||
it('resolves a missing reference to an empty string', () => {
|
||||
expect(interpolateEnvExpressions('x-${{ secrets.MISSING }}-y', lookup)).toEqual({
|
||||
value: 'x--y',
|
||||
missing: [{ context: 'secrets', name: 'MISSING' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves an unsupported expression untouched', () => {
|
||||
expect(interpolateEnvExpressions('${{ github.sha }}', lookup)).toEqual({
|
||||
value: '${{ github.sha }}',
|
||||
missing: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves an expression with an invalid name untouched', () => {
|
||||
expect(interpolateEnvExpressions('${{ secrets.1BAD }}', lookup)).toEqual({
|
||||
value: '${{ secrets.1BAD }}',
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves a literal value untouched', () => {
|
||||
expect(interpolateEnvExpressions('literal', lookup)).toEqual({ value: 'literal', missing: [] })
|
||||
expect(interpolateEnvExpressions('literal', lookup)).toEqual({ value: 'literal' })
|
||||
})
|
||||
})
|
||||
@@ -2,14 +2,14 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type { SecretEntry, SecretKind } from '@opencode-manager/shared/schemas'
|
||||
import { deleteSecret, listSecrets, setSecret, type SecretScope } from '@/api/secrets'
|
||||
|
||||
export interface SetSecretVariables {
|
||||
interface SetSecretVariables {
|
||||
kind: SecretKind
|
||||
name: string
|
||||
value: string
|
||||
environment?: string
|
||||
}
|
||||
|
||||
export interface DeleteSecretVariables {
|
||||
interface DeleteSecretVariables {
|
||||
kind: SecretKind
|
||||
name: string
|
||||
environment?: string
|
||||
@@ -19,7 +19,7 @@ function scopeKey(scope: SecretScope): string {
|
||||
return scope.scope === 'global' ? 'global' : `repo:${scope.repoId}`
|
||||
}
|
||||
|
||||
export function secretsQueryKey(scope: SecretScope, kind: SecretKind) {
|
||||
function secretsQueryKey(scope: SecretScope, kind: SecretKind) {
|
||||
return ['secrets', scopeKey(scope), kind] as const
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { TerminalInfoSchema } from './terminal'
|
||||
import { EnvironmentNameSchema, isReservedEnvName } from './secrets'
|
||||
import { ENV_NAME_PATTERN, EnvironmentNameSchema, isReservedEnvName } from './secrets'
|
||||
import { parseEnvExpressionReferences } from '../utils/env-expressions'
|
||||
|
||||
export const ProjectActionIconSchema = z.enum([
|
||||
@@ -34,7 +34,15 @@ export const ProjectItemSourceSchema = z.enum(['personal', 'repo'])
|
||||
|
||||
export const REPO_PROJECT_ENV_MAX_ENTRIES = 100
|
||||
|
||||
export const REPO_PROJECT_ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
const REPO_PROJECT_ENV_RESERVED_NAMES = ['GH_TOKEN'] as const
|
||||
|
||||
const REPO_PROJECT_ENV_RESERVED_PREFIXES = ['GITHUB_', 'GIT_'] as const
|
||||
|
||||
function isRepoProjectEnvGitReserved(name: string): boolean {
|
||||
const normalized = name.toUpperCase()
|
||||
if ((REPO_PROJECT_ENV_RESERVED_NAMES as readonly string[]).includes(normalized)) return true
|
||||
return REPO_PROJECT_ENV_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
export const RepoProjectEnvValueSchema = z
|
||||
.string()
|
||||
@@ -50,10 +58,16 @@ export const RepoProjectEnvSchema = z
|
||||
.record(z.string(), RepoProjectEnvValueSchema)
|
||||
.superRefine((env, ctx) => {
|
||||
for (const key of Object.keys(env)) {
|
||||
if (!REPO_PROJECT_ENV_NAME_PATTERN.test(key)) {
|
||||
if (!ENV_NAME_PATTERN.test(key)) {
|
||||
ctx.addIssue({ code: 'custom', message: `${key} is not a valid environment variable name`, path: [key] })
|
||||
} else if (isReservedEnvName(key)) {
|
||||
ctx.addIssue({ code: 'custom', message: `${key} is reserved for Manager or the runtime`, path: [key] })
|
||||
} else if (isRepoProjectEnvGitReserved(key)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `${key} is reserved for git authentication; map the value in a local env file or use a secret instead`,
|
||||
path: [key],
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -164,7 +178,6 @@ export type ProjectAction = z.infer<typeof ProjectActionSchema>
|
||||
export type WorktreeSetupCommands = z.infer<typeof WorktreeSetupCommandsSchema>
|
||||
export type ProjectItemSource = z.infer<typeof ProjectItemSourceSchema>
|
||||
export type RepoProjectFile = z.infer<typeof RepoProjectFileSchema>
|
||||
export type RepoProjectEnv = z.infer<typeof RepoProjectEnvSchema>
|
||||
export type ProjectConfigResponse = z.infer<typeof ProjectConfigResponseSchema>
|
||||
export type UpdateProjectActionsRequest = z.infer<typeof UpdateProjectActionsRequestSchema>
|
||||
export type UpdateWorktreeSetupRequest = z.infer<typeof UpdateWorktreeSetupRequestSchema>
|
||||
|
||||
@@ -7,8 +7,17 @@ export type SecretKind = z.infer<typeof SecretKindSchema>
|
||||
|
||||
export const SECRET_VALUE_MAX_BYTES = 48 * 1024
|
||||
|
||||
export const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
|
||||
const RESERVED_ENV_PREFIXES = ['OCM_', 'OPENCODE_', 'GIT_CONFIG_', 'MSB_', 'LD_'] as const
|
||||
|
||||
/**
|
||||
* Prefixes the sandbox owns: a plan-provided or forwarded variable using one of
|
||||
* them could replace the sandbox control variables, so they never cross into a
|
||||
* microVM from a plan.
|
||||
*/
|
||||
export const SANDBOX_CONTROL_ENV_PREFIXES = ['OCM_', 'MSB_'] as const satisfies readonly (typeof RESERVED_ENV_PREFIXES)[number][]
|
||||
|
||||
const RESERVED_ENV_NAMES = ['PATH', 'HOME', 'NODE_OPTIONS'] as const
|
||||
|
||||
const BLOCKED_ENV_NAMES = new Set<string>(BLOCKED_SERVER_ENV_KEYS)
|
||||
@@ -24,7 +33,7 @@ export const SecretNameSchema = z
|
||||
.string()
|
||||
.max(255, 'Name must be at most 255 characters')
|
||||
.regex(
|
||||
/^[A-Za-z_][A-Za-z0-9_]*$/,
|
||||
ENV_NAME_PATTERN,
|
||||
'Name must start with a letter or underscore and contain only letters, numbers, and underscores',
|
||||
)
|
||||
.refine((name) => !name.toUpperCase().startsWith('GITHUB_'), 'Name must not start with GITHUB_')
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ENV_NAME_PATTERN } from '../schemas/secrets'
|
||||
|
||||
export type EnvExpressionContext = 'secrets' | 'vars'
|
||||
|
||||
export interface EnvExpressionReference {
|
||||
@@ -11,7 +13,7 @@ export type ParseEnvExpressionReferencesResult =
|
||||
|
||||
const ENV_EXPRESSION_PATTERN = /\$\{\{([\s\S]*?)\}\}/g
|
||||
|
||||
const ENV_EXPRESSION_REFERENCE_PATTERN = /^\s*(secrets|vars)\.([A-Za-z_][A-Za-z0-9_]*)\s*$/i
|
||||
const ENV_EXPRESSION_REFERENCE_PATTERN = /^\s*(secrets|vars)\.(\S+)\s*$/i
|
||||
|
||||
function toReference(match: RegExpExecArray): EnvExpressionReference {
|
||||
return {
|
||||
@@ -20,6 +22,12 @@ function toReference(match: RegExpExecArray): EnvExpressionReference {
|
||||
}
|
||||
}
|
||||
|
||||
function matchReference(inner: string): EnvExpressionReference | null {
|
||||
const match = ENV_EXPRESSION_REFERENCE_PATTERN.exec(inner)
|
||||
if (!match || !ENV_NAME_PATTERN.test(match[2] ?? '')) return null
|
||||
return toReference(match)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses every `${{ ... }}` occurrence in a value, accepting only
|
||||
* `secrets.<NAME>` and `vars.<NAME>` references. The context is
|
||||
@@ -29,14 +37,14 @@ export function parseEnvExpressionReferences(value: string): ParseEnvExpressionR
|
||||
const references: EnvExpressionReference[] = []
|
||||
|
||||
for (const expression of value.matchAll(ENV_EXPRESSION_PATTERN)) {
|
||||
const reference = ENV_EXPRESSION_REFERENCE_PATTERN.exec(expression[1] ?? '')
|
||||
const reference = matchReference(expression[1] ?? '')
|
||||
if (!reference) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Unsupported expression "${expression[0]}": only secrets.<NAME> and vars.<NAME> are supported`,
|
||||
}
|
||||
}
|
||||
references.push(toReference(reference))
|
||||
references.push(reference)
|
||||
}
|
||||
|
||||
return { ok: true, references }
|
||||
@@ -45,28 +53,21 @@ export function parseEnvExpressionReferences(value: string): ParseEnvExpressionR
|
||||
/**
|
||||
* Replaces every `${{ secrets.<NAME> }}` / `${{ vars.<NAME> }}` occurrence with
|
||||
* the value returned by `lookup`. A reference that resolves to `undefined`
|
||||
* becomes an empty string and is reported in `missing`, matching GitHub Actions.
|
||||
* Unsupported expressions are left untouched.
|
||||
* becomes an empty string, matching GitHub Actions. Unsupported expressions and
|
||||
* expressions with an invalid name are left untouched.
|
||||
*/
|
||||
export function interpolateEnvExpressions(
|
||||
value: string,
|
||||
lookup: (reference: EnvExpressionReference) => string | undefined,
|
||||
): { value: string; missing: EnvExpressionReference[] } {
|
||||
const missing: EnvExpressionReference[] = []
|
||||
|
||||
): { value: string } {
|
||||
const interpolated = value.replace(ENV_EXPRESSION_PATTERN, (expression, inner: string) => {
|
||||
const match = ENV_EXPRESSION_REFERENCE_PATTERN.exec(inner)
|
||||
if (!match) {
|
||||
const reference = matchReference(inner)
|
||||
if (!reference) {
|
||||
return expression
|
||||
}
|
||||
const reference = toReference(match)
|
||||
const resolved = lookup(reference)
|
||||
if (resolved === undefined) {
|
||||
missing.push(reference)
|
||||
return ''
|
||||
}
|
||||
return resolved
|
||||
return resolved === undefined ? '' : resolved
|
||||
})
|
||||
|
||||
return { value: interpolated, missing }
|
||||
return { value: interpolated }
|
||||
}
|
||||
Reference in new issue
Block a user