fix: harden integration security findings

This commit is contained in:
haelyra committed 2026-11-06 00:03:44 -05:00
1 parent b2ea647d41
commit bfb4dbe7b0
8 files changed
+44 -33

No files matched your search

+19 -7
View File
@@ -19,7 +19,6 @@ const {
ensureDir, ensureDir,
readFile, readFile,
countInFile, countInFile,
getTempDir,
log, log,
output output
} = require('../lib/utils'); } = require('../lib/utils');
@@ -28,12 +27,12 @@ const {
resolveProjectContext, resolveProjectContext,
getAliasContexts, getAliasContexts,
listSessionLeases, listSessionLeases,
getHomunculusDir,
resolveSessionId resolveSessionId
} = require('../lib/observer-sessions'); } = require('../lib/observer-sessions');
// Marker that records a delivered Stop nudge, one per session, in the OS // Marker that records a delivered Stop nudge, one per session, in the
// temp dir (same per-session temp-file pattern as suggest-compact's // observer data directory. A marker is what makes delivery once-per-session: a later
// counters). A marker is what makes delivery once-per-session: a later
// user stop in the same session must not block again. // user stop in the same session must not block again.
const DELIVERY_MARKER_PREFIX = 'claude-continuous-learning-delivered-'; const DELIVERY_MARKER_PREFIX = 'claude-continuous-learning-delivered-';
@@ -164,8 +163,8 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s
return; return;
} }
// The session id is sanitized upstream by resolveSessionId, so the // The session id is sanitized upstream by resolveSessionId, so the
// marker filename cannot traverse out of the temp dir. // marker filename cannot traverse out of the private observer directory.
const markerFile = path.join(getTempDir(), `${DELIVERY_MARKER_PREFIX}${sessionId}`); const markerDir = path.join(getHomunculusDir(), 'delivery-markers');
// Claim the marker atomically: 'wx' fails when a nudge was already // Claim the marker atomically: 'wx' fails when a nudge was already
// delivered (EEXIST) and closes the check-then-create gap. Any other // delivered (EEXIST) and closes the check-then-create gap. Any other
// write failure fails closed: without a marker, a later Stop would stay // write failure fails closed: without a marker, a later Stop would stay
@@ -174,7 +173,20 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s
// Stop for one turn, not later turns, so it cannot stand in for the // Stop for one turn, not later turns, so it cannot stand in for the
// marker. // marker.
try { try {
fs.writeFileSync(markerFile, `${new Date().toISOString()}\n`, { flag: 'wx' }); fs.mkdirSync(markerDir, { recursive: true, mode: 0o700 });
const stat = fs.lstatSync(markerDir);
if (!stat.isDirectory() || stat.isSymbolicLink()
|| (process.platform !== 'win32' && ((stat.mode & 0o077) !== 0
|| (typeof process.getuid === 'function' && stat.uid !== process.getuid())))) {
throw new Error('delivery marker directory is not private');
}
} catch (err) {
log(`[ContinuousLearning] Warning: could not record delivery marker, skipping delivery: ${err.message}`);
return;
}
const markerFile = path.join(markerDir, `${DELIVERY_MARKER_PREFIX}${sessionId}`);
try {
fs.writeFileSync(markerFile, `${new Date().toISOString()}\n`, { flag: 'wx', mode: 0o600 });
} catch (err) { } catch (err) {
if (err.code === 'EEXIST') { if (err.code === 'EEXIST') {
log('[ContinuousLearning] Stop nudge already delivered for this session, skipping'); log('[ContinuousLearning] Stop nudge already delivered for this session, skipping');
+1 -3
View File
@@ -439,9 +439,7 @@ function runTests() {
assert.ok(fs.existsSync(installedSkill), assert.ok(fs.existsSync(installedSkill),
`installed skill missing at ${installedSkill}`); `installed skill missing at ${installedSkill}`);
const installedSettings = fs.existsSync(settingsPath) const installedSettings = fs.readFileSync(settingsPath, 'utf8');
? fs.readFileSync(settingsPath, 'utf8')
: '';
// Copying the script is not the SessionStart promise the skill makes: the // Copying the script is not the SessionStart promise the skill makes: the
// installed monitor only runs if the installer also registers it. // installed monitor only runs if the installer also registers it.
const parsedSettings = JSON.parse(installedSettings); const parsedSettings = JSON.parse(installedSettings);
+9 -11
View File
@@ -438,8 +438,8 @@ function runTests() {
// Test session ids below are already sanitized-safe (lowercase, digits, // Test session ids below are already sanitized-safe (lowercase, digits,
// hyphens), so the delivery marker filename is a plain concatenation. // hyphens), so the delivery marker filename is a plain concatenation.
function deliveryMarkerPath(sessionId) { function deliveryMarkerPath(homunculusDir, sessionId) {
return path.join(os.tmpdir(), `claude-continuous-learning-delivered-${sessionId}`); return path.join(homunculusDir, 'delivery-markers', `claude-continuous-learning-delivered-${sessionId}`);
} }
function runEvaluatePayload(payload, extraEnv = {}, dropKeys = []) { function runEvaluatePayload(payload, extraEnv = {}, dropKeys = []) {
@@ -544,7 +544,7 @@ function runTests() {
const transcript = createTranscript(testDir, 12); const transcript = createTranscript(testDir, 12);
const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-'));
const sessionId = 'delivery-ok-1'; const sessionId = 'delivery-ok-1';
const marker = deliveryMarkerPath(sessionId); const marker = deliveryMarkerPath(homunculusDir, sessionId);
try { try {
fs.rmSync(marker, { force: true }); fs.rmSync(marker, { force: true });
registerLeaseFor(testDir, homunculusDir, sessionId); registerLeaseFor(testDir, homunculusDir, sessionId);
@@ -584,22 +584,20 @@ function runTests() {
const transcript = createTranscript(testDir, 12); const transcript = createTranscript(testDir, 12);
const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-'));
const sessionId = 'delivery-marker-fail-1'; const sessionId = 'delivery-marker-fail-1';
const marker = deliveryMarkerPath(sessionId); const marker = deliveryMarkerPath(homunculusDir, sessionId);
// A regular file as TMPDIR makes the marker path uncreatable (ENOTDIR) const notADir = path.dirname(marker);
// even as root, so the write fails while no marker exists.
const notADir = path.join(testDir, 'not-a-dir');
try { try {
fs.rmSync(marker, { force: true }); fs.rmSync(marker, { force: true });
fs.writeFileSync(notADir, 'not a directory\n');
registerLeaseFor(testDir, homunculusDir, sessionId); registerLeaseFor(testDir, homunculusDir, sessionId);
fs.writeFileSync(notADir, 'not a directory\n');
const result = withOptInConfig(true, () => runEvaluatePayload( const result = withOptInConfig(true, () => runEvaluatePayload(
stopPayload(transcript, sessionId, testDir), stopPayload(transcript, sessionId, testDir),
{ CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir, TMPDIR: notADir, TEMP: notADir, TMP: notADir } { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir }
)); ));
assert.strictEqual(result.stdout, '', 'A failed marker write must fail closed, never deliver'); assert.strictEqual(result.stdout, '', 'A failed marker write must fail closed, never deliver');
assert.ok(result.stderr.includes('could not record delivery marker'), 'Marker failure must be logged'); assert.ok(result.stderr.includes('could not record delivery marker'), 'Marker failure must be logged');
} finally { } finally {
fs.rmSync(marker, { force: true }); fs.rmSync(notADir, { force: true });
cleanupTestDir(testDir); cleanupTestDir(testDir);
fs.rmSync(homunculusDir, { recursive: true, force: true }); fs.rmSync(homunculusDir, { recursive: true, force: true });
} }
@@ -626,7 +624,7 @@ function runTests() {
const transcript = createTranscript(testDir, 12); const transcript = createTranscript(testDir, 12);
const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-'));
const sessionId = 'delivery-loop-1'; const sessionId = 'delivery-loop-1';
const marker = deliveryMarkerPath(sessionId); const marker = deliveryMarkerPath(homunculusDir, sessionId);
try { try {
fs.rmSync(marker, { force: true }); fs.rmSync(marker, { force: true });
registerLeaseFor(testDir, homunculusDir, sessionId); registerLeaseFor(testDir, homunculusDir, sessionId);
+1 -1
View File
@@ -355,7 +355,7 @@ if (process.platform === 'win32') {
].join('\r\n'), 'utf8'); ].join('\r\n'), 'utf8');
const invocation = hook.getLinterInvocation(command, ['100% ready.js', '!important!.js'], 'win32'); const invocation = hook.getLinterInvocation(command, ['100% ready.js', '!important!.js'], 'win32');
const result = spawnSync(invocation.command, invocation.args, { const result = spawnSync('cmd.exe', invocation.args, {
...invocation.options, ...invocation.options,
env: { ...invocation.options.env, ECC_CAPTURE_PATH: capturePath } env: { ...invocation.options.env, ECC_CAPTURE_PATH: capturePath }
}); });
@@ -251,9 +251,9 @@ for (const name of SHARED_FILES) {
operation.destinationPath === destination operation.destinationPath === destination
)); ));
writeFile(linkedFile, '# User-owned linked configuration\n'); writeFile(linkedFile, '# User-owned linked configuration\n');
fs.unlinkSync(destination); const replacementLink = fixture.destination(`${name}.replacement-link`);
try { try {
fs.symlinkSync(linkedFile, destination, 'file'); fs.symlinkSync(linkedFile, replacementLink, 'file');
} catch (error) { } catch (error) {
if (process.platform === 'win32' if (process.platform === 'win32'
&& ['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) { && ['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) {
@@ -262,6 +262,8 @@ for (const name of SHARED_FILES) {
} }
throw error; throw error;
} }
fs.unlinkSync(destination);
fs.renameSync(replacementLink, destination);
assert.throws(() => fixture.install(), error => ( assert.throws(() => fixture.install(), error => (
error.code === 'ELOOP' || /Refusing to inspect changed Codex configuration/.test(error.message) error.code === 'ELOOP' || /Refusing to inspect changed Codex configuration/.test(error.message)
+3 -2
View File
@@ -250,7 +250,7 @@ test('legacy non-file operations do not block canonical cleanup or repair', () =
} }
}); });
test('repair migrates a legacy install while preserving modified legacy files', () => { test('repair refuses incomplete legacy migration while preserving modified legacy files', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-repair-')); const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-repair-'));
try { try {
const legacy = seedLegacyInstall(homeDir, { modified: true }); const legacy = seedLegacyInstall(homeDir, { modified: true });
@@ -260,7 +260,8 @@ test('repair migrates a legacy install while preserving modified legacy files',
projectRoot: homeDir, projectRoot: homeDir,
targets: ['opencode'], targets: ['opencode'],
}); });
assert.strictEqual(result.summary.errorCount, 0, JSON.stringify(result)); assert.strictEqual(result.summary.errorCount, 1, JSON.stringify(result));
assert.match(result.results[0].error, /Legacy OpenCode migration is incomplete/);
assert.ok(fs.existsSync(path.join(homeDir, '.config', 'opencode', 'ecc-install-state.json'))); assert.ok(fs.existsSync(path.join(homeDir, '.config', 'opencode', 'ecc-install-state.json')));
assert.strictEqual(fs.readFileSync(legacy.destinationPath, 'utf8'), 'user-modified\n'); assert.strictEqual(fs.readFileSync(legacy.destinationPath, 'utf8'), 'user-modified\n');
assert.ok(fs.existsSync(legacy.installStatePath)); assert.ok(fs.existsSync(legacy.installStatePath));
+1 -3
View File
@@ -27,9 +27,7 @@ function test(name, fn) {
// Create a temporary test directory // Create a temporary test directory
function createTestDir() { function createTestDir() {
const testDir = path.join(os.tmpdir(), `pm-test-${Date.now()}`); return fs.mkdtempSync(path.join(os.tmpdir(), 'pm-test-'));
fs.mkdirSync(testDir, { recursive: true });
return testDir;
} }
// Clean up test directory // Clean up test directory
+6 -4
View File
@@ -67,15 +67,16 @@ function runWithGuidedDispatcherFailure(failureMode) {
const root = createTempDir('install-apply-guided-failure-'); const root = createTempDir('install-apply-guided-failure-');
const preloadPath = path.join(root, 'preload.js'); const preloadPath = path.join(root, 'preload.js');
const failureMessage = 'guided dispatcher failed\u001b[31m'; const failureMessage = 'guided dispatcher failed\u001b[31m';
const replacement = failureMode === 'load'
? `throw new Error(${JSON.stringify(failureMessage)});`
: `return { main: () => Promise.reject(new Error(${JSON.stringify(failureMessage)})) };`;
fs.writeFileSync(preloadPath, ` fs.writeFileSync(preloadPath, `
const Module = require('module'); const Module = require('module');
const originalLoad = Module._load; const originalLoad = Module._load;
Module._load = function(request, parent, isMain) { Module._load = function(request, parent, isMain) {
if (request === './install-guided' && /install-apply\\.js$/.test(parent?.filename || '')) { if (request === './install-guided' && /install-apply\\.js$/.test(parent?.filename || '')) {
${replacement} const failureMessage = process.env.ECC_GUIDED_FAILURE_MESSAGE;
if (process.env.ECC_GUIDED_FAILURE_MODE === 'load') {
throw new Error(failureMessage);
}
return { main: () => Promise.reject(new Error(failureMessage)) };
} }
return originalLoad.call(this, request, parent, isMain); return originalLoad.call(this, request, parent, isMain);
}; };
@@ -84,6 +85,7 @@ function runWithGuidedDispatcherFailure(failureMode) {
return spawnSync(process.execPath, ['--require', preloadPath, SCRIPT, '--guided'], { return spawnSync(process.execPath, ['--require', preloadPath, SCRIPT, '--guided'], {
cwd: path.dirname(SCRIPT), cwd: path.dirname(SCRIPT),
encoding: 'utf8', encoding: 'utf8',
env: { ...process.env, ECC_GUIDED_FAILURE_MODE: failureMode, ECC_GUIDED_FAILURE_MESSAGE: failureMessage },
}); });
} finally { } finally {
cleanup(root); cleanup(root);