Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 12 additions & 4 deletions lib/cso/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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',
Expand Down
8 changes: 8 additions & 0 deletions lib/cso/launcher.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<sizeof names/sizeof names[0];i++){envp[e]=entry(names[i],"");if(!envp[e++]){fputs("gstack-cso: environment input is too large\n",stderr);return 69;}}
envp[e]=fixed_entry("MULTICA_TASK_WORKSPACES_ROOT",GSTACK_CSO_MANAGED_ROOT);if(!envp[e++]){fputs("gstack-cso: managed root is too large\n",stderr);return 69;}
envp[e]=fixed_entry("GSTACK_CSO_CALLER_CWD",caller_cwd);if(!envp[e++]){fputs("gstack-cso: caller working directory is too large\n",stderr);return 69;}
char lock_value[32];snprintf(lock_value,sizeof lock_value,"%d",generation_lock);
envp[e]=fixed_entry("GSTACK_CSO_GENERATION_LOCK_FD",lock_value);if(!envp[e++])return 69;
Expand Down
97 changes: 86 additions & 11 deletions lib/cso/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
realpathSync,
statSync,
} from 'node:fs';
import { basename, dirname, join, isAbsolute, delimiter, resolve } from 'node:path';
import { basename, dirname, join, isAbsolute, delimiter, resolve, sep } from 'node:path';
import { redactFindingSpans, redactJsonFindingSpans } from '../redact-engine';
import { CsoError, MAX_OUTPUT } from './contracts';
import { windowsDockerUnavailable } from './windows-docker';
Expand Down Expand Up @@ -308,6 +308,10 @@ export interface ProcessResult {
interface GitConfigIdentity {
path: string;
exists: boolean;
/** True for a file pulled in by an accepted [include]; it may not include anything itself. */
included?: boolean;
/** True when the caller verified a managed worktree config that may carry plain includes. */
allowIncludes?: boolean;
dev?: number;
ino?: number;
mode?: number;
Expand Down Expand Up @@ -400,21 +404,52 @@ function boundedMetadataFile(
} catch {}
}
}
function boundedConfig(path: string): GitConfigIdentity {
const GIT_INCLUDE_SECTION = /^\s*\[\s*include(?:if)?(?=[\s."\]])/im;
const INCLUDE_REJECTED = 'Repository Git config includes are not allowed during a security snapshot';
/**
* Include targets of a config whose only include directives are plain
* `[include]` sections with `path = <plain relative name>` 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,
Expand All @@ -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'),
Expand Down Expand Up @@ -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 ||
Expand Down
6 changes: 5 additions & 1 deletion lib/cso/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
11 changes: 10 additions & 1 deletion scripts/build-cso.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading