mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(secrets): repository secrets and variables injected into agent shells and terminals
Add a GitHub Actions-style store for secrets and variables so tests can read
credentials from the environment without .env files in the repo.
- secrets table keyed by kind, repo (NULL for global) and environment;
secrets are encrypted with encryptSecret and write-only, variables are plain
text. Names follow GitHub's rules and reject Manager-reserved names.
- Global (/api/secrets, /api/variables) and repo
(/api/repos/:id/secrets|variables) routes.
- The trusted .ocm/project.json gains environment and env fields that map
names to ${{ secrets.X }} / ${{ vars.X }} expressions. Both are part of the
trust hash; files without them hash as before, so existing trust survives.
- RepoEnvService.resolveForDirectory resolves the repo and approved mapping
for any directory, including worktrees outside the repo folder, with
environment > repo > global precedence. It never throws.
- /api/internal/shell-env replaces /git-credentials/gh-env and feeds the
ocm-gh-env plugin, the sandbox shell plan and TerminalService.create.
- The plugin masks injected secret values as *** in completed tool results.
- The sandbox shell plan is now the only source of the guest environment: the
plugin pins OCM_SANDBOX_FORWARD_ENV and the shim forwards only those names.
This commit is contained in:
1 parent
b431c121a2
commit
e0331b43bf
47 files changed
+2073
-156
No files matched your search
@@ -0,0 +1,26 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181400-secrets',
|
||||
up(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS secrets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('secret','variable')),
|
||||
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
|
||||
environment TEXT NOT NULL DEFAULT '',
|
||||
name TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_secrets_scope ON secrets(kind, COALESCE(repo_id, 0), environment, name)')
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS secrets')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -37,6 +37,7 @@ import migration202610181200 from './202610181200-opencode-servers'
|
||||
import migration202610181300 from './202610181300-session-server-scope'
|
||||
import migration202610181310 from './202610181310-multi-run-targets'
|
||||
import migration202610181320 from './202610181320-remote-schedule-targets'
|
||||
import migration202610181400 from './202610181400-secrets'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -77,4 +78,5 @@ export const allMigrations: Migration[] = [
|
||||
migration202610181300,
|
||||
migration202610181310,
|
||||
migration202610181320,
|
||||
migration202610181400,
|
||||
]
|
||||
@@ -351,6 +351,7 @@ export function deleteRepo(db: Database, id: number): void {
|
||||
db.prepare('DELETE FROM multi_run_fusions WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
|
||||
db.prepare('DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
|
||||
db.prepare('DELETE FROM multi_runs WHERE repo_id = ?').run(id)
|
||||
db.prepare('DELETE FROM secrets WHERE repo_id = ?').run(id)
|
||||
for (const table of TABLES_WITH_REPO_ID) {
|
||||
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
|
||||
}
|
||||
|
||||
+13
-5
@@ -46,6 +46,7 @@ import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
|
||||
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
|
||||
import { createGlobalSecretRoutes } from './routes/secrets'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
@@ -76,6 +77,8 @@ import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||
import { CredentialProvider } from './services/credential-provider'
|
||||
import { TerminalService } from './services/terminal'
|
||||
import { ProjectConfigService } from './services/project-config'
|
||||
import { SecretsService } from './services/secrets'
|
||||
import { RepoEnvService } from './services/repo-env'
|
||||
import { RepoWorkspaceService } from './services/repo-workspace'
|
||||
import { createGitService } from './services/git/GitService'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
@@ -141,6 +144,10 @@ import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const secretsService = new SecretsService(db)
|
||||
const repoEnvService = new RepoEnvService(db, projectConfigService, secretsService)
|
||||
let openCodeSupervisor: OpenCodeSupervisor | undefined
|
||||
async function ensureOpenCodeConfigFileExists(): Promise<void> {
|
||||
await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
|
||||
@@ -239,7 +246,7 @@ try {
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
void new SandboxRuntimeService(db).prepareSandboxOnBoot().catch((error) => {
|
||||
void new SandboxRuntimeService(db, repoEnvService).prepareSandboxOnBoot().catch((error) => {
|
||||
logger.warn('Sandbox preparation failed:', error)
|
||||
})
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
@@ -260,6 +267,7 @@ const terminalService = new TerminalService(
|
||||
includeLocalCredentials: true,
|
||||
},
|
||||
new CredentialProvider(db),
|
||||
repoEnvService,
|
||||
)
|
||||
const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
const connection = opencodeServerRegistry.getConnection(serverId)
|
||||
@@ -269,8 +277,6 @@ const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
includeLocalCredentials: false,
|
||||
})
|
||||
}
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry)
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
@@ -385,14 +391,14 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
|
||||
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/repos', createRepoTerminalSocketRoutes(db, gitAuthService, openCodeClient, terminalService, upgradeWebSocket))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, secretsService))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
protectedApi.route('/filesystem', createFilesystemRoutes())
|
||||
@@ -404,6 +410,8 @@ protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
|
||||
protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { CredentialProvider } from '../../services/credential-provider'
|
||||
|
||||
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
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
|
||||
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
|
||||
import { createInternalSessionRoutes } from './sessions'
|
||||
import { createInternalAssistantRoutes } from './assistant'
|
||||
import { createInternalGitCredentialsRoutes } from './git-credentials'
|
||||
import { createInternalShellEnvRoutes } from './shell-env'
|
||||
import { createInternalSandboxRoutes } from './sandbox'
|
||||
import { createInternalSessionArtifactRoutes } from './session-artifacts'
|
||||
import { createSessionGoalRoutes } from '../session-goals'
|
||||
@@ -29,6 +29,7 @@ import type { GitAuthService } from '../../services/git-auth'
|
||||
import type { SessionGoalService } from '../../services/session-goals'
|
||||
import type { MultiRunService } from '../../services/multi-runs'
|
||||
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
|
||||
export function createInternalRoutes(
|
||||
db: Database,
|
||||
@@ -43,6 +44,7 @@ export function createInternalRoutes(
|
||||
multiRuns: MultiRunService,
|
||||
changeWalkthroughService: ChangeWalkthroughService,
|
||||
sessionSandbox: SessionSandboxService,
|
||||
repoEnvService: RepoEnvService,
|
||||
) {
|
||||
const app = new Hono()
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
@@ -64,7 +66,7 @@ export function createInternalRoutes(
|
||||
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
|
||||
app.route('/walkthrough-sessions', createInternalWalkthroughSessionRoutes(changeWalkthroughService))
|
||||
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
|
||||
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
|
||||
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox))
|
||||
app.route('/shell-env', createInternalShellEnvRoutes(db, repoEnvService))
|
||||
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox, repoEnvService))
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
|
||||
import type { SessionSandboxService } from '../../services/session-sandbox'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const SandboxShellRequestSchema = z.object({
|
||||
@@ -12,7 +13,11 @@ const SandboxShellRequestSchema = z.object({
|
||||
enforced: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export function createInternalSandboxRoutes(db: Database, sessionSandbox: SessionSandboxService) {
|
||||
export function createInternalSandboxRoutes(
|
||||
db: Database,
|
||||
sessionSandbox: SessionSandboxService,
|
||||
repoEnvService: RepoEnvService,
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/sessions/:sessionId', async (c) => {
|
||||
@@ -40,7 +45,7 @@ export function createInternalSandboxRoutes(db: Database, sessionSandbox: Sessio
|
||||
try {
|
||||
const target = await sessionSandbox.resolveShellTarget(parsed.data.sessionId)
|
||||
return c.json(
|
||||
await new SandboxRuntimeService(db).planShell(
|
||||
await new SandboxRuntimeService(db, repoEnvService).planShell(
|
||||
parsed.data.directory,
|
||||
{ ...target, locationDirectory: parsed.data.locationDirectory },
|
||||
parsed.data.enforced === true,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { CredentialProvider } from '../../services/credential-provider'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
|
||||
export function createInternalShellEnvRoutes(db: Database, repoEnvService: RepoEnvService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
const provider = new CredentialProvider(db)
|
||||
const cwd = c.req.query('cwd')
|
||||
const ghEnv = provider.getGhCliEnv({ cwd })
|
||||
if (!cwd) {
|
||||
return c.json({ env: ghEnv, mask: [] })
|
||||
}
|
||||
|
||||
const repoEnv = await repoEnvService.resolveForDirectory(cwd)
|
||||
return c.json({ env: { ...ghEnv, ...repoEnv.env }, mask: repoEnv.maskValues })
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { createRepo, getRepoById, setRepoSetting } from '../db/queries'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import { createGitService } from '../services/git/GitService'
|
||||
import { ProjectConfigService } from '../services/project-config'
|
||||
import type { SecretsService } from '../services/secrets'
|
||||
import { RepoWorkspaceService } from '../services/repo-workspace'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
@@ -68,7 +69,7 @@ function createTestApp(
|
||||
} as any
|
||||
const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, {} as unknown as SecretsService))
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,12 @@ import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/open
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import { createRepoTerminalRoutes } from './repo-terminals'
|
||||
import { createRepoProjectConfigRoutes } from './repo-project-config'
|
||||
import { createRepoSecretRoutes } from './secrets'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import type { ProjectConfigService } from '../services/project-config'
|
||||
import type { SecretsService } from '../services/secrets'
|
||||
import type { RepoWorkspaceService } from '../services/repo-workspace'
|
||||
import { createGitService } from '../services/git/GitService'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
@@ -47,6 +49,7 @@ export function createRepoRoutes(
|
||||
terminalService: TerminalService,
|
||||
projectConfigService: ProjectConfigService,
|
||||
repoWorkspaces: RepoWorkspaceService,
|
||||
secretsService: SecretsService,
|
||||
) {
|
||||
const app = new Hono()
|
||||
const git = createGitService(gitAuthService)
|
||||
@@ -55,6 +58,8 @@ export function createRepoRoutes(
|
||||
app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService))
|
||||
app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService))
|
||||
app.route('/:id/schedules', createScheduleRoutes(scheduleService))
|
||||
app.route('/', createRepoSecretRoutes({ database, projectConfigService, secretsService }, 'secret'))
|
||||
app.route('/', createRepoSecretRoutes({ database, projectConfigService, secretsService }, 'variable'))
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { EnvironmentNameSchema, SecretNameSchema, SetSecretRequestSchema, type SecretKind } from '@opencode-manager/shared/schemas'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { SecretsService, SecretsServiceError } from '../services/secrets'
|
||||
import type { ProjectConfigService } from '../services/project-config'
|
||||
import { handleServiceError } from '../utils/route-helpers'
|
||||
|
||||
function readName(c: Context): { name: string } | Response {
|
||||
const parsed = SecretNameSchema.safeParse(c.req.param('name'))
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid name' }, 400)
|
||||
}
|
||||
return { name: parsed.data }
|
||||
}
|
||||
|
||||
function readEnvironmentQuery(c: Context): { environment: string | null } | Response {
|
||||
const value = c.req.query('environment')
|
||||
if (value === undefined) {
|
||||
return { environment: null }
|
||||
}
|
||||
|
||||
const parsed = EnvironmentNameSchema.safeParse(value)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid environment' }, 400)
|
||||
}
|
||||
return { environment: parsed.data }
|
||||
}
|
||||
|
||||
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.delete('/:name', (c) => {
|
||||
const name = readName(c)
|
||||
if (name instanceof Response) return name
|
||||
|
||||
const deleted = secretsService.delete(kind, null, null, name.name)
|
||||
if (!deleted) {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
export interface RepoSecretRouteDeps {
|
||||
database: Database
|
||||
projectConfigService: ProjectConfigService
|
||||
secretsService: SecretsService
|
||||
}
|
||||
|
||||
export function createRepoSecretRoutes(deps: RepoSecretRouteDeps, kind: SecretKind) {
|
||||
const { database, projectConfigService, secretsService } = deps
|
||||
const segment = kind === 'secret' ? 'secrets' : 'variables'
|
||||
const app = new Hono()
|
||||
|
||||
const resolveProjectRepo = async (c: Context): Promise<Repo | Response> => {
|
||||
const id = Number.parseInt(c.req.param('id') ?? '', 10)
|
||||
if (Number.isNaN(id)) {
|
||||
return c.json({ error: 'Invalid repo id' }, 400)
|
||||
}
|
||||
|
||||
const repo = getRepoById(database, id)
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
return projectConfigService.resolveProjectRepo(repo)
|
||||
}
|
||||
|
||||
app.get(`/:id/${segment}`, async (c) => {
|
||||
const repo = await resolveProjectRepo(c)
|
||||
if (repo instanceof Response) return repo
|
||||
return c.json({ items: secretsService.list(kind, repo.id) })
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete(`/:id/${segment}/:name`, async (c) => {
|
||||
const name = readName(c)
|
||||
if (name instanceof Response) return name
|
||||
|
||||
const environment = readEnvironmentQuery(c)
|
||||
if (environment instanceof Response) return environment
|
||||
|
||||
const repo = await resolveProjectRepo(c)
|
||||
if (repo instanceof Response) return repo
|
||||
|
||||
const deleted = secretsService.delete(kind, repo.id, environment.environment, name.name)
|
||||
if (!deleted) {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -1,36 +1,111 @@
|
||||
export function buildGhEnvPluginSource(id: string): string {
|
||||
return `const TTL_MS = 5000
|
||||
let cache = new Map()
|
||||
const maskValues = new Set()
|
||||
|
||||
async function fetchGhEnv(cwd) {
|
||||
function rememberMasks(values) {
|
||||
if (!Array.isArray(values)) return
|
||||
for (const value of values) {
|
||||
if (typeof value === 'string' && value.length > 0) maskValues.add(value)
|
||||
}
|
||||
}
|
||||
|
||||
function emptyBody() {
|
||||
return { env: {}, mask: [] }
|
||||
}
|
||||
|
||||
async function fetchShellEnv(cwd) {
|
||||
const baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
const token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) return {}
|
||||
if (!baseUrl || !token) return emptyBody()
|
||||
const now = Date.now()
|
||||
const cacheKey = cwd || ''
|
||||
const cached = cache.get(cacheKey)
|
||||
if (cached && now < cached.expiry) return cached.env
|
||||
if (cached && now < cached.expiry) return cached
|
||||
try {
|
||||
const url = new URL(baseUrl + '/git-credentials/gh-env')
|
||||
const url = new URL(baseUrl + '/shell-env')
|
||||
if (cwd) url.searchParams.set('cwd', cwd)
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
})
|
||||
if (!res.ok) return cached?.env || {}
|
||||
const env = await res.json()
|
||||
const next = { expiry: now + TTL_MS, env: env && typeof env === 'object' ? env : {} }
|
||||
if (!res.ok) return cached || emptyBody()
|
||||
const body = await res.json()
|
||||
const env = body && typeof body.env === 'object' && body.env !== null ? body.env : {}
|
||||
const mask = body && Array.isArray(body.mask) ? body.mask : []
|
||||
const next = { expiry: now + TTL_MS, env, mask }
|
||||
cache.set(cacheKey, next)
|
||||
return next.env
|
||||
return next
|
||||
} catch {
|
||||
return cached?.env || {}
|
||||
return cached || emptyBody()
|
||||
}
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
||||
const proto = Object.getPrototypeOf(value)
|
||||
return proto === Object.prototype || proto === null
|
||||
}
|
||||
|
||||
function containsMask(text) {
|
||||
for (const value of maskValues) {
|
||||
if (text.indexOf(value) !== -1) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function applyMasks(text) {
|
||||
let result = text
|
||||
const ordered = Array.from(maskValues).sort(function (a, b) { return b.length - a.length })
|
||||
for (const value of ordered) {
|
||||
if (result.indexOf(value) !== -1) result = result.split(value).join('***')
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function maskValue(value) {
|
||||
if (typeof value === 'string') {
|
||||
return containsMask(value) ? applyMasks(value) : value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
let copy = null
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const masked = maskValue(value[index])
|
||||
if (masked !== value[index]) {
|
||||
if (copy === null) copy = value.slice()
|
||||
copy[index] = masked
|
||||
}
|
||||
}
|
||||
return copy === null ? value : copy
|
||||
}
|
||||
if (isPlainObject(value)) {
|
||||
let copy = null
|
||||
for (const key of Object.keys(value)) {
|
||||
const masked = maskValue(value[key])
|
||||
if (masked !== value[key]) {
|
||||
if (copy === null) copy = Object.assign({}, value)
|
||||
copy[key] = masked
|
||||
}
|
||||
}
|
||||
return copy === null ? value : copy
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export default {
|
||||
id: '${id}',
|
||||
async setup(ctx) {
|
||||
await ctx.shell.hook('create.before', async (event) => {
|
||||
Object.assign(event.env, await fetchGhEnv(event.cwd))
|
||||
const body = await fetchShellEnv(event.cwd)
|
||||
rememberMasks(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 source = { ...event.result }
|
||||
const masked = maskValue(source)
|
||||
if (masked !== source) event.result = masked
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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'
|
||||
@@ -25,6 +26,7 @@ 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 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.'
|
||||
@@ -312,11 +314,15 @@ async function pinSandboxShell(event, sessionID, locationDirectory) {
|
||||
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
|
||||
}
|
||||
var plan = await planSandboxShell(event.cwd, sessionID, locationDirectory)
|
||||
var forwardNames = []
|
||||
if (plan.env !== null && typeof plan.env === 'object') {
|
||||
for (var name of FORWARDED_ENV_NAMES) {
|
||||
if (typeof plan.env[name] === 'string') {
|
||||
event.env[name] = plan.env[name]
|
||||
}
|
||||
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
|
||||
event.env[name] = value
|
||||
forwardNames.push(name)
|
||||
}
|
||||
}
|
||||
if (!lockAccessor(event, 'shell', SHELL_SHIM_PATH)) {
|
||||
@@ -328,6 +334,9 @@ async function pinSandboxShell(event, sessionID, locationDirectory) {
|
||||
if (!lockAccessor(event.env, ENV_SANDBOX_NAME, plan.name)) {
|
||||
throw unavailable('sandbox enforcement could not pin the sandbox session name; aborting before the command runs on the host')
|
||||
}
|
||||
if (!lockAccessor(event.env, ENV_FORWARD, forwardNames.join(' '))) {
|
||||
throw unavailable('sandbox enforcement could not pin the forwarded environment list; aborting before the command runs on the host')
|
||||
}
|
||||
}
|
||||
|
||||
async function wrapSandboxedShellTool(ctx) {
|
||||
|
||||
@@ -31,6 +31,14 @@ const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
|
||||
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
|
||||
const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link'
|
||||
|
||||
function describeZodIssue(issue: { path?: PropertyKey[]; message: string } | undefined): string {
|
||||
if (!issue) {
|
||||
return 'Invalid value'
|
||||
}
|
||||
const issuePath = (issue.path ?? []).map(String).join('.')
|
||||
return issuePath ? `${issuePath}: ${issue.message}` : issue.message
|
||||
}
|
||||
|
||||
export interface RepoFileState {
|
||||
exists: boolean
|
||||
file: RepoProjectFile | null
|
||||
@@ -280,7 +288,7 @@ export class ProjectConfigService {
|
||||
}
|
||||
}
|
||||
|
||||
private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
|
||||
isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
|
||||
return (
|
||||
repoFile.hash !== null &&
|
||||
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
|
||||
@@ -306,7 +314,7 @@ export class ProjectConfigService {
|
||||
|
||||
const parsed = RepoProjectFileSchema.safeParse(parsedJson)
|
||||
if (!parsed.success) {
|
||||
return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' }
|
||||
return { exists: true, file: null, hash: null, error: `Does not match the project file schema: ${describeZodIssue(parsed.error.issues[0])}` }
|
||||
}
|
||||
return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) }
|
||||
} catch {
|
||||
@@ -315,7 +323,7 @@ export class ProjectConfigService {
|
||||
}
|
||||
|
||||
buildRepoFileExecutable(file: RepoProjectFile): NonNullable<ProjectConfigResponse['repoFile']['executable']> {
|
||||
return {
|
||||
const executable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
|
||||
actions: (file.projectActions ?? []).map((action) => ({
|
||||
id: action.id,
|
||||
name: action.name,
|
||||
@@ -325,6 +333,13 @@ export class ProjectConfigService {
|
||||
})),
|
||||
setup: file.setupWorktree ?? [],
|
||||
}
|
||||
if (file.environment !== undefined) {
|
||||
executable.environment = file.environment
|
||||
}
|
||||
if (file.env && Object.keys(file.env).length > 0) {
|
||||
executable.env = file.env
|
||||
}
|
||||
return executable
|
||||
}
|
||||
|
||||
hashRepoFile(file: RepoProjectFile): string {
|
||||
@@ -459,7 +474,10 @@ export class ProjectConfigService {
|
||||
return false
|
||||
}
|
||||
const hasExecutable =
|
||||
(state.file.projectActions?.length ?? 0) > 0 || (state.file.setupWorktree?.length ?? 0) > 0
|
||||
(state.file.projectActions?.length ?? 0) > 0 ||
|
||||
(state.file.setupWorktree?.length ?? 0) > 0 ||
|
||||
(state.file.env !== undefined && Object.keys(state.file.env).length > 0) ||
|
||||
state.file.environment !== undefined
|
||||
return hasExecutable && !this.isRepoFileTrusted(projectRepo, state)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
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 { logger } from '../utils/logger'
|
||||
import { resolveMainCheckoutPath, resolveRepoForDirectory } from './repo'
|
||||
import type { ProjectConfigService } from './project-config'
|
||||
import type { SecretsService } from './secrets'
|
||||
|
||||
export interface ResolvedRepoEnv {
|
||||
env: Record<string, string>
|
||||
maskValues: string[]
|
||||
missing: string[]
|
||||
}
|
||||
|
||||
function emptyResult(): ResolvedRepoEnv {
|
||||
return { env: {}, maskValues: [], missing: [] }
|
||||
}
|
||||
|
||||
export class RepoEnvService {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly projectConfigService: ProjectConfigService,
|
||||
private readonly secretsService: SecretsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Resolves the repository environment for a directory.
|
||||
*
|
||||
* Never rejects: any internal failure is logged as a warning naming the directory
|
||||
* and resolves to an empty result.
|
||||
*/
|
||||
async resolveForDirectory(cwd: string): Promise<ResolvedRepoEnv> {
|
||||
try {
|
||||
const topLevel = await this.findTopLevel(cwd)
|
||||
if (!topLevel) {
|
||||
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)) {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
const mapping = repoFile.file.env
|
||||
if (!mapping || Object.keys(mapping).length === 0) {
|
||||
return emptyResult()
|
||||
}
|
||||
|
||||
const resolved = this.secretsService.resolveValues(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') {
|
||||
maskValues.add(found)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
const env: Record<string, string> = {}
|
||||
for (const [name, template] of Object.entries(mapping)) {
|
||||
env[name] = interpolateEnvExpressions(template, lookup).value
|
||||
}
|
||||
|
||||
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)
|
||||
return emptyResult()
|
||||
}
|
||||
}
|
||||
|
||||
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 async findRepo(topLevel: string): Promise<Repo | null> {
|
||||
const direct = getRepoByDirectory(this.db, topLevel)
|
||||
if (direct) {
|
||||
return direct
|
||||
}
|
||||
|
||||
const mainCheckout = await resolveMainCheckoutPath(topLevel)
|
||||
if (mainCheckout) {
|
||||
const mainRepo = getRepoByDirectory(this.db, mainCheckout)
|
||||
if (mainRepo) {
|
||||
return mainRepo
|
||||
}
|
||||
}
|
||||
|
||||
return resolveRepoForDirectory(this.db, topLevel)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { isPathWithinRoot, mkdirSafe } from '../../utils/fs-safe'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { SettingsService } from '../settings'
|
||||
import { CredentialProvider } from '../credential-provider'
|
||||
import type { RepoEnvService } from '../repo-env'
|
||||
import { getGitIdentityEnvForDirectory } from '../git-identity'
|
||||
import { getProcessIdentityAttestationError } from '../opencode/process-identity'
|
||||
import { detectSandboxCapability } from './capability'
|
||||
@@ -1049,7 +1050,10 @@ function sandboxMaxRunningVms(db: Database): number {
|
||||
}
|
||||
|
||||
export class SandboxRuntimeService {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly repoEnvService?: RepoEnvService,
|
||||
) {}
|
||||
|
||||
async prepareSandboxOnBoot(): Promise<void> {
|
||||
if (!this.isSandboxEnabled()) return
|
||||
@@ -1119,6 +1123,10 @@ export class SandboxRuntimeService {
|
||||
...new CredentialProvider(this.db).getSandboxGitEnv({ cwd: directory }),
|
||||
...await getGitIdentityEnvForDirectory(directory, this.db),
|
||||
}
|
||||
if (this.repoEnvService) {
|
||||
const repoEnv = await this.repoEnvService.resolveForDirectory(directory)
|
||||
Object.assign(env, repoEnv.env)
|
||||
}
|
||||
return Object.keys(env).length > 0
|
||||
? { mode: 'sandbox', name: spec.name, workdir: workDirectory, env }
|
||||
: { mode: 'sandbox', name: spec.name, workdir: workDirectory }
|
||||
|
||||
@@ -15,18 +15,25 @@ export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR'
|
||||
export const SANDBOX_SHELL_ENV_NAME = 'OCM_SANDBOX_NAME'
|
||||
|
||||
/**
|
||||
* Upper bound on `http.<host>.extraheader` pairs forwarded into the microVM.
|
||||
* The shim enumerates a fixed set of variable names rather than expanding
|
||||
* `GIT_CONFIG_KEY_$i` indirectly, which would require `eval` on values holding
|
||||
* credentials. Credentials are configured per host, so this bounds the number
|
||||
* of distinct git hosts a sandboxed command can authenticate against.
|
||||
* Space-separated allow-list of variable names the shim forwards from its own
|
||||
* environment into the microVM with `msb exec -e`. The plugin pins it from the
|
||||
* sandbox plan, so only names the plan approved reach a sandboxed command; the
|
||||
* guest environment is otherwise empty.
|
||||
*/
|
||||
export const SANDBOX_SHELL_ENV_FORWARD = 'OCM_SANDBOX_FORWARD_ENV'
|
||||
|
||||
/**
|
||||
* Upper bound on `http.<host>.extraheader` pairs the planner forwards into the
|
||||
* microVM. Credentials are configured per host, so this bounds the number of
|
||||
* distinct git hosts a sandboxed command can authenticate against.
|
||||
*/
|
||||
export const SANDBOX_MAX_FORWARDED_GIT_CONFIGS = 16
|
||||
|
||||
/**
|
||||
* Variables the shim copies from its own environment into the microVM with
|
||||
* `msb exec -e`. The guest environment is otherwise empty, so anything absent
|
||||
* from this list never reaches a sandboxed command.
|
||||
* 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',
|
||||
@@ -44,9 +51,10 @@ export const SANDBOX_FORWARDED_ENV_NAMES: readonly string[] = [
|
||||
]
|
||||
|
||||
/**
|
||||
* Drops `http.<host>.extraheader` pairs the shim cannot forward, so the guest
|
||||
* never sees a `GIT_CONFIG_COUNT` that overstates the pairs actually present.
|
||||
* A count larger than the pairs in the environment makes git fail outright.
|
||||
* Drops `http.<host>.extraheader` pairs beyond the forwarding cap, so the
|
||||
* guest never sees a `GIT_CONFIG_COUNT` that overstates the pairs actually
|
||||
* present. A count larger than the pairs in the environment makes git fail
|
||||
* outright.
|
||||
*/
|
||||
export function limitForwardedGitConfigs(env: Record<string, string>): {
|
||||
env: Record<string, string>
|
||||
@@ -85,9 +93,22 @@ export function buildSandboxShellShimScript(): string {
|
||||
'--timeout',
|
||||
`${timeoutSeconds}s`,
|
||||
].join(' ')
|
||||
const forwardEnv = SANDBOX_FORWARDED_ENV_NAMES.map(
|
||||
(name) => ` if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`,
|
||||
).join('\n')
|
||||
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 ;;`,
|
||||
' esac',
|
||||
` eval "OCM_SHIM_SET=\\\${$OCM_SHIM_NAME+x}"`,
|
||||
` [ -n "$OCM_SHIM_SET" ] || continue`,
|
||||
` eval "OCM_SHIM_VALUE=\\\${$OCM_SHIM_NAME}"`,
|
||||
` set -- "$@" -e "$OCM_SHIM_NAME=$OCM_SHIM_VALUE"`,
|
||||
'done',
|
||||
'set +f',
|
||||
].join('\n')
|
||||
return `#!/bin/sh
|
||||
if [ -z "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
|
||||
echo 'ocm-sandbox-shell: sandbox working directory missing; refusing to run on the host' >&2
|
||||
@@ -100,16 +121,16 @@ case "\${${SANDBOX_SHELL_ENV_NAME}:-}" in
|
||||
exit 126
|
||||
;;
|
||||
esac
|
||||
ocm_argc=$#
|
||||
OCM_SHIM_ARGC=$#
|
||||
set -- "$@" ${execArgs}
|
||||
${forwardEnv}
|
||||
set -- "$@" -- sh
|
||||
ocm_i=0
|
||||
while [ "$ocm_i" -lt "$ocm_argc" ]; do
|
||||
ocm_arg=$1
|
||||
OCM_SHIM_I=0
|
||||
while [ "$OCM_SHIM_I" -lt "$OCM_SHIM_ARGC" ]; do
|
||||
OCM_SHIM_ARG=$1
|
||||
shift
|
||||
set -- "$@" "$ocm_arg"
|
||||
ocm_i=$((ocm_i + 1))
|
||||
set -- "$@" "$OCM_SHIM_ARG"
|
||||
OCM_SHIM_I=$((OCM_SHIM_I + 1))
|
||||
done
|
||||
exec "$@"
|
||||
`
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { SecretEntry, SecretKind } from '@opencode-manager/shared/schemas'
|
||||
import { decryptSecret, encryptSecret } from '../utils/crypto'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export class SecretsServiceError extends Error {
|
||||
constructor(message: string, public statusCode: number = 500) {
|
||||
super(message)
|
||||
this.name = 'SecretsServiceError'
|
||||
}
|
||||
}
|
||||
|
||||
interface SecretRow {
|
||||
kind: SecretKind
|
||||
repo_id: number | null
|
||||
environment: string
|
||||
name: string
|
||||
value: string
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
interface SecretValueRow {
|
||||
kind: SecretKind
|
||||
repo_id: number | null
|
||||
environment: string
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface ResolvedSecretValues {
|
||||
secrets: Record<string, string>
|
||||
vars: Record<string, string>
|
||||
}
|
||||
|
||||
export class SecretsService {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
list(kind: SecretKind, repoId: number | null): SecretEntry[] {
|
||||
return this.selectRows(kind, repoId).map((row) => this.toEntry(kind, row))
|
||||
}
|
||||
|
||||
set(kind: SecretKind, repoId: number | null, environment: string | null, name: string, value: string): void {
|
||||
const normalizedEnvironment = environment ?? ''
|
||||
if (repoId === null && normalizedEnvironment !== '') {
|
||||
throw new SecretsServiceError('Environments are only supported for repository secrets', 400)
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const storedValue = kind === 'secret' ? encryptSecret(value) : value
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
|
||||
)
|
||||
.run(kind, repoId, normalizedEnvironment, name, storedValue, now, now)
|
||||
}
|
||||
|
||||
delete(kind: SecretKind, repoId: number | null, environment: string | null, name: string): boolean {
|
||||
const result = this.db
|
||||
.prepare('DELETE FROM secrets WHERE kind = ? AND repo_id IS ? AND environment = ? AND name = ?')
|
||||
.run(kind, repoId, environment ?? '', name)
|
||||
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
resolveValues(repoId: number, environment: string | null): ResolvedSecretValues {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT kind, repo_id, environment, name, value FROM secrets
|
||||
WHERE repo_id IS NULL OR repo_id = ?
|
||||
ORDER BY CASE WHEN repo_id IS NULL THEN 0 WHEN environment = '' THEN 1 ELSE 2 END`,
|
||||
)
|
||||
.all(repoId) as SecretValueRow[]
|
||||
|
||||
const secrets: Record<string, string> = {}
|
||||
const vars: Record<string, string> = {}
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.repo_id !== null && row.environment !== '' && row.environment !== environment) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (row.kind === 'secret') {
|
||||
try {
|
||||
secrets[row.name] = decryptSecret(row.value)
|
||||
} catch {
|
||||
logger.warn(`Skipping secret "${row.name}" because it could not be decrypted`)
|
||||
}
|
||||
} else {
|
||||
vars[row.name] = row.value
|
||||
}
|
||||
}
|
||||
|
||||
return { secrets, vars }
|
||||
}
|
||||
|
||||
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',
|
||||
)
|
||||
.all(kind, repoId) as SecretRow[]
|
||||
}
|
||||
|
||||
private toEntry(kind: SecretKind, row: SecretRow): SecretEntry {
|
||||
return {
|
||||
name: row.name,
|
||||
environment: row.environment === '' ? null : row.environment,
|
||||
updatedAt: row.updated_at,
|
||||
...(kind === 'variable' ? { value: row.value } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/share
|
||||
import type { TerminalInfo, TerminalKind } from '@opencode-manager/shared/types'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import type { CredentialProvider } from './credential-provider'
|
||||
import type { RepoEnvService } from './repo-env'
|
||||
import { toWebSocketUrl } from './opencode/upstream'
|
||||
import { bridgeWebSocket, type WebSocketBridge, type WebSocketPeer } from '../utils/websocket-bridge'
|
||||
import { TerminalHub, TerminalHubRegistry } from './terminal-hub'
|
||||
@@ -56,13 +57,21 @@ export class TerminalService {
|
||||
constructor(
|
||||
private readonly target: TerminalTarget,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly repoEnvService: RepoEnvService,
|
||||
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
|
||||
private readonly hubs: TerminalHubRegistry = new TerminalHubRegistry(),
|
||||
private readonly deferredReleases: Map<string, DeferredRelease> = new Map(),
|
||||
) {}
|
||||
|
||||
forTarget(target: TerminalTarget): TerminalService {
|
||||
return new TerminalService(target, this.credentialProvider, this.openSocket, this.hubs, this.deferredReleases)
|
||||
return new TerminalService(
|
||||
target,
|
||||
this.credentialProvider,
|
||||
this.repoEnvService,
|
||||
this.openSocket,
|
||||
this.hubs,
|
||||
this.deferredReleases,
|
||||
)
|
||||
}
|
||||
|
||||
async list(directory: string): Promise<TerminalInfo[]> {
|
||||
@@ -75,6 +84,7 @@ 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 result = await this.target.client.api.pty.create({
|
||||
location: { directory },
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
|
||||
@@ -86,6 +96,7 @@ export class TerminalService {
|
||||
}),
|
||||
env: {
|
||||
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
|
||||
...repoEnv,
|
||||
...input.env,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -245,6 +245,7 @@ describe('Database Queries', () => {
|
||||
const deleteFusionsStmt = { run: vi.fn().mockReturnValue({ changes: 3 }) }
|
||||
const deleteEntriesStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
const deleteMultiRunsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
const deleteSecretsStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
const deleteRunsStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
const deleteJobsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
const deleteSettingsStmt = { run: vi.fn().mockReturnValue({ changes: 0 }) }
|
||||
@@ -253,6 +254,7 @@ describe('Database Queries', () => {
|
||||
.mockReturnValueOnce(deleteFusionsStmt)
|
||||
.mockReturnValueOnce(deleteEntriesStmt)
|
||||
.mockReturnValueOnce(deleteMultiRunsStmt)
|
||||
.mockReturnValueOnce(deleteSecretsStmt)
|
||||
.mockReturnValueOnce(deleteJobsStmt)
|
||||
.mockReturnValueOnce(deleteRunsStmt)
|
||||
.mockReturnValueOnce(deleteSettingsStmt)
|
||||
@@ -271,13 +273,15 @@ describe('Database Queries', () => {
|
||||
expect(deleteEntriesStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM multi_runs WHERE repo_id = ?')
|
||||
expect(deleteMultiRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(4, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(4, 'DELETE FROM secrets WHERE repo_id = ?')
|
||||
expect(deleteSecretsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(5, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(5, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(6, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(6, 'DELETE FROM repo_settings WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(7, 'DELETE FROM repo_settings WHERE repo_id = ?')
|
||||
expect(deleteSettingsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(7,
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(8,
|
||||
'DELETE FROM repos WHERE id = ?'
|
||||
)
|
||||
expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
|
||||
|
||||
@@ -15,8 +15,15 @@ type InternalTestAppOverrides = Partial<{
|
||||
multiRuns: CreateInternalRoutesParams[9]
|
||||
changeWalkthroughService: CreateInternalRoutesParams[10]
|
||||
sessionSandbox: CreateInternalRoutesParams[11]
|
||||
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 = {},
|
||||
@@ -34,5 +41,6 @@ export function createInternalTestApp(
|
||||
overrides.multiRuns ?? ({} as CreateInternalRoutesParams[9]),
|
||||
overrides.changeWalkthroughService ?? ({} as CreateInternalRoutesParams[10]),
|
||||
overrides.sessionSandbox ?? ({} as CreateInternalRoutesParams[11]),
|
||||
overrides.repoEnvService ?? createStubRepoEnvService(),
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { ScheduleService } from '../../src/services/schedules'
|
||||
import type { TerminalService } from '../../src/services/terminal'
|
||||
import type { ProjectConfigService } from '../../src/services/project-config'
|
||||
import type { SecretsService } from '../../src/services/secrets'
|
||||
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
@@ -63,7 +64,7 @@ describe('Git Routes', () => {
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService)
|
||||
app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService, {} as unknown as SecretsService)
|
||||
})
|
||||
|
||||
describe('GET /:id/git/status', () => {
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
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('internal git-credentials routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let app: ReturnType<typeof createInternalGitCredentialsRoutes>
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
app = createInternalGitCredentialsRoutes(db)
|
||||
})
|
||||
|
||||
it('GET /gh-env returns GH_TOKEN and GITHUB_TOKEN for a GitHub PAT', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request('/gh-env')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' })
|
||||
})
|
||||
|
||||
it('GET /gh-env returns an empty object when no GitHub credential exists', async () => {
|
||||
const res = await app.request('/gh-env')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({})
|
||||
})
|
||||
|
||||
it('GET /gh-env returns only GH env for a repo cwd', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_repo_token' } as GitCredential,
|
||||
],
|
||||
gitIdentities: [{ id: 'work', name: 'Work User', email: 'work@example.com' }],
|
||||
})
|
||||
|
||||
const res = await app.request('/gh-env?cwd=/tmp/any-repo')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_repo_token', GITHUB_TOKEN: 'ghp_repo_token' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, beforeEach, vi } 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 { createInternalShellEnvRoutes } from '../../../src/routes/internal/shell-env'
|
||||
import type { RepoEnvService, ResolvedRepoEnv } from '../../../src/services/repo-env'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
function createRepoEnvService(resolve: (cwd: string) => Promise<ResolvedRepoEnv>): RepoEnvService {
|
||||
return { resolveForDirectory: vi.fn(resolve) } as unknown as RepoEnvService
|
||||
}
|
||||
|
||||
describe('internal shell-env routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
|
||||
function appWith(repoEnvService: RepoEnvService) {
|
||||
return createInternalShellEnvRoutes(db, repoEnvService)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
})
|
||||
|
||||
it('returns GH_TOKEN and GITHUB_TOKEN for a GitHub PAT when no cwd is given', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
const repoEnvService = createRepoEnvService(async () => ({ env: {}, maskValues: [], missing: [] }))
|
||||
const app = appWith(repoEnvService)
|
||||
|
||||
const res = await app.request('/')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ env: { GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' }, mask: [] })
|
||||
expect(repoEnvService.resolveForDirectory).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns an empty GH env when no GitHub credential exists', async () => {
|
||||
const app = appWith(createRepoEnvService(async () => ({ env: {}, maskValues: [], missing: [] })))
|
||||
|
||||
const res = await app.request('/')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ env: {}, mask: [] })
|
||||
})
|
||||
|
||||
it('merges the mapped repository env and mask after the GitHub env for a cwd', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_repo_token' } as GitCredential,
|
||||
],
|
||||
gitIdentities: [{ id: 'work', name: 'Work User', email: 'work@example.com' }],
|
||||
})
|
||||
const repoEnvService = createRepoEnvService(async () => ({
|
||||
env: { API_URL: 'https://internal.example', GITHUB_TOKEN: 'mapped' },
|
||||
maskValues: ['super-secret'],
|
||||
missing: [],
|
||||
}))
|
||||
const app = appWith(repoEnvService)
|
||||
|
||||
const res = await app.request('/?cwd=/tmp/any-repo')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
env: { GH_TOKEN: 'ghp_repo_token', GITHUB_TOKEN: 'mapped', API_URL: 'https://internal.example' },
|
||||
mask: ['super-secret'],
|
||||
})
|
||||
expect(repoEnvService.resolveForDirectory).toHaveBeenCalledWith('/tmp/any-repo')
|
||||
})
|
||||
})
|
||||
@@ -10,11 +10,16 @@ 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 { 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'
|
||||
|
||||
@@ -61,6 +66,7 @@ const managerWs = createNodeWebSocket({ app: managerApp })
|
||||
const terminalService = new TerminalService(
|
||||
{ client: remoteClient, baseUrl: () => `http://127.0.0.1:${upstream.port}`, includeLocalCredentials: false },
|
||||
credentialProvider,
|
||||
stubRepoEnvService(),
|
||||
)
|
||||
|
||||
const resolveTerminalService: ServerTerminalServiceResolver = (serverId) => {
|
||||
|
||||
@@ -9,6 +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'
|
||||
|
||||
const DIRECTORY = '/home/me/app'
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
@@ -43,6 +44,10 @@ 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>>) {
|
||||
const remote = createRemoteClient(terminals)
|
||||
const credentialProvider = {
|
||||
@@ -51,6 +56,7 @@ function createService(includeLocalCredentials = false, terminals?: Array<Record
|
||||
const service = new TerminalService(
|
||||
{ client: remote.client, baseUrl: () => 'https://remote.internal', includeLocalCredentials },
|
||||
credentialProvider,
|
||||
stubRepoEnvService(),
|
||||
)
|
||||
return { service, credentialProvider, ...remote }
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ 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'
|
||||
|
||||
@@ -81,6 +82,7 @@ upstreamApp.get(
|
||||
const terminalService = new TerminalService(
|
||||
{ client: openCodeClient, baseUrl: () => upstreamBase, includeLocalCredentials: true },
|
||||
credentialProvider,
|
||||
{ resolveForDirectory: async () => ({ env: {}, maskValues: [], missing: [] }) } as unknown as RepoEnvService,
|
||||
)
|
||||
|
||||
const managerApp = new Hono()
|
||||
|
||||
@@ -17,6 +17,7 @@ import { createGitAuthService, cloneOrigin, createOrigin, git, uniqueName } from
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
import type { TerminalService } from '../../src/services/terminal'
|
||||
import type { ProjectConfigService } from '../../src/services/project-config'
|
||||
import type { SecretsService } from '../../src/services/secrets'
|
||||
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
|
||||
|
||||
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'repos-git-identity-'))
|
||||
@@ -52,7 +53,7 @@ describe('repo git identity routes', () => {
|
||||
mkdirSync(reposPath, { recursive: true })
|
||||
const scheduleService = { prepareRepoDelete: () => {} } as unknown as Parameters<typeof createRepoRoutes>[2]
|
||||
app = new Hono()
|
||||
app.route('/repos', createRepoRoutes(db, createGitAuthService(), scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService))
|
||||
app.route('/repos', createRepoRoutes(db, createGitAuthService(), scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService, {} as unknown as SecretsService))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -84,6 +84,7 @@ import * as archiveService from '../../src/services/archive'
|
||||
import { createRepoRoutes } from '../../src/routes/repos'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { ProjectConfigService } from '../../src/services/project-config'
|
||||
import type { SecretsService } from '../../src/services/secrets'
|
||||
import { RepoWorkspaceService } from '../../src/services/repo-workspace'
|
||||
import { createGitService } from '../../src/services/git/GitService'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
@@ -112,7 +113,7 @@ const mockTerminalService = {
|
||||
function createTestRoutes(openCodeClient: ReturnType<typeof createStubOpenCodeClient> = createStubOpenCodeClient()): ReturnType<typeof createRepoRoutes> {
|
||||
const projectConfigService = new ProjectConfigService(mockDb, createGitService(mockGitAuthService), mockGitAuthService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService, mockScheduleService)
|
||||
return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService, projectConfigService, repoWorkspaces)
|
||||
return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService, projectConfigService, repoWorkspaces, {} as unknown as SecretsService)
|
||||
}
|
||||
|
||||
function createMockRepo(overrides: Partial<Repo> = {}): Repo {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { SecretsService } from '../../src/services/secrets'
|
||||
import { ProjectConfigService } from '../../src/services/project-config'
|
||||
import { createGitService } from '../../src/services/git/GitService'
|
||||
import { createGlobalSecretRoutes, createRepoSecretRoutes } from '../../src/routes/secrets'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { SecretEntry } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
function createApp(db: Database): Hono {
|
||||
const secretsService = new SecretsService(db)
|
||||
const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
|
||||
const app = new Hono()
|
||||
app.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
|
||||
app.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
|
||||
app.route('/repos', createRepoSecretRoutes({ database: db, projectConfigService, secretsService }, 'secret'))
|
||||
app.route('/repos', createRepoSecretRoutes({ database: db, projectConfigService, secretsService }, 'variable'))
|
||||
return app
|
||||
}
|
||||
|
||||
function seedRepo(db: Database): number {
|
||||
return createRepo(db, {
|
||||
localPath: 'repo-a',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
}).id
|
||||
}
|
||||
|
||||
async function readItems(res: Response): Promise<SecretEntry[]> {
|
||||
const body = await res.json() as { items: SecretEntry[] }
|
||||
return body.items
|
||||
}
|
||||
|
||||
describe('secret routes', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createApp(db)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('lists global secrets and variables as empty initially', async () => {
|
||||
const secrets = await app.request('/secrets')
|
||||
const variables = await app.request('/variables')
|
||||
expect(secrets.status).toBe(200)
|
||||
expect(variables.status).toBe(200)
|
||||
expect(await readItems(secrets)).toEqual([])
|
||||
expect(await readItems(variables)).toEqual([])
|
||||
})
|
||||
|
||||
it('stores a secret without ever returning its value', async () => {
|
||||
const put = await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'super-secret' }),
|
||||
})
|
||||
expect(put.status).toBe(204)
|
||||
|
||||
const list = await app.request('/secrets')
|
||||
const items = await readItems(list)
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ name: 'TOKEN', environment: null })
|
||||
expect(items[0]).not.toHaveProperty('value')
|
||||
|
||||
const stored = db.prepare('SELECT value FROM secrets WHERE name = ?').get('TOKEN') as { value: string }
|
||||
expect(stored.value).not.toBe('super-secret')
|
||||
})
|
||||
|
||||
it('stores a variable and returns its value', async () => {
|
||||
const put = await app.request('/variables/log_level', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'debug' }),
|
||||
})
|
||||
expect(put.status).toBe(204)
|
||||
|
||||
const items = await readItems(await app.request('/variables'))
|
||||
expect(items).toEqual([expect.objectContaining({ name: 'LOG_LEVEL', environment: null, value: 'debug' })])
|
||||
})
|
||||
|
||||
it('normalizes names to upper case', async () => {
|
||||
await app.request('/secrets/my_token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'v' }),
|
||||
})
|
||||
|
||||
const items = await readItems(await app.request('/secrets'))
|
||||
expect(items[0]?.name).toBe('MY_TOKEN')
|
||||
})
|
||||
|
||||
it('rejects invalid, GITHUB_, and reserved names with 400', async () => {
|
||||
for (const name of ['1BAD', 'GITHUB_TOKEN', 'PATH', 'OCM_SOMETHING']) {
|
||||
const res = await app.request(`/secrets/${name}`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'v' }),
|
||||
})
|
||||
expect(res.status, name).toBe(400)
|
||||
}
|
||||
})
|
||||
|
||||
it('enforces the 48 KiB value limit', async () => {
|
||||
const atLimit = await app.request('/variables/big', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'a'.repeat(48 * 1024) }),
|
||||
})
|
||||
expect(atLimit.status).toBe(204)
|
||||
|
||||
const overLimit = await app.request('/variables/too_big', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'a'.repeat(48 * 1024 + 1) }),
|
||||
})
|
||||
expect(overLimit.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects an environment on a global secret', async () => {
|
||||
const res = await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'v', environment: 'prod' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('deletes a global secret and returns 404 when missing', async () => {
|
||||
await app.request('/secrets/token', {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'v' }),
|
||||
})
|
||||
|
||||
expect((await app.request('/secrets/token', { method: 'DELETE' })).status).toBe(204)
|
||||
expect((await app.request('/secrets/token', { method: 'DELETE' })).status).toBe(404)
|
||||
})
|
||||
|
||||
it('stores repository secrets against the repo and never returns values', async () => {
|
||||
const repoId = seedRepo(db)
|
||||
|
||||
const put = await app.request(`/repos/${repoId}/secrets/token`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'repo-secret' }),
|
||||
})
|
||||
expect(put.status).toBe(204)
|
||||
|
||||
const items = await readItems(await app.request(`/repos/${repoId}/secrets`))
|
||||
expect(items).toEqual([expect.objectContaining({ name: 'TOKEN', environment: null })])
|
||||
expect(items[0]).not.toHaveProperty('value')
|
||||
})
|
||||
|
||||
it('supports repository environments and scoped deletes', async () => {
|
||||
const repoId = seedRepo(db)
|
||||
|
||||
await app.request(`/repos/${repoId}/variables/deploy_url`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ value: 'https://example.test', environment: 'Production' }),
|
||||
})
|
||||
|
||||
const items = await readItems(await app.request(`/repos/${repoId}/variables`))
|
||||
expect(items).toEqual([expect.objectContaining({ name: 'DEPLOY_URL', environment: 'production', value: 'https://example.test' })])
|
||||
|
||||
const deleted = await app.request(`/repos/${repoId}/variables/deploy_url?environment=production`, { method: 'DELETE' })
|
||||
expect(deleted.status).toBe(204)
|
||||
|
||||
const missing = await app.request(`/repos/${repoId}/variables/deploy_url?environment=production`, { method: 'DELETE' })
|
||||
expect(missing.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown repository', async () => {
|
||||
const res = await app.request('/repos/9999/secrets')
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { REPO_PROJECT_ENV_MAX_ENTRIES, RepoProjectFileSchema } from '@opencode-manager/shared/schemas'
|
||||
|
||||
function parseEnv(env: Record<string, string>) {
|
||||
return RepoProjectFileSchema.safeParse({ version: 1, env })
|
||||
}
|
||||
|
||||
describe('RepoProjectFileSchema env', () => {
|
||||
it('accepts valid expressions and keeps key case', () => {
|
||||
const result = parseEnv({ API_URL: 'https://${{ vars.HOST }}', plainVar: 'literal' })
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data.env).toEqual({ API_URL: 'https://${{ vars.HOST }}', plainVar: 'literal' })
|
||||
}
|
||||
})
|
||||
|
||||
it('lower-cases the environment name', () => {
|
||||
const result = RepoProjectFileSchema.safeParse({ version: 1, environment: 'Prod', env: { A: 'x' } })
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data.environment).toBe('prod')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a reserved environment variable name with an actionable message', () => {
|
||||
const result = parseEnv({ OCM_TOKEN: 'x' })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toBe('OCM_TOKEN is reserved for Manager or the runtime')
|
||||
expect(result.error.issues[0]?.path).toEqual(['env', 'OCM_TOKEN'])
|
||||
}
|
||||
expect(parseEnv({ PATH: '/tmp' }).success).toBe(false)
|
||||
expect(parseEnv({ OPENCODE_TOKEN: 'x' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an invalid environment variable name with an actionable message', () => {
|
||||
const result = parseEnv({ '1BAD': 'x' })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toBe('1BAD is not a valid environment variable name')
|
||||
expect(result.error.issues[0]?.path).toEqual(['env', '1BAD'])
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an unsupported expression with an actionable error', () => {
|
||||
const result = parseEnv({ TOKEN: '${{ github.sha }}' })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
const issue = result.error.issues[0]
|
||||
expect(issue?.message).toContain('Unsupported expression')
|
||||
expect(issue?.message).toContain('github.sha')
|
||||
expect(issue?.path).toEqual(['env', 'TOKEN'])
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an environment value over 4000 characters', () => {
|
||||
expect(parseEnv({ TOKEN: 'a'.repeat(4001) }).success).toBe(false)
|
||||
expect(parseEnv({ TOKEN: 'a'.repeat(4000) }).success).toBe(true)
|
||||
})
|
||||
|
||||
it('allows up to the environment entry limit and rejects more', () => {
|
||||
const atLimit = Object.fromEntries(
|
||||
Array.from({ length: REPO_PROJECT_ENV_MAX_ENTRIES }, (_, index) => [`VAR_${index}`, 'x']),
|
||||
)
|
||||
const overLimit = Object.fromEntries(
|
||||
Array.from({ length: REPO_PROJECT_ENV_MAX_ENTRIES + 1 }, (_, index) => [`VAR_${index}`, 'x']),
|
||||
)
|
||||
|
||||
expect(parseEnv(atLimit).success).toBe(true)
|
||||
expect(parseEnv(overLimit).success).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@ import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
import type { Repo } from '../../../src/types/repo'
|
||||
import type { TerminalService } from '../../../src/services/terminal'
|
||||
import type { ProjectConfigService } from '../../../src/services/project-config'
|
||||
import type { SecretsService } from '../../../src/services/secrets'
|
||||
import type { RepoWorkspaceService } from '../../../src/services/repo-workspace'
|
||||
|
||||
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'git-service-real-'))
|
||||
@@ -1198,7 +1199,7 @@ describe('GitService real git', () => {
|
||||
remove: async () => undefined,
|
||||
removeRepoTerminals: async () => undefined,
|
||||
} as unknown as RepoWorkspaceService
|
||||
app.route('/repos', createRepoRoutes(db, gitAuth, scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, repoWorkspaces))
|
||||
app.route('/repos', createRepoRoutes(db, gitAuth, scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, repoWorkspaces, {} as unknown as SecretsService))
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 } from '../helpers/opencode-plugin-context'
|
||||
import { loadGeneratedPlugin, type ToolExecuteAfterEvent } from '../helpers/opencode-plugin-context'
|
||||
|
||||
const INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
|
||||
@@ -22,10 +22,10 @@ describe('ocm-gh-env plugin', () => {
|
||||
return loadGeneratedPlugin(pluginPath())
|
||||
}
|
||||
|
||||
function stubGhEnvFetch(env: Record<string, string>) {
|
||||
function stubShellEnvFetch(body: { env?: Record<string, string>; mask?: string[] }) {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => env,
|
||||
json: async () => body,
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
return fetchMock
|
||||
@@ -97,8 +97,8 @@ describe('ocm-gh-env plugin', () => {
|
||||
await expect(fs.access(pluginPath())).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('merges the fetched GH env into the create.before event env', async () => {
|
||||
const fetchMock = stubGhEnvFetch({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
|
||||
it('merges the fetched shell env into the create.before event env', async () => {
|
||||
const fetchMock = stubShellEnvFetch({ env: { GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }, mask: [] })
|
||||
const plugin = await loadPlugin()
|
||||
const event = { command: 'git push', cwd: '/repo', env: { PATH: '/usr/bin' } }
|
||||
|
||||
@@ -106,7 +106,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
|
||||
expect(event.env).toEqual({ PATH: '/usr/bin', GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
|
||||
const [url, options] = fetchMock.mock.calls[0]!
|
||||
expect(url.toString()).toBe('http://localhost:5003/api/internal/git-credentials/gh-env?cwd=%2Frepo')
|
||||
expect(url.toString()).toBe('http://localhost:5003/api/internal/shell-env?cwd=%2Frepo')
|
||||
expect(options).toEqual({ headers: { Authorization: 'Bearer secret-token' } })
|
||||
})
|
||||
|
||||
@@ -135,7 +135,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
})
|
||||
|
||||
it('caches results within the TTL so rapid calls fetch once', async () => {
|
||||
const fetchMock = stubGhEnvFetch({ GH_TOKEN: 'ghp' })
|
||||
const fetchMock = stubShellEnvFetch({ env: { GH_TOKEN: 'ghp' } })
|
||||
const plugin = await loadPlugin()
|
||||
const first = { command: 'git push', cwd: '/repo', env: {} }
|
||||
const second = { command: 'git push', cwd: '/repo', env: {} }
|
||||
@@ -148,7 +148,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
})
|
||||
|
||||
it('caches results per cwd', async () => {
|
||||
const fetchMock = stubGhEnvFetch({ GH_TOKEN: 'ghp' })
|
||||
const fetchMock = stubShellEnvFetch({ env: { GH_TOKEN: 'ghp' } })
|
||||
const plugin = await loadPlugin()
|
||||
|
||||
await plugin.triggerShellCreateBefore({ command: 'git push', cwd: '/repo-a', env: {} })
|
||||
@@ -161,7 +161,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
|
||||
it('keeps the cached env when a later fetch fails', async () => {
|
||||
const realNow = Date.now
|
||||
const fetchMock = stubGhEnvFetch({ GH_TOKEN: 'ghp' })
|
||||
const fetchMock = stubShellEnvFetch({ env: { GH_TOKEN: 'ghp' } })
|
||||
const plugin = await loadPlugin()
|
||||
const first = { command: 'git push', cwd: '/repo', env: {} }
|
||||
await plugin.triggerShellCreateBefore(first)
|
||||
@@ -175,6 +175,101 @@ describe('ocm-gh-env plugin', () => {
|
||||
expect(second.env).toEqual({ GH_TOKEN: 'ghp' })
|
||||
})
|
||||
|
||||
it('masks learned secret values in output, content text and nested metadata for every tool', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['s3cret-value'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
const event: ToolExecuteAfterEvent = {
|
||||
tool: 'read',
|
||||
status: 'completed',
|
||||
result: {
|
||||
output: 'token s3cret-value here',
|
||||
content: [{ type: 'text', text: 'also s3cret-value' }],
|
||||
metadata: { output: 'nested s3cret-value' },
|
||||
},
|
||||
}
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({
|
||||
output: 'token *** here',
|
||||
content: [{ type: 'text', text: 'also ***' }],
|
||||
metadata: { output: 'nested ***' },
|
||||
})
|
||||
})
|
||||
|
||||
it('masks a completed result that is not a plain object', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['s3cret-value'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
class ToolResult {
|
||||
[key: string]: unknown
|
||||
output = 'token s3cret-value'
|
||||
}
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result: new ToolResult() }
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
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()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
const result = { output: 's3cret-value' }
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'error', result }
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toBe(result)
|
||||
})
|
||||
|
||||
it('does not reallocate the result when no mask value occurs', async () => {
|
||||
stubShellEnvFetch({ env: {}, mask: ['s3cret-value'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
const result = { output: 'nothing sensitive', content: [{ type: 'text', text: 'plain' }] }
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result }
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toBe(result)
|
||||
})
|
||||
|
||||
it('keeps masking values learned earlier even after they rotate out of the response', async () => {
|
||||
const realNow = Date.now
|
||||
const fetchMock = stubShellEnvFetch({ env: {}, mask: ['first-secret'] })
|
||||
const plugin = await loadPlugin()
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ env: {}, mask: ['second-secret'] }) })
|
||||
vi.spyOn(Date, 'now').mockReturnValue(realNow() + 6000)
|
||||
await plugin.triggerShellCreateBefore({ command: 'ls', cwd: '/repo', env: {} })
|
||||
|
||||
const event: ToolExecuteAfterEvent = { tool: 'shell', status: 'completed', result: { output: 'first-secret and second-secret' } }
|
||||
|
||||
await plugin.triggerToolExecuteAfter(event)
|
||||
|
||||
expect(event.result).toEqual({ output: '*** and ***' })
|
||||
})
|
||||
|
||||
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 {} }')
|
||||
|
||||
@@ -655,7 +655,7 @@ describe('ocm-manager plugin', () => {
|
||||
it('rejects non-allow-listed routes without calling the API', async () => {
|
||||
const tool = await loadTool(configHome)
|
||||
const deniedRoutes = [
|
||||
['GET', '/git-credentials/gh-env'],
|
||||
['GET', '/shell-env'],
|
||||
['POST', '/sandbox/shell'],
|
||||
['GET', '/repos/0/mirror/head'],
|
||||
['POST', '/notifications/send'],
|
||||
@@ -707,7 +707,7 @@ describe('ocm-manager plugin', () => {
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
await expect(
|
||||
runTool(tool, { action: 'request', params: { method: 'GET', path: '/repos/x/../../git-credentials/gh-env' } }),
|
||||
runTool(tool, { action: 'request', params: { method: 'GET', path: '/repos/x/../../shell-env' } }),
|
||||
).rejects.toThrow(/is not an allowed OpenCode Manager route/)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '../../src/services/opencode-sandbox-plugin'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
import {
|
||||
SANDBOX_FORWARDED_ENV_NAMES,
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
SANDBOX_SHELL_ENV_NAME,
|
||||
SANDBOX_SHELL_ENV_WORKDIR,
|
||||
sandboxShellShimPath,
|
||||
@@ -284,6 +284,8 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(statSync(shimPath).mode & 0o100).not.toBe(0)
|
||||
expect(shim.startsWith('#!/bin/sh')).toBe(true)
|
||||
expect(shim).toContain(`$${SANDBOX_SHELL_ENV_WORKDIR}`)
|
||||
expect(shim).toContain(`\${${SANDBOX_SHELL_ENV_FORWARD}}`)
|
||||
expect(pluginSource).toContain(`var ENV_FORWARD = ${JSON.stringify(SANDBOX_SHELL_ENV_FORWARD)}`)
|
||||
expect(pluginSource).toContain(`var SHELL_SHIM_PATH = ${JSON.stringify(shimPath)}`)
|
||||
})
|
||||
|
||||
@@ -374,6 +376,7 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(createEvent.shell).toBe(sandboxShellShimPath(configHome))
|
||||
expect(createEvent.env[SANDBOX_SHELL_ENV_WORKDIR]).toBe(WORKDIR)
|
||||
expect(createEvent.env[SANDBOX_SHELL_ENV_NAME]).toBe(PLAN_NAME)
|
||||
expect(createEvent.env[SANDBOX_SHELL_ENV_FORWARD]).toBe('')
|
||||
const planCall = fetchMock.mock.calls.find(([url]) => String(url).endsWith('/sandbox/shell'))
|
||||
expect(planCall).toBeDefined()
|
||||
const [url, init] = planCall as [string, { body: string; headers: Record<string, string> }]
|
||||
@@ -403,6 +406,9 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(() => {
|
||||
createEvent.env[SANDBOX_SHELL_ENV_NAME] = 'other'
|
||||
}).toThrow(message)
|
||||
expect(() => {
|
||||
createEvent.env[SANDBOX_SHELL_ENV_FORWARD] = 'EVIL'
|
||||
}).toThrow(message)
|
||||
|
||||
expect(createEvent.shell).toBe(sandboxShellShimPath(configHome))
|
||||
expect(createEvent.env[SANDBOX_SHELL_ENV_WORKDIR]).toBe(WORKDIR)
|
||||
@@ -410,9 +416,10 @@ describe('ocm-sandbox plugin', () => {
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent, 'shell')?.configurable).toBe(false)
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent.env, SANDBOX_SHELL_ENV_WORKDIR)?.configurable).toBe(false)
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent.env, SANDBOX_SHELL_ENV_NAME)?.configurable).toBe(false)
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent.env, SANDBOX_SHELL_ENV_FORWARD)?.configurable).toBe(false)
|
||||
})
|
||||
|
||||
it('forwards only the allow-listed plan env values into the spawn environment', async () => {
|
||||
it('forwards the plan env names it can represent and pins the forward list', async () => {
|
||||
const plugin = await loadPlugin(configHome)
|
||||
const fetchMock = managerFetch({
|
||||
session: { sandboxed: true },
|
||||
@@ -421,7 +428,16 @@ describe('ocm-sandbox plugin', () => {
|
||||
mode: 'sandbox',
|
||||
workdir: WORKDIR,
|
||||
name: PLAN_NAME,
|
||||
env: { GH_TOKEN: 'gh-secret', OCM_INTERNAL_TOKEN: 'must-not-be-forwarded', GIT_CONFIG_COUNT: '1' },
|
||||
env: {
|
||||
GH_TOKEN: 'gh-secret',
|
||||
GIT_CONFIG_COUNT: '1',
|
||||
OPENAI_API_KEY: 'sk-secret',
|
||||
OCM_INTERNAL_TOKEN: 'must-not-be-forwarded',
|
||||
MSB_SECRET: 'must-not-be-forwarded',
|
||||
'1BAD': 'invalid',
|
||||
'A-B': 'invalid',
|
||||
NUMERIC: 5,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -431,12 +447,14 @@ describe('ocm-sandbox plugin', () => {
|
||||
|
||||
expect(createEvent.env.GH_TOKEN).toBe('gh-secret')
|
||||
expect(createEvent.env.GIT_CONFIG_COUNT).toBe('1')
|
||||
expect(createEvent.env.OPENAI_API_KEY).toBe('sk-secret')
|
||||
expect(createEvent.env.OCM_INTERNAL_TOKEN).toBeUndefined()
|
||||
for (const name of Object.keys(createEvent.env)) {
|
||||
if (createEvent.env[name] === undefined) continue
|
||||
if (name === SANDBOX_SHELL_ENV_WORKDIR || name === SANDBOX_SHELL_ENV_NAME || name === 'TERM' || name === 'OPENCODE_TERMINAL') continue
|
||||
expect(SANDBOX_FORWARDED_ENV_NAMES).toContain(name)
|
||||
}
|
||||
expect(createEvent.env.MSB_SECRET).toBeUndefined()
|
||||
expect(createEvent.env['1BAD']).toBeUndefined()
|
||||
expect(createEvent.env['A-B']).toBeUndefined()
|
||||
expect(createEvent.env.NUMERIC).toBeUndefined()
|
||||
expect(createEvent.env[SANDBOX_SHELL_ENV_FORWARD]).toBe('GH_TOKEN GIT_CONFIG_COUNT OPENAI_API_KEY')
|
||||
expect(Object.getOwnPropertyDescriptor(createEvent.env, SANDBOX_SHELL_ENV_FORWARD)?.configurable).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves an unmarked spawn on the host without planning', async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { execSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
@@ -340,7 +341,7 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.repoFile.error).toContain('Does not match the project file schema')
|
||||
expect(config.actions).toEqual([])
|
||||
})
|
||||
|
||||
@@ -352,7 +353,7 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.repoFile.error).toContain('Does not match the project file schema')
|
||||
expect(config.repoFile.executable).toBeNull()
|
||||
})
|
||||
|
||||
@@ -529,6 +530,93 @@ describe('ProjectConfigService repository file', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('hashes a file without env exactly like the legacy executable shape', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
const legacyHash = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
actions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: null, autoOpenUrl: false }],
|
||||
setup: [],
|
||||
}),
|
||||
)
|
||||
.digest('hex')
|
||||
|
||||
expect(config.repoFile.hash).toBe(legacyHash)
|
||||
})
|
||||
|
||||
it('changes the hash and drops trust when env is added or edited', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
const base = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, base.repoFile.hash ?? '')
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }],
|
||||
env: { TOKEN: '${{ secrets.TOKEN }}' },
|
||||
})
|
||||
const withEnv = await service.getConfig(repo, directory)
|
||||
expect(withEnv.repoFile.hash).not.toBe(base.repoFile.hash)
|
||||
expect(withEnv.repoFile.trusted).toBe(false)
|
||||
|
||||
await service.trustRepoFile(repo, directory, withEnv.repoFile.hash ?? '')
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }],
|
||||
env: { TOKEN: '${{ secrets.OTHER }}' },
|
||||
})
|
||||
const edited = await service.getConfig(repo, directory)
|
||||
expect(edited.repoFile.hash).not.toBe(withEnv.repoFile.hash)
|
||||
expect(edited.repoFile.trusted).toBe(false)
|
||||
})
|
||||
|
||||
it('includes environment and env in the executable snapshot only when present', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
expect((await service.getConfig(repo, directory)).repoFile.executable).not.toHaveProperty('env')
|
||||
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }],
|
||||
environment: 'Prod',
|
||||
env: { TOKEN: '${{ secrets.TOKEN }}' },
|
||||
})
|
||||
const config = await service.getConfig(repo, directory)
|
||||
expect(config.repoFile.executable?.environment).toBe('prod')
|
||||
expect(config.repoFile.executable?.env).toEqual({ TOKEN: '${{ secrets.TOKEN }}' })
|
||||
})
|
||||
|
||||
it('counts an untrusted env mapping as executable content when moving an action', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
writeRepoFile({ version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } })
|
||||
|
||||
await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })
|
||||
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
})
|
||||
|
||||
it('counts an untrusted environment selector as executable content when moving an action', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
writeRepoFile({ version: 1, environment: 'prod' })
|
||||
|
||||
await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })
|
||||
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
})
|
||||
|
||||
it('reports the first schema issue with its path and message', async () => {
|
||||
writeRepoFile({ version: 1, env: { TOKEN: '${{ github.sha }}' } })
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toContain('Does not match the project file schema')
|
||||
expect(config.repoFile.error).toContain('env.TOKEN')
|
||||
expect(config.repoFile.error).toContain('Unsupported expression')
|
||||
})
|
||||
|
||||
it('rejects moving an unknown personal action', async () => {
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({
|
||||
status: 404,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { execSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
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 { logger } from '../../src/utils/logger'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
|
||||
const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService
|
||||
|
||||
const EMPTY = { env: {}, maskValues: [], missing: [] }
|
||||
|
||||
describe('RepoEnvService', () => {
|
||||
let db: Database
|
||||
let projectConfigService: ProjectConfigService
|
||||
let secretsService: SecretsService
|
||||
let repoEnvService: RepoEnvService
|
||||
let tempDirs: string[]
|
||||
|
||||
function createTempDir(prefix: string): string {
|
||||
const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
function initGitRepo(dir: string): void {
|
||||
execSync(`git init "${dir}"`)
|
||||
execSync(`git -C "${dir}" config user.email test@test.com`)
|
||||
execSync(`git -C "${dir}" config user.name Test`)
|
||||
execSync(`git -C "${dir}" commit --allow-empty -m "Initial commit"`)
|
||||
}
|
||||
|
||||
function writeProjectFile(dir: string, content: unknown): void {
|
||||
const filePath = path.join(dir, '.ocm', 'project.json')
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, JSON.stringify(content, null, 2))
|
||||
}
|
||||
|
||||
function registerRepo(dir: string): Repo {
|
||||
return createRepo(db, {
|
||||
localPath: dir,
|
||||
sourcePath: dir,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function trust(dir: string, repo: Repo): Promise<void> {
|
||||
const hash = projectConfigService.readRepoFile(dir).hash
|
||||
await projectConfigService.trustRepoFile(repo, dir, hash ?? '')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
|
||||
secretsService = new SecretsService(db)
|
||||
repoEnvService = new RepoEnvService(db, projectConfigService, secretsService)
|
||||
tempDirs = []
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
for (const dir of tempDirs) {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves a trusted mapping with secret precedence and the selected environment', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, {
|
||||
version: 1,
|
||||
environment: 'prod',
|
||||
env: {
|
||||
API_URL: 'https://${{ vars.HOST }}/${{ secrets.TOKEN }}',
|
||||
PLAIN: 'literal',
|
||||
},
|
||||
})
|
||||
secretsService.set('variable', repo.id, 'prod', 'HOST', 'example.com')
|
||||
secretsService.set('secret', repo.id, null, 'TOKEN', 'repo-token')
|
||||
secretsService.set('secret', repo.id, 'prod', 'TOKEN', 'prod-token')
|
||||
await trust(root, repo)
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(root)
|
||||
|
||||
expect(result.env).toEqual({
|
||||
API_URL: 'https://example.com/prod-token',
|
||||
PLAIN: 'literal',
|
||||
})
|
||||
expect(result.maskValues).toEqual(['prod-token'])
|
||||
expect(result.missing).toEqual([])
|
||||
})
|
||||
|
||||
it('returns an empty result for an untrusted mapping', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } })
|
||||
secretsService.set('secret', repo.id, null, 'TOKEN', 'prod-token')
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
})
|
||||
|
||||
it('returns an empty result when the file has no env mapping', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
await trust(root, repo)
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
})
|
||||
|
||||
it('resolves from a subdirectory of the checkout', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { PLAIN: 'literal' } })
|
||||
await trust(root, repo)
|
||||
const nested = path.join(root, 'packages', 'app')
|
||||
fs.mkdirSync(nested, { recursive: true })
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(nested)
|
||||
|
||||
expect(result.env).toEqual({ PLAIN: 'literal' })
|
||||
})
|
||||
|
||||
it('resolves a git worktree outside the repository folder to the main repo', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { PLAIN: 'literal' } })
|
||||
execSync(`git -C "${root}" add -A`)
|
||||
execSync(`git -C "${root}" commit -m "Add project config"`)
|
||||
const repo = registerRepo(root)
|
||||
await trust(root, repo)
|
||||
const worktreePath = createTempDir('ocm-repo-env-worktree-')
|
||||
fs.rmSync(worktreePath, { recursive: true, force: true })
|
||||
execSync(`git -C "${root}" worktree add -b feature "${worktreePath}"`)
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(worktreePath)
|
||||
|
||||
expect(result.env).toEqual({ PLAIN: 'literal' })
|
||||
})
|
||||
|
||||
it('returns an empty result for a non-git directory', async () => {
|
||||
const plain = createTempDir('ocm-repo-env-plain-')
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(plain)).toEqual(EMPTY)
|
||||
})
|
||||
|
||||
it('reports missing references and resolves them to an empty string', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, {
|
||||
version: 1,
|
||||
env: { MISSING: '${{ secrets.NOPE }}-${{ vars.NOPE2 }}' },
|
||||
})
|
||||
await trust(root, repo)
|
||||
|
||||
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 () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, {
|
||||
version: 1,
|
||||
env: {
|
||||
LONG: '${{ secrets.LONG }}',
|
||||
SHORT: '${{ secrets.SHORT }}',
|
||||
FROM_VAR: '${{ vars.VAR }}',
|
||||
},
|
||||
})
|
||||
secretsService.set('secret', repo.id, null, 'LONG', 'longvalue')
|
||||
secretsService.set('secret', repo.id, null, 'SHORT', 'abc')
|
||||
secretsService.set('variable', repo.id, null, 'VAR', 'variablevalue')
|
||||
await trust(root, repo)
|
||||
|
||||
const result = await repoEnvService.resolveForDirectory(root)
|
||||
|
||||
expect(result.maskValues).toEqual(['longvalue'])
|
||||
})
|
||||
|
||||
it('returns an empty result and warns when the secrets resolver fails', async () => {
|
||||
const root = createTempDir('ocm-repo-env-')
|
||||
initGitRepo(root)
|
||||
const repo = registerRepo(root)
|
||||
writeProjectFile(root, { version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } })
|
||||
await trust(root, repo)
|
||||
vi.spyOn(secretsService, 'resolveValues').mockImplementation(() => {
|
||||
throw new Error('boom')
|
||||
})
|
||||
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined)
|
||||
|
||||
expect(await repoEnvService.resolveForDirectory(root)).toEqual(EMPTY)
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining(root), expect.anything())
|
||||
|
||||
warn.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -32,6 +32,7 @@ import { executeCommand } from '../../../src/utils/process'
|
||||
import { detectSandboxCapability } from '../../../src/services/sandbox/capability'
|
||||
import { logger } from '../../../src/utils/logger'
|
||||
import { forceProcessAttestation } from '../../../src/services/opencode/process-identity'
|
||||
import type { RepoEnvService } from '../../../src/services/repo-env'
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
@@ -525,6 +526,43 @@ describe('SandboxRuntimeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('includes the repository env in the sandbox plan env after the git env', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('inspect')) return { exitCode: 0, stdout: runningInspectOutput(inspectConfig(vm(), VM_NAME), VM_NAME), stderr: '' }
|
||||
if (args.includes('config') && args.includes('user.name')) {
|
||||
return { exitCode: 0, stdout: 'local\tfile:/repo/.git/config\tLocal User\n', stderr: '' }
|
||||
}
|
||||
if (args.includes('config') && args.includes('user.email')) {
|
||||
return { exitCode: 0, stdout: 'local\tfile:/repo/.git/config\tlocal@example.com\n', stderr: '' }
|
||||
}
|
||||
return { exitCode: 0, stdout: '[]', stderr: '' }
|
||||
})
|
||||
const repoEnvService = {
|
||||
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)
|
||||
|
||||
const plan = await withRepoEnv.planShell(repoADir, shellTarget(repoADir))
|
||||
|
||||
expect(plan).toEqual({
|
||||
mode: 'sandbox',
|
||||
name: VM_NAME,
|
||||
workdir: repoADir,
|
||||
env: {
|
||||
GIT_AUTHOR_NAME: 'Repo User',
|
||||
GIT_AUTHOR_EMAIL: 'local@example.com',
|
||||
GIT_COMMITTER_NAME: 'Local User',
|
||||
GIT_COMMITTER_EMAIL: 'local@example.com',
|
||||
REPO_SECRET: 's3cret',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('starts an existing stopped sandbox instead of recreating it', async () => {
|
||||
enableEnforcement()
|
||||
const vms = new Map<string, FakeVm>([[VM_NAME, vm({ running: false })]])
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { sessionSandboxName } from '../../../src/services/sandbox/command'
|
||||
import {
|
||||
SANDBOX_FORWARDED_ENV_NAMES,
|
||||
SANDBOX_SHELL_ENV_FORWARD,
|
||||
SANDBOX_SHELL_ENV_NAME,
|
||||
SANDBOX_SHELL_ENV_WORKDIR,
|
||||
} from '../../../src/services/sandbox/shell-shim'
|
||||
@@ -38,6 +39,7 @@ 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]
|
||||
return { ...env, ...overrides }
|
||||
}
|
||||
|
||||
@@ -96,7 +98,7 @@ describe('sandbox shell shim', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards only the allow-listed credential env into the guest as -e pairs, ahead of the command', async () => {
|
||||
it('forwards the planned names and the always-forwarded git 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')
|
||||
@@ -118,9 +120,11 @@ describe('sandbox shell shim', () => {
|
||||
env: sandboxShellEnv({
|
||||
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
|
||||
[SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME,
|
||||
[SANDBOX_SHELL_ENV_FORWARD]: 'GIT_CONFIG_COUNT GIT_CONFIG_KEY_0 GIT_CONFIG_VALUE_0',
|
||||
GIT_CONFIG_COUNT: '1',
|
||||
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
|
||||
GIT_CONFIG_VALUE_0: extraheaderValue,
|
||||
GH_TOKEN: 'inherited-must-not-be-forwarded',
|
||||
OCM_INTERNAL_TOKEN: 'must-not-be-forwarded',
|
||||
}),
|
||||
})
|
||||
@@ -130,19 +134,121 @@ describe('sandbox shell shim', () => {
|
||||
|
||||
expect(argv).toContain('-e')
|
||||
expect(argv).toContain('GIT_CONFIG_COUNT=1')
|
||||
expect(argv).toContain('GIT_CONFIG_KEY_0=http.https://github.com/.extraheader')
|
||||
expect(argv).toContain(`GIT_CONFIG_VALUE_0=${extraheaderValue}`)
|
||||
|
||||
const separatorIndex = argv.indexOf('--')
|
||||
expect(argv.slice(separatorIndex)).toEqual(['--', 'sh', '-c', 'echo -e sentinel'])
|
||||
expect(argv.slice(0, separatorIndex).filter((element) => element === '-e')).toHaveLength(3)
|
||||
expect(argv.slice(0, separatorIndex).filter((element) => element === '-e')).toHaveLength(4)
|
||||
|
||||
expect(argv).toContain('GH_TOKEN=inherited-must-not-be-forwarded')
|
||||
expect(argv.some((element) => element.startsWith('OCM_INTERNAL_TOKEN='))).toBe(false)
|
||||
for (const element of argv) {
|
||||
if (!element.includes('=') || element === '--') continue
|
||||
const name = element.slice(0, element.indexOf('='))
|
||||
if (!SANDBOX_FORWARDED_ENV_NAMES.includes(name as never)) continue
|
||||
expect(SANDBOX_FORWARDED_ENV_NAMES).toContain(name)
|
||||
} finally {
|
||||
if (originalMsbPath === undefined) {
|
||||
delete process.env.MSB_PATH
|
||||
} else {
|
||||
process.env.MSB_PATH = originalMsbPath
|
||||
}
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
rmSync(configHome, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('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-'))
|
||||
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 marker = path.join(fakeBin, 'injected.marker')
|
||||
const substitutionName = `$(touch ${marker})`
|
||||
const result = spawnSync(shimPath, ['-c', 'echo invalid-sentinel'], {
|
||||
encoding: 'utf8',
|
||||
env: sandboxShellEnv({
|
||||
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
|
||||
[SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME,
|
||||
[SANDBOX_SHELL_ENV_FORWARD]: `1BAD A-B ${substitutionName} OCM_INTERNAL_TOKEN MSB_SECRET GOOD_ONE`,
|
||||
'1BAD': 'leading-digit',
|
||||
'A-B': 'dash',
|
||||
[substitutionName]: 'substitution',
|
||||
OCM_INTERNAL_TOKEN: 'reserved-ocm',
|
||||
MSB_SECRET: 'reserved-msb',
|
||||
GOOD_ONE: 'forwarded',
|
||||
}),
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('invalid-sentinel\n')
|
||||
expect(existsSync(marker)).toBe(false)
|
||||
|
||||
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
|
||||
expect(argv.filter((element) => element === '-e')).toHaveLength(1)
|
||||
expect(argv).toContain('GOOD_ONE=forwarded')
|
||||
expect(argv.some((element) => element.startsWith('OCM_INTERNAL_TOKEN='))).toBe(false)
|
||||
expect(argv.some((element) => element.startsWith('MSB_SECRET='))).toBe(false)
|
||||
expect(argv.some((element) => element.startsWith('1BAD='))).toBe(false)
|
||||
expect(argv.some((element) => element.startsWith('A-B='))).toBe(false)
|
||||
} finally {
|
||||
if (originalMsbPath === undefined) {
|
||||
delete process.env.MSB_PATH
|
||||
} else {
|
||||
process.env.MSB_PATH = originalMsbPath
|
||||
}
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
rmSync(configHome, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('passes forwarded values with spaces, quotes, dollars, and newlines verbatim as single arguments', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-values-'))
|
||||
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 plain = 'a b c'
|
||||
const quoted = 'it\'s "quoted"'
|
||||
const dollar = '$HOME ${not_expanded} `backtick`'
|
||||
const multiline = 'line1\nline2'
|
||||
const result = spawnSync(shimPath, ['-c', 'echo verbatim-sentinel'], {
|
||||
encoding: 'utf8',
|
||||
env: sandboxShellEnv({
|
||||
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
|
||||
[SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME,
|
||||
[SANDBOX_SHELL_ENV_FORWARD]: 'PLAIN QUOTED DOLLAR MULTILINE',
|
||||
PLAIN: plain,
|
||||
QUOTED: quoted,
|
||||
DOLLAR: dollar,
|
||||
MULTILINE: multiline,
|
||||
}),
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('verbatim-sentinel\n')
|
||||
|
||||
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
|
||||
expect(argv.filter((element) => element === '-e')).toHaveLength(4)
|
||||
expect(argv).toContain(`PLAIN=${plain}`)
|
||||
expect(argv).toContain(`QUOTED=${quoted}`)
|
||||
expect(argv).toContain(`DOLLAR=${dollar}`)
|
||||
expect(argv).toContain(`MULTILINE=${multiline}`)
|
||||
} finally {
|
||||
if (originalMsbPath === undefined) {
|
||||
delete process.env.MSB_PATH
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { SecretsService, SecretsServiceError } from '../../src/services/secrets'
|
||||
import { decryptSecret } from '../../src/utils/crypto'
|
||||
import { logger } from '../../src/utils/logger'
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
function readStoredValue(db: Database, name: string): string {
|
||||
const row = db.prepare('SELECT value FROM secrets WHERE name = ?').get(name) as { value: string } | undefined
|
||||
return row?.value ?? ''
|
||||
}
|
||||
|
||||
describe('SecretsService', () => {
|
||||
let db: Database
|
||||
let service: SecretsService
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
service = new SecretsService(db)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('stores secret values encrypted at rest and decrypts them on resolve', () => {
|
||||
service.set('secret', null, null, 'TOKEN', 'super-secret')
|
||||
|
||||
const stored = readStoredValue(db, 'TOKEN')
|
||||
expect(stored).not.toBe('super-secret')
|
||||
expect(decryptSecret(stored)).toBe('super-secret')
|
||||
|
||||
expect(service.resolveValues(1, null).secrets.TOKEN).toBe('super-secret')
|
||||
})
|
||||
|
||||
it('stores variable values in plain text', () => {
|
||||
service.set('variable', null, null, 'LOG_LEVEL', 'debug')
|
||||
|
||||
expect(readStoredValue(db, 'LOG_LEVEL')).toBe('debug')
|
||||
expect(service.resolveValues(1, null).vars.LOG_LEVEL).toBe('debug')
|
||||
})
|
||||
|
||||
it('omits secret values from list but includes variable values', () => {
|
||||
service.set('secret', null, null, 'TOKEN', 'super-secret')
|
||||
service.set('variable', null, null, 'LOG_LEVEL', 'debug')
|
||||
|
||||
const secrets = service.list('secret', null)
|
||||
expect(secrets).toHaveLength(1)
|
||||
expect(secrets[0]).not.toHaveProperty('value')
|
||||
|
||||
const variables = service.list('variable', null)
|
||||
expect(variables).toHaveLength(1)
|
||||
expect(variables[0]?.value).toBe('debug')
|
||||
})
|
||||
|
||||
it('upserts an existing entry and refreshes updatedAt', () => {
|
||||
const nowSpy = vi.spyOn(Date, 'now')
|
||||
nowSpy.mockReturnValueOnce(1000)
|
||||
service.set('variable', null, null, 'LOG_LEVEL', 'info')
|
||||
|
||||
nowSpy.mockReturnValueOnce(2000)
|
||||
service.set('variable', null, null, 'LOG_LEVEL', 'debug')
|
||||
|
||||
const variables = service.list('variable', null)
|
||||
expect(variables).toHaveLength(1)
|
||||
expect(variables[0]?.value).toBe('debug')
|
||||
expect(variables[0]?.updatedAt).toBe(2000)
|
||||
})
|
||||
|
||||
it('rejects an environment for a global entry', () => {
|
||||
expect(() => service.set('secret', null, 'prod', 'TOKEN', 'value')).toThrow(SecretsServiceError)
|
||||
|
||||
try {
|
||||
service.set('secret', null, 'prod', 'TOKEN', 'value')
|
||||
} catch (error) {
|
||||
expect((error as SecretsServiceError).statusCode).toBe(400)
|
||||
}
|
||||
})
|
||||
|
||||
it('deletes an entry and reports whether it existed', () => {
|
||||
service.set('variable', null, null, 'LOG_LEVEL', 'debug')
|
||||
|
||||
expect(service.delete('variable', null, null, 'LOG_LEVEL')).toBe(true)
|
||||
expect(service.delete('variable', null, null, 'LOG_LEVEL')).toBe(false)
|
||||
expect(service.list('variable', null)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('lists a repository entries across all environments with empty environment mapped to null', () => {
|
||||
service.set('variable', 7, null, 'PLAIN', 'plain')
|
||||
service.set('variable', 7, 'prod', 'SCOPED', 'scoped')
|
||||
|
||||
const variables = service.list('variable', 7)
|
||||
expect(variables).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ name: 'PLAIN', environment: null }),
|
||||
expect.objectContaining({ name: 'SCOPED', environment: 'prod' }),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('resolves values with global < repository < repository+environment precedence', () => {
|
||||
service.set('secret', null, null, 'GLOBAL_ONLY', 'g')
|
||||
service.set('secret', 7, null, 'SHARED', 'repo')
|
||||
service.set('secret', 7, 'prod', 'SHARED', 'prod')
|
||||
service.set('variable', null, null, 'VAR_GLOBAL', 'vg')
|
||||
service.set('variable', 7, null, 'VAR_SHARED', 'vrepo')
|
||||
service.set('variable', 7, 'prod', 'VAR_SHARED', 'vprod')
|
||||
|
||||
const production = service.resolveValues(7, 'prod')
|
||||
expect(production.secrets).toEqual({ GLOBAL_ONLY: 'g', SHARED: 'prod' })
|
||||
expect(production.vars).toEqual({ VAR_GLOBAL: 'vg', VAR_SHARED: 'vprod' })
|
||||
|
||||
const withoutEnvironment = service.resolveValues(7, null)
|
||||
expect(withoutEnvironment.secrets).toEqual({ GLOBAL_ONLY: 'g', SHARED: 'repo' })
|
||||
expect(withoutEnvironment.vars).toEqual({ VAR_GLOBAL: 'vg', VAR_SHARED: 'vrepo' })
|
||||
|
||||
const otherRepo = service.resolveValues(8, 'prod')
|
||||
expect(otherRepo.secrets).toEqual({ GLOBAL_ONLY: 'g' })
|
||||
expect(otherRepo.vars).toEqual({ VAR_GLOBAL: 'vg' })
|
||||
})
|
||||
|
||||
it('skips a secret that cannot be decrypted and logs only its name', () => {
|
||||
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
const now = Date.now()
|
||||
db.prepare(
|
||||
'INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
).run('secret', null, '', 'BROKEN', 'not-a-valid-encrypted-value', now, now)
|
||||
|
||||
const resolved = service.resolveValues(1, null)
|
||||
expect(resolved.secrets).not.toHaveProperty('BROKEN')
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
expect(warn.mock.calls[0]?.[0]).toContain('BROKEN')
|
||||
expect(warn.mock.calls[0]?.[0]).not.toContain('not-a-valid-encrypted-value')
|
||||
})
|
||||
})
|
||||
@@ -2,6 +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'
|
||||
|
||||
interface PtyRecord {
|
||||
id: string
|
||||
@@ -45,6 +46,12 @@ 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,
|
||||
@@ -55,6 +62,7 @@ function createTerminalService(
|
||||
return new TerminalService(
|
||||
{ client, baseUrl: () => baseUrl, includeLocalCredentials },
|
||||
provider,
|
||||
createRepoEnvService(),
|
||||
openSocket,
|
||||
)
|
||||
}
|
||||
@@ -224,6 +232,27 @@ describe('TerminalService', () => {
|
||||
|
||||
expect(captured).toMatchObject({ command: '/bin/zsh', args: ['-l'] })
|
||||
})
|
||||
|
||||
it('merges the repository env between the GitHub env and the input env', async () => {
|
||||
const create = vi.fn(async () => ({
|
||||
location: { directory: '/repo' },
|
||||
data: createPty({ id: 'pty-new', title: 'Terminal' }),
|
||||
}))
|
||||
const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh', SHARED: 'gh' })
|
||||
const repoEnvService = createRepoEnvService({ REPO_VAR: 'repo', SHARED: 'repo' })
|
||||
const service = new TerminalService(
|
||||
{ client: createClient({ create }), baseUrl: () => 'http://127.0.0.1:5551', includeLocalCredentials: true },
|
||||
credentialProvider,
|
||||
repoEnvService,
|
||||
)
|
||||
|
||||
await service.create('/repo', { kind: 'shell', name: 'Terminal', env: { FOO: 'bar', SHARED: 'input' } })
|
||||
|
||||
expect(repoEnvService.resolveForDirectory).toHaveBeenCalledWith('/repo')
|
||||
expect(create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ env: { GH_TOKEN: 'gh', REPO_VAR: 'repo', FOO: 'bar', SHARED: 'input' } }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hub capture', () => {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { interpolateEnvExpressions, parseEnvExpressionReferences } from '@opencode-manager/shared/utils'
|
||||
|
||||
describe('parseEnvExpressionReferences', () => {
|
||||
it('accepts a single secrets reference', () => {
|
||||
expect(parseEnvExpressionReferences('${{ secrets.TOKEN }}')).toEqual({
|
||||
ok: true,
|
||||
references: [{ context: 'secrets', name: 'TOKEN' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts interpolation inside a larger string and multiple references', () => {
|
||||
expect(parseEnvExpressionReferences('Bearer ${{ secrets.TOKEN }} on ${{ vars.HOST }}')).toEqual({
|
||||
ok: true,
|
||||
references: [
|
||||
{ context: 'secrets', name: 'TOKEN' },
|
||||
{ context: 'vars', name: 'HOST' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('treats the context case-insensitively and upper-cases the name', () => {
|
||||
expect(parseEnvExpressionReferences('${{ Secrets.my_token }}')).toEqual({
|
||||
ok: true,
|
||||
references: [{ context: 'secrets', name: 'MY_TOKEN' }],
|
||||
})
|
||||
expect(parseEnvExpressionReferences('${{ VARS.Host }}')).toEqual({
|
||||
ok: true,
|
||||
references: [{ context: 'vars', name: 'HOST' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('returns no references for a literal value', () => {
|
||||
expect(parseEnvExpressionReferences('plain value')).toEqual({ ok: true, references: [] })
|
||||
})
|
||||
|
||||
it('rejects an unknown context', () => {
|
||||
const result = parseEnvExpressionReferences('${{ github.sha }}')
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) {
|
||||
expect(result.error).toContain('${{ github.sha }}')
|
||||
expect(result.error).toContain('secrets.<NAME>')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an operator inside the expression', () => {
|
||||
expect(parseEnvExpressionReferences("${{ secrets.A || 'x' }}").ok).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a function call inside the expression', () => {
|
||||
expect(parseEnvExpressionReferences("${{ format('{0}', vars.A) }}").ok).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a reference with an invalid name', () => {
|
||||
expect(parseEnvExpressionReferences('${{ secrets.1BAD }}').ok).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('interpolateEnvExpressions', () => {
|
||||
const lookup = (reference: { context: string; name: string }): string | undefined => {
|
||||
const values: Record<string, string> = {
|
||||
'secrets.TOKEN': 'super-secret',
|
||||
'vars.HOST': 'example.com',
|
||||
}
|
||||
return values[`${reference.context}.${reference.name}`]
|
||||
}
|
||||
|
||||
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', () => {
|
||||
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 a literal value untouched', () => {
|
||||
expect(interpolateEnvExpressions('literal', lookup)).toEqual({ value: 'literal', missing: [] })
|
||||
})
|
||||
})
|
||||
@@ -24,3 +24,4 @@ export * from './project-config'
|
||||
export * from './preview'
|
||||
export * from './change-walkthroughs'
|
||||
export * from './opencode-servers'
|
||||
export * from './secrets'
|
||||
@@ -1,5 +1,7 @@
|
||||
import { z } from 'zod'
|
||||
import { TerminalInfoSchema } from './terminal'
|
||||
import { EnvironmentNameSchema, isReservedEnvName } from './secrets'
|
||||
import { parseEnvExpressionReferences } from '../utils/env-expressions'
|
||||
|
||||
export const ProjectActionIconSchema = z.enum([
|
||||
'play',
|
||||
@@ -30,10 +32,42 @@ export const WorktreeSetupCommandsSchema = z.array(z.string().trim().min(1).max(
|
||||
|
||||
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_]*$/
|
||||
|
||||
export const RepoProjectEnvValueSchema = z
|
||||
.string()
|
||||
.max(4000, 'Environment value must be at most 4000 characters')
|
||||
.superRefine((value, ctx) => {
|
||||
const parsed = parseEnvExpressionReferences(value)
|
||||
if (!parsed.ok) {
|
||||
ctx.addIssue({ code: 'custom', message: parsed.error })
|
||||
}
|
||||
})
|
||||
|
||||
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)) {
|
||||
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] })
|
||||
}
|
||||
}
|
||||
})
|
||||
.refine(
|
||||
(env) => Object.keys(env).length <= REPO_PROJECT_ENV_MAX_ENTRIES,
|
||||
`At most ${REPO_PROJECT_ENV_MAX_ENTRIES} environment entries are allowed`,
|
||||
)
|
||||
|
||||
export const RepoProjectFileSchema = z.looseObject({
|
||||
version: z.literal(1),
|
||||
projectActions: z.array(ProjectActionSchema).optional(),
|
||||
setupWorktree: WorktreeSetupCommandsSchema.optional(),
|
||||
environment: EnvironmentNameSchema.optional(),
|
||||
env: RepoProjectEnvSchema.optional(),
|
||||
})
|
||||
|
||||
export const ProjectConfigResponseSchema = z.object({
|
||||
@@ -66,6 +100,8 @@ export const ProjectConfigResponseSchema = z.object({
|
||||
}),
|
||||
),
|
||||
setup: z.array(z.string()),
|
||||
environment: z.string().optional(),
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
})
|
||||
.nullable(),
|
||||
error: z.string().optional(),
|
||||
@@ -128,6 +164,7 @@ 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>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { z } from 'zod'
|
||||
import { BLOCKED_SERVER_ENV_KEYS } from './settings'
|
||||
|
||||
export const SecretKindSchema = z.enum(['secret', 'variable'])
|
||||
|
||||
export type SecretKind = z.infer<typeof SecretKindSchema>
|
||||
|
||||
export const SECRET_VALUE_MAX_BYTES = 48 * 1024
|
||||
|
||||
const RESERVED_ENV_PREFIXES = ['OCM_', 'OPENCODE_', 'GIT_CONFIG_', 'MSB_', 'LD_'] as const
|
||||
|
||||
const RESERVED_ENV_NAMES = ['PATH', 'HOME', 'NODE_OPTIONS'] as const
|
||||
|
||||
const BLOCKED_ENV_NAMES = new Set<string>(BLOCKED_SERVER_ENV_KEYS)
|
||||
|
||||
export function isReservedEnvName(name: string): boolean {
|
||||
const normalized = name.toUpperCase()
|
||||
if (BLOCKED_ENV_NAMES.has(normalized)) return true
|
||||
if ((RESERVED_ENV_NAMES as readonly string[]).includes(normalized)) return true
|
||||
return RESERVED_ENV_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
export const SecretNameSchema = z
|
||||
.string()
|
||||
.max(255, 'Name must be at most 255 characters')
|
||||
.regex(
|
||||
/^[A-Za-z_][A-Za-z0-9_]*$/,
|
||||
'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_')
|
||||
.refine((name) => !isReservedEnvName(name), 'Name is reserved for Manager or the runtime')
|
||||
.transform((name) => name.toUpperCase())
|
||||
|
||||
export type SecretName = z.infer<typeof SecretNameSchema>
|
||||
|
||||
export const EnvironmentNameSchema = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[A-Za-z0-9_.-]{1,64}$/,
|
||||
'Environment name must be 1-64 characters of letters, numbers, dots, underscores, or hyphens',
|
||||
)
|
||||
.transform((name) => name.toLowerCase())
|
||||
|
||||
export type EnvironmentName = z.infer<typeof EnvironmentNameSchema>
|
||||
|
||||
const textEncoder = new TextEncoder()
|
||||
|
||||
export const SecretValueSchema = z
|
||||
.string()
|
||||
.min(1, 'Value must not be empty')
|
||||
.refine(
|
||||
(value) => textEncoder.encode(value).length <= SECRET_VALUE_MAX_BYTES,
|
||||
`Value must be at most ${SECRET_VALUE_MAX_BYTES} bytes`,
|
||||
)
|
||||
|
||||
export const SetSecretRequestSchema = z.object({
|
||||
value: SecretValueSchema,
|
||||
environment: EnvironmentNameSchema.optional(),
|
||||
})
|
||||
|
||||
export type SetSecretRequest = z.infer<typeof SetSecretRequestSchema>
|
||||
|
||||
export const SecretEntrySchema = z.object({
|
||||
name: z.string(),
|
||||
environment: z.string().nullable(),
|
||||
updatedAt: z.number(),
|
||||
value: z.string().optional(),
|
||||
})
|
||||
|
||||
export type SecretEntry = z.infer<typeof SecretEntrySchema>
|
||||
|
||||
export const SecretListResponseSchema = z.object({
|
||||
items: z.array(SecretEntrySchema),
|
||||
})
|
||||
|
||||
export type SecretListResponse = z.infer<typeof SecretListResponseSchema>
|
||||
@@ -0,0 +1,72 @@
|
||||
export type EnvExpressionContext = 'secrets' | 'vars'
|
||||
|
||||
export interface EnvExpressionReference {
|
||||
context: EnvExpressionContext
|
||||
name: string
|
||||
}
|
||||
|
||||
export type ParseEnvExpressionReferencesResult =
|
||||
| { ok: true; references: EnvExpressionReference[] }
|
||||
| { ok: false; error: string }
|
||||
|
||||
const ENV_EXPRESSION_PATTERN = /\$\{\{([\s\S]*?)\}\}/g
|
||||
|
||||
const ENV_EXPRESSION_REFERENCE_PATTERN = /^\s*(secrets|vars)\.([A-Za-z_][A-Za-z0-9_]*)\s*$/i
|
||||
|
||||
function toReference(match: RegExpExecArray): EnvExpressionReference {
|
||||
return {
|
||||
context: (match[1] ?? '').toLowerCase() as EnvExpressionContext,
|
||||
name: (match[2] ?? '').toUpperCase(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses every `${{ ... }}` occurrence in a value, accepting only
|
||||
* `secrets.<NAME>` and `vars.<NAME>` references. The context is
|
||||
* case-insensitive and the name is normalized to upper case.
|
||||
*/
|
||||
export function parseEnvExpressionReferences(value: string): ParseEnvExpressionReferencesResult {
|
||||
const references: EnvExpressionReference[] = []
|
||||
|
||||
for (const expression of value.matchAll(ENV_EXPRESSION_PATTERN)) {
|
||||
const reference = ENV_EXPRESSION_REFERENCE_PATTERN.exec(expression[1] ?? '')
|
||||
if (!reference) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Unsupported expression "${expression[0]}": only secrets.<NAME> and vars.<NAME> are supported`,
|
||||
}
|
||||
}
|
||||
references.push(toReference(reference))
|
||||
}
|
||||
|
||||
return { ok: true, references }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function interpolateEnvExpressions(
|
||||
value: string,
|
||||
lookup: (reference: EnvExpressionReference) => string | undefined,
|
||||
): { value: string; missing: EnvExpressionReference[] } {
|
||||
const missing: EnvExpressionReference[] = []
|
||||
|
||||
const interpolated = value.replace(ENV_EXPRESSION_PATTERN, (expression, inner: string) => {
|
||||
const match = ENV_EXPRESSION_REFERENCE_PATTERN.exec(inner)
|
||||
if (!match) {
|
||||
return expression
|
||||
}
|
||||
const reference = toReference(match)
|
||||
const resolved = lookup(reference)
|
||||
if (resolved === undefined) {
|
||||
missing.push(reference)
|
||||
return ''
|
||||
}
|
||||
return resolved
|
||||
})
|
||||
|
||||
return { value: interpolated, missing }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from './env-expressions'
|
||||
export * from './jsonc'
|
||||
export * from './record'
|
||||
export * from './repo'
|
||||
|
||||
Reference in new issue
Block a user