diff --git a/changelog.d/cso-managed-worktree-include-and-fault-codes.md b/changelog.d/cso-managed-worktree-include-and-fault-codes.md new file mode 100644 index 00000000000..3d045bd79c3 --- /dev/null +++ b/changelog.d/cso-managed-worktree-include-and-fault-codes.md @@ -0,0 +1 @@ +- **`/cso` now starts inside a Multica managed worktree, and helper faults are named (CHE-9982).** The launcher rejected every managed worktree with `UNSAFE_PATH` because Multica writes `[include] path = multica-identity.config` into the worktree's `config.worktree`. It now accepts only that shape, and only in the `config.worktree` of a linked worktree whose working tree and Git directories live under the managed workspace root (ordinary clones, shared `config` files and unmanaged linked worktrees still reject every include): a plain relative `[include] path` that resolves to a regular file directly inside the Git directory holding the config, with no nested include. The file is bound and re-checked like the config itself. `includeIf`, subsections, absolute or `..` paths, symlinks and working-tree targets are still rejected. A filesystem fault (for example an unwritable `$HOME`) used to be reported as `INVALID_SCHEMA` "The helper rejected an unexpected or unsafe input"; it is now `PERSISTENCE_FAILED` with the errno and, for the state directory, a `GSTACK_HOME` hint. The root is fixed in the launcher binary at build time (`GSTACK_CSO_MANAGED_ROOT`, else the installer's `MULTICA_TASK_WORKSPACES_ROOT`; a plain absolute path) and the launcher never reads it from the caller, so a caller cannot widen it to enclose an unmanaged worktree. A launcher built without a root rejects every include. Re-run setup after merge so the installed launcher is rebuilt with the root. diff --git a/lib/cso/cli.ts b/lib/cso/cli.ts index c9e0b5d86a8..63cd42d1d7a 100644 --- a/lib/cso/cli.ts +++ b/lib/cso/cli.ts @@ -2919,6 +2919,17 @@ const PRODUCTION_CLI_DEPENDENCIES: CsoCliDependencies = Object.freeze({ catalogImageSession: productionCatalogImageSession, watchdogPath: watchdog, }); +/** + * An exception that is not a CsoError is a helper fault, not a rejected input. + * Filesystem faults keep their errno name so the caller can act on it; only a + * truly unknown exception keeps the opaque INVALID_SCHEMA label. + */ +export function unexpectedFailure(error: unknown): CsoError { + const errno = (error as { code?: unknown } | null)?.code; + if (typeof errno === 'string' && /^E[A-Z0-9]{2,}$/.test(errno)) + return new CsoError('PERSISTENCE_FAILED', `The helper hit a filesystem error (${errno})`); + return new CsoError('INVALID_SCHEMA', 'The helper rejected an unexpected or unsafe input'); +} async function main() { const args = process.argv.slice(2), command = args.shift(); @@ -2949,10 +2960,7 @@ async function main() { } if (import.meta.main) main().catch((error) => { - const e = - error instanceof CsoError - ? error - : new CsoError('INVALID_SCHEMA', 'The helper rejected an unexpected or unsafe input'); + const e = error instanceof CsoError ? error : unexpectedFailure(error); try { process.stderr.write( redact(JSON.stringify({ ok: false, error: { code: e.code, message: e.message } })) + '\n', diff --git a/lib/cso/launcher.c b/lib/cso/launcher.c index 57ebdaeae8f..9bc16a77891 100644 --- a/lib/cso/launcher.c +++ b/lib/cso/launcher.c @@ -25,6 +25,13 @@ #error GSTACK_CSO_CORE_SHA256 must bind the launcher to its compiled core #endif +/* The managed workspace root is fixed when the launcher is built (setup's + * environment), never read from the caller: a caller who could choose it could + * widen it to enclose an unmanaged worktree and unlock Git config includes. */ +#ifndef GSTACK_CSO_MANAGED_ROOT +#define GSTACK_CSO_MANAGED_ROOT "" +#endif + typedef struct { uint32_t state[8]; uint64_t bits; @@ -135,6 +142,7 @@ int main(int argc,char **argv){ envp[e++]=strdup("LANG=C.UTF-8");envp[e++]=strdup("LC_ALL=C.UTF-8");envp[e++]=strdup("TZ=UTC"); const char *names[]={"HOME","GSTACK_HOME","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","DOCKER_HOST","DOCKER_CONTEXT","DOCKER_CONFIG"}; for(size_t i=0;i` lines (what the + * Multica managed-worktree setup writes for its identity defaults). Returns + * undefined for anything else (includeIf, subsections, quoting, escapes, + * other keys, same-line values) so the caller rejects it. + */ +function plainIncludePaths(content: string): string[] | undefined { + const paths: string[] = []; + let inInclude = false; + for (const raw of content.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith('#') || line.startsWith(';')) continue; + if (line.startsWith('[')) { + if (/^\[\s*include\s*\]$/i.test(line)) inInclude = true; + else if (GIT_INCLUDE_SECTION.test(line)) return undefined; + else inInclude = false; + continue; + } + if (!inInclude) continue; + const match = /^path\s*=\s*([A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*)$/i.exec(line); + if (!match || match[1].split('/').some((part) => part === '.' || part === '..')) return undefined; + paths.push(match[1]); + } + return paths; +} +function boundedConfig(path: string, included = false, allowIncludes = false): GitConfigIdentity[] { const file = boundedMetadataFile(path, GIT_CONFIG_LIMIT, 'Repository Git configuration', true); - if (!file) return { path, exists: false }; + if (!file) return [{ path, exists: false, ...(included ? { included } : {}) }]; const { content } = file; // There is no process-wide "--no-includes" switch for ordinary Git // commands. Reject include directives before spawning Git so repository // configuration cannot pull policy or executable settings from elsewhere. - if (/^\s*\[\s*include(?:if)?(?=[\s."\]])/im.test(content)) - throw new CsoError( - 'UNSAFE_PATH', - 'Repository Git config includes are not allowed during a security snapshot', - ); - return { + // The one exception, only when the caller verified a managed worktree (the + // `config.worktree` of a linked worktree): plain relative `[include] path` + // entries that resolve to a regular file directly inside the Git admin + // directory that holds this config (never the working tree, never outside + // it). Each such file is bound like the config itself and may not include + // anything further. Ordinary clones and shared `config` files never qualify. + const identity: GitConfigIdentity = { path, exists: true, + ...(included ? { included } : {}), + ...(allowIncludes ? { allowIncludes } : {}), dev: file.dev, ino: file.ino, mode: file.mode, @@ -423,6 +458,25 @@ function boundedConfig(path: string): GitConfigIdentity { ctimeMs: file.ctimeMs, content, }; + if (!GIT_INCLUDE_SECTION.test(content)) return [identity]; + const targets = included || !allowIncludes ? undefined : plainIncludePaths(content); + if (!targets?.length) throw new CsoError('UNSAFE_PATH', INCLUDE_REJECTED); + const home = realpathSync(dirname(path)); + const bound = targets.map((target) => { + const resolved = join(home, target); + let real: string; + try { + real = realpathSync(resolved); + } catch { + throw new CsoError('UNSAFE_PATH', INCLUDE_REJECTED); + } + if (real !== resolved || !real.startsWith(`${home}${sep}`)) + throw new CsoError('UNSAFE_PATH', INCLUDE_REJECTED); + const leaf = boundedConfig(real, true); + if (!leaf[0].exists) throw new CsoError('UNSAFE_PATH', INCLUDE_REJECTED); + return leaf; + }); + return [identity, ...bound.flat()]; } function gitDirectories(repo: string): { gitDir: string; commonDir: string } { const marker = join(repo, '.git'), @@ -451,18 +505,39 @@ function gitDirectories(repo: string): { gitDir: string; commonDir: string } { } return { gitDir, commonDir }; } +function insideManagedRoot(paths: string[]): boolean { + const configured = process.env.MULTICA_TASK_WORKSPACES_ROOT; + if (!configured || !isAbsolute(configured)) return false; + try { + const root = realpathSync(configured); + return paths.every((path) => realpathSync(path).startsWith(`${root}${sep}`)); + } catch { + return false; + } +} function gitConfigIdentities(repo: string): GitConfigIdentity[] { const { gitDir, commonDir } = gitDirectories(repo); // extensions.worktreeConfig makes config.worktree active in both linked and // main worktrees. Bind even its absence so it cannot appear after inspection // and feed Git an unchecked include or executable setting. - return [join(commonDir, 'config'), join(gitDir, 'config.worktree')].map(boundedConfig); + // Only a Multica-managed worktree's own config.worktree may carry the identity + // include: a linked worktree (gitDir differs from commonDir) whose working + // tree, Git directory and common directory all live under the daemon-set + // MULTICA_TASK_WORKSPACES_ROOT. The shared config, ordinary clones, and an + // unmanaged `git worktree add` elsewhere keep rejecting every include. + const managed = gitDir !== commonDir && insideManagedRoot([repo, gitDir, commonDir]); + return [ + ...boundedConfig(join(commonDir, 'config')), + ...boundedConfig(join(gitDir, 'config.worktree'), false, managed), + ]; } function assertGitConfigIdentities(expected: GitConfigIdentity[]): void { for (const item of expected) { - const current = boundedConfig(item.path); + // An included file is re-read as a leaf; its parent re-validates the include set on its own turn. + const current = boundedConfig(item.path, item.included, item.allowIncludes)[0]; if ( current.exists !== item.exists || + current.included !== item.included || current.dev !== item.dev || current.ino !== item.ino || current.mode !== item.mode || diff --git a/lib/cso/state.ts b/lib/cso/state.ts index c0f3bc12e3f..974f0b24bcb 100644 --- a/lib/cso/state.ts +++ b/lib/cso/state.ts @@ -716,7 +716,11 @@ function ensureDirectory(path: string, hardenExistingLeaf: boolean): string { fs.mkdirSync(cursor, { mode: 0o700 }); created = true; } catch (error: any) { - if (error?.code !== 'EEXIST') throw error; + if (error?.code !== 'EEXIST') + throw new CsoError( + 'PERSISTENCE_FAILED', + `Private state directory could not be created (${error?.code ?? 'unknown error'}); set GSTACK_HOME to a writable directory`, + ); } if (cursor === p) leafCreated = created; const s = fs.lstatSync(cursor); diff --git a/scripts/build-cso.sh b/scripts/build-cso.sh index 303d03e6aac..4ca72ce4f4d 100644 --- a/scripts/build-cso.sh +++ b/scripts/build-cso.sh @@ -199,9 +199,18 @@ cso_compile_posix_launcher() { # ad-hoc dylib. This section makes dyld prune DYLD_* before constructors. Darwin) CSO_LAUNCHER_FLAGS="-Wl,-sectcreate,__RESTRICT,__restrict,/dev/null" ;; esac + # The managed workspace root is fixed here, from the installer's environment, + # so the audited caller cannot choose where Git config includes are allowed. + CSO_MANAGED_ROOT="${GSTACK_CSO_MANAGED_ROOT:-${MULTICA_TASK_WORKSPACES_ROOT:-}}" + case "$CSO_MANAGED_ROOT" in + "") ;; + /*[!A-Za-z0-9._/+@:-]*|*..*|*//*) echo 'CSO managed workspace root must be a plain absolute path.' >&2; return 64 ;; + /*) ;; + *) echo 'CSO managed workspace root must be a plain absolute path.' >&2; return 64 ;; + esac # shellcheck disable=SC2086 -- the optional platform flags are fixed literals. "$CSO_CC" -std=c11 -D_POSIX_C_SOURCE=200809L -O2 -Wall -Wextra $CSO_LAUNCHER_FLAGS \ - "-DGSTACK_CSO_CORE_SHA256=\"$2\"" lib/cso/launcher.c -o "$1" + "-DGSTACK_CSO_CORE_SHA256=\"$2\"" "-DGSTACK_CSO_MANAGED_ROOT=\"$CSO_MANAGED_ROOT\"" lib/cso/launcher.c -o "$1" } # An evaluation candidate embeds a cso-eval-* runtime catalog in a private diff --git a/test/cso-cli.test.ts b/test/cso-cli.test.ts index b3b10735b85..787600adeef 100644 --- a/test/cso-cli.test.ts +++ b/test/cso-cli.test.ts @@ -145,6 +145,29 @@ describe('compiled CSO command workflow',()=>{ }); test('a surviving root-cause variant leaves the fresh recheck open for correction',()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),rootCause='Tenant query omits caller tenant predicate',finding={title:'Cross-tenant user read',rootCause,location:{path:'src/users.ts',line:1,symbol:'tenantQuery'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The captured caller-to-sink trace and control review directly support the finding',evidence:'supported',attackerControl:'Authenticated caller chooses the record ID',impact:'Another tenant record is returned',scenario:'A tenant supplies a known record ID owned by another tenant and receives that record',trace:['GET /users/:id','tenantQuery','findUnique by id'],references:['src/users.ts:1','OWASP API1:2023'],recommendation:'Bind the lookup predicate to the authenticated tenant identifier before returning the record',challenge:{reviewer:'independent-2',independent:true,mode:'independent_agent',callers:'Authenticated route forwards path ID',controls:'Authentication exists; authorization predicate does not',counterevidence:'Opaque IDs reduce guessing but do not authorize',conclusion:'The caller can provide a known cross-tenant ID'}},application={actors:['tenant user'],assets:['records'],entrypoints:['GET /users/:id'],tenantBoundaries:['tenant id'],sensitiveOperations:['record read'],invariants:['tenant isolation']},reportPath=path.join(state,'security','cso',original.repoId,original.runId,'report.json'),report=JSON.parse(fs.readFileSync(reportPath,'utf8')),submission=path.join(root,'recheck-original.json');fs.writeFileSync(submission,JSON.stringify({application,findings:[finding],coverage:report.coverage.filter((c:any)=>!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',gaps:[],method:'fresh trace',evidence:['captured source']})),gaps:[]}));expect(command(['submit',original.runId,submission]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const findingId=JSON.parse(fs.readFileSync(reportPath,'utf8')).findings[0].id,rechecked=command(['recheck',findingId,'--run',original.runId,'--repo',repo]);expect(rechecked.status).toBe(0);const child=JSON.parse(rechecked.stdout),childPath=path.join(state,'security','cso',original.repoId,child.runId,'report.json'),childReport=JSON.parse(fs.readFileSync(childPath,'utf8')),claim=path.join(root,'recheck-claim.json'),variant={...finding,title:'Moved cross-tenant user read',location:{...finding.location,symbol:'movedTenantQuery'}};fs.writeFileSync(claim,JSON.stringify({application,findings:[variant],coverage:childReport.coverage.filter((c:any)=>!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',gaps:[],method:'fresh current-source trace',evidence:['new snapshot']})),gaps:[],recheck:{findingId,outcome:'resolved',evidence:[{kind:'caller',path:'src/users.ts',line:1,observation:'Fresh caller trace reaches the tenant predicate'},{kind:'security_boundary',path:'src/users.ts',line:1,observation:'Fresh boundary trace checks cross-tenant denial'}],rootCause}}));expect(command(['submit',child.runId,claim]).status).toBe(0);const finished=command(['finish',child.runId]);expect(finished.status).not.toBe(0);expect(finished.stderr).toContain('surviving root-cause');expect(JSON.parse(fs.readFileSync(childPath,'utf8')).status).toBe('running');}); test('doctor performs no downloads and rejects a remote Docker endpoint',()=>{const r=command(['doctor','--repo',repo],{DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(r.status).toBe(0);const value=JSON.parse(r.stdout);expect(value.downloads).toBe(false);expect(value.checks.find((x:any)=>x.capability==='local-docker-isolation')).toMatchObject({status:'missing'});expect(JSON.stringify(value)).toContain('Remote TCP');}); + test.skipIf(process.platform==='win32')('compiled launcher takes the managed workspace root from its build, never from the caller (CHE-9982)',()=>{ + const REJECTED='Repository Git config includes are not allowed during a security snapshot'; + const linkedWorktree=(parent:string,name:string)=>{const linked=path.join(parent,name);git('config','extensions.worktreeConfig','true');git('worktree','add','-q','-b',name,linked); + const gitDir=fs.realpathSync(path.resolve(linked,fs.readFileSync(path.join(linked,'.git'),'utf8').trim().replace(/^gitdir:\s*/,''))); + fs.writeFileSync(path.join(gitDir,'multica-identity.config'),'[user]\n\tname = "bot"\n',{mode:0o600});fs.writeFileSync(path.join(gitDir,'config.worktree'),'[include]\n\tpath = multica-identity.config\n');return linked;}; + // A launcher built like setup builds it, with the managed root fixed in the binary. + const install=path.join(root,'managed-launcher'),managedRoot=fs.realpathSync(root),core=path.join(install,'gstack-cso-core'),managedLauncher=path.join(install,'gstack-cso-launcher'); + fs.mkdirSync(install);fs.copyFileSync(path.join(ROOT,'bin','gstack-cso-core'),core);fs.chmodSync(core,0o755); + const digest=createHash('sha256').update(fs.readFileSync(core)).digest('hex');fs.writeFileSync(path.join(install,'.gstack-cso-generation'),`${digest}\n`); + const build=(output:string,...defines:string[])=>spawnSync('/usr/bin/cc',['-std=c11','-D_POSIX_C_SOURCE=200809L','-O2',`-DGSTACK_CSO_CORE_SHA256="${digest}"`,...defines,path.join(ROOT,'lib/cso/launcher.c'),'-o',output],{encoding:'utf8',timeout:30_000}).status; + const rootless=path.join(install,'gstack-cso-launcher-no-root');expect(build(managedLauncher,`-DGSTACK_CSO_MANAGED_ROOT="${managedRoot}"`)).toBe(0);expect(build(rootless)).toBe(0); + const snapshot=(file:string,linked:string,extra:Record={})=>JSON.parse(command(['doctor','--repo',linked],extra,file).stdout).checks.find((x:any)=>x.capability==='static-snapshot'); + // Managed: inside the baked root. The caller's own variable, even a wrong one, changes nothing. + const managed=linkedWorktree(managedRoot,'managed-e2e'); + expect(snapshot(managedLauncher,managed)).toMatchObject({status:'ready'}); + expect(snapshot(managedLauncher,managed,{MULTICA_TASK_WORKSPACES_ROOT:'/nonexistent-root'})).toMatchObject({status:'ready'}); + // Unmanaged linked worktree outside the baked root: a caller-supplied root that encloses it must not unlock includes. + const outside=fs.mkdtempSync(path.join(os.tmpdir(),'cso-cli-unmanaged-')); + try{const unmanaged=linkedWorktree(outside,'unmanaged-e2e'); + for(const enclosing of [outside,path.dirname(outside),'/'])expect(snapshot(managedLauncher,unmanaged,{MULTICA_TASK_WORKSPACES_ROOT:enclosing})).toMatchObject({status:'missing',detail:REJECTED}); + // A launcher built without a root fails closed, whatever the caller sets. + for(const linked of [managed,unmanaged])expect(snapshot(rootless,linked,{MULTICA_TASK_WORKSPACES_ROOT:managedRoot})).toMatchObject({status:'missing',detail:REJECTED});}finally{fs.rmSync(outside,{recursive:true,force:true});} + },60_000); test('doctor returns exact missing capabilities for an unavailable repository',()=>{const r=command(['doctor','--repo',path.join(root,'missing-repository')],{DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(r.status).toBe(0);const value=JSON.parse(r.stdout);expect(value.elapsedMs).toBeLessThan(30_000);expect(value.checks.find((x:any)=>x.capability==='static-snapshot')).toMatchObject({status:'missing'});expect(value.checks.find((x:any)=>x.capability==='application-preparation')).toMatchObject({status:'missing'});expect(value.checks.find((x:any)=>x.capability==='qualified-runtimes')).toMatchObject({status:'missing'});}); test('audits nonignored source in a newly initialized repository before its first commit',()=>{ const unborn=path.join(root,'unborn-repo');fs.mkdirSync(unborn);const runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',unborn,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);};runGit('init','-q');fs.writeFileSync(path.join(unborn,'app.js'),'export const newProject = true\n'); diff --git a/test/cso-error-mapping.test.ts b/test/cso-error-mapping.test.ts new file mode 100644 index 00000000000..3c6f7b1f14b --- /dev/null +++ b/test/cso-error-mapping.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, test } from 'bun:test'; +import { unexpectedFailure } from '../lib/cso/cli'; +import { CsoError } from '../lib/cso/contracts'; +import { secureDirectory } from '../lib/cso/state'; + +// CHE-9982: a helper fault (unwritable state root) used to surface as INVALID_SCHEMA +// "The helper rejected an unexpected or unsafe input", which hid the cause. +describe('CSO helper fault reporting', () => { + test('names filesystem faults instead of calling them a schema rejection', () => { + const error = Object.assign(new Error("EACCES: permission denied, mkdir '/secret/path'"), { code: 'EACCES' }); + const mapped = unexpectedFailure(error); + expect(mapped).toMatchObject({ code: 'PERSISTENCE_FAILED', message: 'The helper hit a filesystem error (EACCES)' }); + expect(mapped.message).not.toContain('/secret/path'); + }); + + test('keeps the opaque label for an unknown exception', () => { + for (const value of [new Error('boom'), 'text', null, { code: 'not-errno' }, { code: 42 }]) + expect(unexpectedFailure(value)).toMatchObject({ + code: 'INVALID_SCHEMA', + message: 'The helper rejected an unexpected or unsafe input', + }); + }); + + test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'an unwritable state root reports PERSISTENCE_FAILED with the errno and a remedy', + () => { + let failure: unknown; + try { + secureDirectory('/proc/cso-state-che-9982'); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(CsoError); + expect(failure).toMatchObject({ code: 'PERSISTENCE_FAILED' }); + expect((failure as CsoError).message).toMatch(/\((EACCES|ENOENT|EPERM|EROFS)\).*GSTACK_HOME/); + }, + ); +}); diff --git a/test/cso-git-hardening.test.ts b/test/cso-git-hardening.test.ts index 99021e7d45d..fb55d4970be 100644 --- a/test/cso-git-hardening.test.ts +++ b/test/cso-git-hardening.test.ts @@ -7,7 +7,7 @@ import { capture } from '../lib/cso/snapshot'; import { childEnvironment, executable, git as readGitMetadata, runProcess } from '../lib/cso/process'; const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); +afterEach(()=>{delete process.env.MULTICA_TASK_WORKSPACES_ROOT;for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); const fixtureGit=(repo:string,home:string)=>(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:home,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.error||result.status!==0)throw new Error(`fixture git ${args.join(' ')} failed (status ${result.status}, signal ${result.signal}): ${result.error?.message??result.stderr}`);return result.stdout;}; // Each fixture builds its own repository from Git; nothing is copied from a shared @@ -167,3 +167,108 @@ describe('CSO Git metadata hardening',()=>{ expect(race.wasSwapped()).toBe(true); }); }); + +describe('CSO Git config includes in managed worktrees',()=>{ + // Mirrors the Multica managed worktree: extensions.worktreeConfig, config.worktree with a relative + // [include], and the included identity file next to it in the worktree's own Git admin directory. + function managed(){ + const f=fixture(),{root,repo,git}=f,linked=path.join(root,'linked'); + git('config','extensions.worktreeConfig','true');git('worktree','add','-q','-b','managed-test',linked); + const marker=fs.readFileSync(path.join(linked,'.git'),'utf8').trim().replace(/^gitdir:\s*/,''),gitDir=fs.realpathSync(path.resolve(linked,marker)); + const identity=path.join(gitDir,'multica-identity.config'); + fs.writeFileSync(identity,'[user]\n\tname = "bot"\n\temail = "bot@example.test"\n',{mode:0o600}); + const setInclude=(value:string)=>fs.writeFileSync(path.join(gitDir,'config.worktree'),`# Multica identity defaults\n[include]\n\tpath = ${value}\n`); + setInclude('multica-identity.config'); + process.env.MULTICA_TASK_WORKSPACES_ROOT=root; + return{...f,linked,gitDir,identity,setInclude}; + } + const head=async(repo:string,root:string)=>(await readGitMetadata(repo,['rev-parse','HEAD'],root)).trim(); + + test.skipIf(process.platform==='win32')('accepts a relative include that resolves inside the worktree Git directory (CHE-9982)',async()=>{ + const {root,linked,git}=managed(); + expect(await head(linked,root)).toBe(git('rev-parse','HEAD').trim()); + }); + + test.skipIf(process.platform==='win32')('still rejects an include that points outside the Git directory',async()=>{ + const {root,linked,gitDir,setInclude}=managed(),outside=path.join(root,'outside.conf'); + fs.writeFileSync(outside,'[core]\n\tpager = decoy\n'); + for(const value of[outside,'../../../outside.conf','../outside.conf','sub/../../outside.conf','~/x.conf']) + {setInclude(value);await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH',message:'Repository Git config includes are not allowed during a security snapshot'});} + expect(gitDir).toContain(root); + }); + + test.skipIf(process.platform==='win32')('rejects includeIf, subsection, keyed and quoted include forms',async()=>{ + const {root,linked,gitDir}=managed(),config=path.join(gitDir,'config.worktree'); + for(const body of['[includeIf "gitdir:/"]\n\tpath = multica-identity.config\n','[include "x"]\n\tpath = multica-identity.config\n','[include]\n\tpath = "multica-identity.config"\n','[include]\n\tpath = multica-identity.config\n\tfoo = bar\n','[include]\n\tpath = multica-identity.config\n[includeIf "gitdir:/"]\n\tpath = multica-identity.config\n','[include] path = multica-identity.config\n']){ + fs.writeFileSync(config,body); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + } + }); + + test.skipIf(process.platform==='win32')('rejects a symlinked, missing or nested-include target',async()=>{ + const {root,linked,gitDir,identity}=managed(),outside=path.join(root,'outside.conf'); + fs.writeFileSync(outside,'[core]\n\tpager = decoy\n'); + fs.rmSync(identity);fs.symlinkSync(outside,identity); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + fs.rmSync(identity); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + fs.writeFileSync(identity,`[include]\n\tpath = ${outside}\n`); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + expect(gitDir).toContain(root); + }); + + test.skipIf(process.platform==='win32')('does not accept an include that targets a file in the working tree',async()=>{ + const {root,linked,gitDir,setInclude}=managed(); + fs.writeFileSync(path.join(linked,'tracked-config'),'[core]\n\tpager = decoy\n'); + setInclude(path.relative(gitDir,path.join(linked,'tracked-config'))); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + }); + + test.skipIf(process.platform==='win32')('rejects an include in an ordinary clone, even to a file inside .git',async()=>{ + const {root,repo,git}=fixture(),gitDir=path.join(repo,'.git'),rejected={code:'UNSAFE_PATH',message:'Repository Git config includes are not allowed during a security snapshot'}; + fs.writeFileSync(path.join(gitDir,'local.config'),'[user]\n\tname = "bot"\n'); + // Shared config of an ordinary clone. + fs.appendFileSync(path.join(gitDir,'config'),'[include]\n\tpath = local.config\n'); + await expect(readGitMetadata(repo,['rev-parse','HEAD'],root)).rejects.toMatchObject(rejected); + // config.worktree of the main worktree (gitDir === commonDir) is not a managed worktree either. + fs.writeFileSync(path.join(gitDir,'config'),'[core]\n\trepositoryformatversion = 1\n[extensions]\n\tworktreeConfig = true\n'); + fs.writeFileSync(path.join(gitDir,'config.worktree'),'[include]\n\tpath = local.config\n'); + await expect(readGitMetadata(repo,['rev-parse','HEAD'],root)).rejects.toMatchObject(rejected); + expect(git).toBeDefined(); + }); + + test.skipIf(process.platform==='win32')('rejects an include in an unmanaged linked worktree (outside the managed root, or no managed root)',async()=>{ + const {root,linked}=managed(),elsewhere=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cso-unmanaged-root-'))); + roots.push(elsewhere); + const rejected={code:'UNSAFE_PATH',message:'Repository Git config includes are not allowed during a security snapshot'}; + process.env.MULTICA_TASK_WORKSPACES_ROOT=elsewhere; + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject(rejected); + process.env.MULTICA_TASK_WORKSPACES_ROOT='relative/root'; + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject(rejected); + delete process.env.MULTICA_TASK_WORKSPACES_ROOT; + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject(rejected); + }); + + test.skipIf(process.platform==='win32')('rejects an include in the shared config of a linked worktree',async()=>{ + const {root,linked,gitDir}=managed(),common=fs.realpathSync(path.resolve(gitDir,fs.readFileSync(path.join(gitDir,'commondir'),'utf8').trim())); + fs.writeFileSync(path.join(common,'local.config'),'[user]\n\tname = "bot"\n'); + fs.appendFileSync(path.join(common,'config'),'[include]\n\tpath = local.config\n'); + await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'UNSAFE_PATH'}); + }); + + test.skipIf(process.platform==='win32')('detects the included file changing during a metadata operation',async()=>{ + const {root,linked,identity}=managed(); + const original=fs.lstatSync;let hits=0; + const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{ + const result=options===undefined?original(candidate):original(candidate,options); + if(path.resolve(String(candidate))===identity&&++hits===3)fs.writeFileSync(identity,'[user]\n\tname = "swapped"\n'); + return result; + }) as typeof fs.lstatSync); + try{await expect(readGitMetadata(linked,['rev-parse','HEAD'],root)).rejects.toMatchObject({code:'SNAPSHOT_RACE'});}finally{patched.mockRestore();} + }); + + test.skipIf(process.platform==='win32')('snapshot capture succeeds in a managed worktree',async()=>{ + const {linked,runDir}=managed(); + await expect(capture(linked,runDir)).resolves.toBeDefined(); + }); +});