Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
ca8aec9
fix(host-kit): refuse a script destination another local user can steer
thymikee Nov 16, 2026
b4340d0
fix(daemon): apply the destination rule to a local script save
thymikee Nov 16, 2026
a0b1332
fix(remote): refuse an unsafe script destination before it is downloaded
thymikee Nov 16, 2026
e26b698
docs: say which directories a script save accepts
thymikee Nov 16, 2026
cc0b597
test: carry the script publish through the wire and ownership gates
thymikee Nov 16, 2026
d93ac5d
fix(host-kit): judge a script destination by ownership and its real path
thymikee Nov 16, 2026
5816981
fix(host-kit): keep foreign ground out of a script destination chain
thymikee Nov 16, 2026
35fb969
test(daemon): refuse a recording under a directory another user owns
thymikee Nov 16, 2026
1540984
fix(host-kit): judge every directory a script destination walks through
thymikee Nov 16, 2026
5901614
fix(host-kit): walk a script destination the way the kernel resolves it
thymikee Nov 16, 2026
352adcc
fix(host-kit): resolve a link target relative to the directory that h…
thymikee Nov 16, 2026
239ad68
fix(host-kit): name a published temp file by the directory it stands in
thymikee Nov 16, 2026
43d436c
fix(host-kit): judge a relative destination from the root down
thymikee Nov 16, 2026
8440213
fix(host-kit): judge a script destination before creating its parent
thymikee Nov 16, 2026
2af90f4
fix(remote): create a published script in the directory the rule veri…
thymikee Nov 16, 2026
c5b41a0
fix(host-kit): refuse a script destination the walk cannot resolve
thymikee Nov 16, 2026
927b042
refactor(host-kit): own script destination creation in one call
thymikee Nov 16, 2026
925158d
fix(host-kit): judge every script-path step from its own lstat
thymikee Nov 16, 2026
eaa9747
fix(daemon-contracts): judge a state repair before forcing its mode
thymikee Nov 16, 2026
ed5c7b9
fix(host-kit): confirm a script destination with one call, and cut th…
thymikee Nov 16, 2026
b9f17ce
fix(daemon-contracts): never let a state-mode repair decide daemon st…
thymikee Nov 17, 2026
632cc84
test(daemon-contracts): pin a state repair that skips levels it may n…
thymikee Nov 17, 2026
4b630c1
docs(adr): say what the state repair judges, in the tense the code has
thymikee Nov 17, 2026
e38764b
fix(daemon): judge the state repair down from the state base
thymikee Nov 17, 2026
8cd5b8a
fix(daemon): judge what a state level is before its mode
thymikee Nov 17, 2026
fa64dfe
fix(daemon): refuse a script the state repair could not claim
thymikee Nov 17, 2026
687822a
fix(daemon): carry the close refusal's reason and say who owns the state
thymikee Nov 17, 2026
208b380
fix(daemon): judge the ancestry above the state base before repairing it
thymikee Nov 17, 2026
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
37 changes: 35 additions & 2 deletions docs/adr/0016-active-session-script-publication.md

Large diffs are not rendered by default.

Large diffs are not rendered by default.

207 changes: 203 additions & 4 deletions packages/daemon-contracts/src/daemon-registration-owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
inspectProcessLock,
tryAcquireProcessLock,
acquireProcessLockAcquisition,
untrustedDirectoryAncestry,
type ProcessLockAttempt,
type ProcessLockAcquisition,
} from '@agent-device/host-kit/file';
Expand Down Expand Up @@ -276,6 +277,207 @@ export function createOwnedReplayStateDir(): OwnedReplayStateDir {
return owned;
}

/**
* Creates one of the daemon's own state directories, and forces the mode of one that exists, to 0700.
*
* Every directory on the chain of a script destination the daemon picks for itself — the state dir,
* `sessions/`, `remote-scripts/` — is judged by the destination-ancestry rule on the way to a recording
* (ADR 0016), and that rule refuses a group-writable directory. A mode-less `mkdir` under the shared-checkout
* umask 002 creates `sessions/` at 0775, so creation carries the mode and the repair forces it for a level
* an older version already left loose.
*
* The repair is BEST-EFFORT and never refuses (#4565): a state directory on a mounted volume, or one another
* uid left at 0755, still gets a daemon that starts. It answers {@link DaemonStateDir}, and a caller that
* WRITES under the directory reads the verdict on the chain; startup ignores it.
*
* `stateBase` is the daemon's state directory that the levels below it are judged from: a level is repaired
* only when every level above it, down from that base, is one this process may judge. {@link
* repairStateChain} says why the whole chain has to be judged rather than the leaf alone.
*/
export function ensurePrivateDaemonStateDir(directory: string, stateBase: string): DaemonStateDir {
// One recursive `mkdir`, BEFORE the chain is judged: it creates the whole tail even on ground the repair
// will stop at, which is what keeps a `~/.agent-device` linked to another disk working. What it can leave
// beyond a rejected level is an empty directory, and no script is published on a chain the verdict refuses.
fs.mkdirSync(directory, { recursive: true, mode: STATE_DIR_MODE });
return { path: directory, privateChain: repairStateChain(stateBase, directory) };
}

/**
* What {@link ensurePrivateDaemonStateDir} leaves behind: the directory it created or repaired, and whether
* every level from the state base down to it is now a real directory this uid owns, standing 0700, reached
* without following a link. `privateChain: false` says the repair STOPPED somewhere on that chain. It does
* not say anything failed — startup proceeds either way — only that a script must not be written there.
*/
export type DaemonStateDir = Readonly<{ path: string; privateChain: boolean }>;

/**
* {@link ensurePrivateDaemonStateDir} for a caller that writes no script under the directory — startup, or a
* tombstone written beside a session — so it takes the path and leaves the verdict unread.
*/
export function ensureDaemonStateDir(directory: string, stateBase: string): string {
return ensurePrivateDaemonStateDir(directory, stateBase).path;
}

const STATE_DIR_MODE = 0o700;

/**
* Forces every state level from `stateBase` down to `directory` to {@link STATE_DIR_MODE}, and never throws.
*
* `O_NOFOLLOW` guards only the LAST name of an open, so judging the leaf alone is not enough: a `sessions`
* left as a link to `/etc` by a user who could write a legacy state directory makes the leaf `sessions/ssh`
* resolve to `/etc/ssh`, and a root daemon repairing that leaf would change the mode of a directory nobody
* asked it to touch. So the chain is walked DOWN from the state base, each level judged by the `lstat` of the
* entry under its name, and the first level that is a link, is not a directory, or belongs to another uid
* stops the descent: that level and every level beneath it are left exactly as they are.
*
* Judging DOWN is not enough either, because the descent never questions the ground the base stands on: a
* user who can write an ancestor above it can rename the base and leave a link at its name between two of
* this function's calls, and every level below then resolves on ground nothing judged. So the ancestry above
* the base is asked FIRST, by {@link untrustedDirectoryAncestry} — the walk a script destination is judged
* by, not a second rule. It is asked of the ANCESTRY only: the levels at and below the base are what this
* repair exists to make private (ADR 0016).
*
* Nothing here decides whether the daemon starts (ADR 0016), so no error is allowed to travel either: the
* `lstat`, the open, the `fstat`, the `fchmod` and the closing `close` are inside one catch, and any of them
* failing — `EACCES` on a directory this user cannot read, `ENOENT` on a name that went missing meanwhile,
* `EIO` on a host that cannot even release the descriptor — is reported as a skipped level and stopped there.
* Creation keeps its own failures, which come from the `mkdir` in the caller. The answer says whether the
* WHOLE chain reached `directory` and stands private; {@link DaemonStateDir} says who reads it.
*/
function repairStateChain(stateBase: string, directory: string): boolean {
// Windows answers access from an ACL, and `chmod` there only toggles the read-only bit.
if (process.platform === 'win32') return true;
const levels = stateLevelsBelow(stateBase, directory);
// A caller that names a directory outside the state base has no chain here to judge it from.
if (levels === undefined) {
skipStateDirMode(directory, 'not_below_state_base');
return false;
}
if (!stateAncestryIsTrusted(stateBase)) return false;
for (const level of levels) {
try {
if (!repairStateLevel(level)) return false;
} catch (error) {
skipStateDirMode(level, (error as NodeJS.ErrnoException).code ?? 'unknown');
return false;
}
}
return true;
}

/**
* Whether `stateBase` stands on ground no other local user can move, asked before a single level is touched.
*
* {@link untrustedDirectoryAncestry} is given the base's PARENT, so it answers about the ancestry above the
* base and leaves the base itself to {@link repairStateLevel}, which can force its mode instead of only
* refusing it. Where the rule refuses, nothing below is repaired and the chain is not private ground.
*/
function stateAncestryIsTrusted(stateBase: string): boolean {
const exposure = untrustedDirectoryAncestry(path.dirname(stateBase));
if (exposure === undefined) return true;
skipStateDirMode(exposure.ancestor, `state_ancestry_${exposure.exposure}`);
return false;
}

/**
* Forces one level, and reports whether the chain is intact THROUGH it — the descent may go on beneath it,
* and the level counts as private ground.
*
* `chmod` given the NAME acts on whatever the name resolves to, so the mode goes through a descriptor opened
* `O_DIRECTORY | O_NOFOLLOW`, and only after that descriptor's `fstat` says this uid owns the entry — the
* entry the `fchmod` will change is the one asked about, because a writable parent can swap the name between
* two calls. A LINK or a non-directory is not a level of this tree, and a foreign directory is not this
* process's to judge, so both stop the descent rather than being followed or forced.
*/
function repairStateLevel(level: string): boolean {
const judged = fs.lstatSync(level, { bigint: true, throwIfNoEntry: false });
// The name is gone: whatever removed it also removed the mode this call came to force, and there is
// nothing below it. Said out loud like every other stop, because the log has to show WHERE it stopped.
if (judged === undefined) {
skipStateDirMode(level, 'absent');
return false;
}
// Asked BEFORE the mode, never after it: a LINK whose own bits are 0700 answers the mode question with the
// private mode, and a repair that read the mode first would pass that link without judging it at all.
if (!judged.isDirectory()) {
skipStateDirMode(level, 'not_a_directory');
return false;
}
if (Number(judged.uid) !== (process.getuid?.() ?? -1)) {
skipStateDirMode(level, 'foreign_owned');
return false;
}
// The fast path: a level that already has the mode needs nothing, and asking nothing of the mount keeps
// the common start free of an open.
if ((Number(judged.mode) & 0o777) === STATE_DIR_MODE) return true;
return forcePrivateStateDir(level);
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

/**
* Forces one level whose `lstat` passed, through a descriptor that cannot follow a link, and reports whether
* the entry that open REACHED is this process's to keep private. The `lstat` said so a moment ago, and only
* the descriptor says what the `fchmod` changed: a name swapped for a link between the two calls is caught
* here, and a level caught there is NOT private ground, whatever its `lstat` claimed.
*/
function forcePrivateStateDir(level: string): boolean {
let descriptor: number | undefined;
try {
descriptor = fs.openSync(
level,
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
// The entry this open REACHED, asked before the mode is forced: the name can be swapped for a link
// between the `lstat` above and this open, and only the descriptor says what the `fchmod` will change.
if (Number(fs.fstatSync(descriptor, { bigint: true }).uid) !== (process.getuid?.() ?? -1)) {
skipStateDirMode(level, 'foreign_owned');
return false;
}
fs.fchmodSync(descriptor, STATE_DIR_MODE);
return true;
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
}
}

/** Every level from `stateBase` down to `directory`, base first, or `undefined` if it is not below it. */
function stateLevelsBelow(stateBase: string, directory: string): readonly string[] | undefined {
const below = path.relative(stateBase, directory);
if (below === '') return [stateBase];
if (below.startsWith('..') || path.isAbsolute(below)) return undefined;
const names = below.split(path.sep);
return [
stateBase,
...names.map((_, index) => path.join(stateBase, ...names.slice(0, index + 1))),
];
}

/**
* Reports the one state level whose mode this repair will not change, and returns nothing: a skip is never a
* refusal, and a caller that cannot reach a level still gets the directory it asked for.
*/
function skipStateDirMode(level: string, reason: string): void {
emitDiagnostic({
level: 'warn',
phase: 'daemon_state_mode_repair_skipped',
data: { path: level, reason: `state mode repair stopped at this level: ${reason}` },
});
}

/**
* What a mode repair may never fail the daemon on: a host that denies the chmod (`EPERM`, `EROFS`, and the
* two spellings of an unsupported one), a name that cannot open as a directory (`ELOOP`, `ENOTDIR`), and a
* directory that will not open for this user at all (`EACCES`).
*/
const MODE_REPAIR_SKIPPED_CODES = new Set([
'EPERM',
'EROFS',
'ENOTSUP',
'EOPNOTSUPP',
'EACCES',
'ELOOP',
'ENOTDIR',
]);

/**
* Forces a pre-existing state path to the private mode, whatever mode it had. On Windows, chmod
* only toggles the read-only bit, so it cannot make the path private. The repair never decides
Expand All @@ -294,8 +496,6 @@ function repairStateMode(target: string, mode: number): void {
}
}

const MODE_REPAIR_SKIPPED_CODES = new Set(['EPERM', 'EROFS', 'ENOTSUP', 'EOPNOTSUPP']);

/** Launches and monitors the actual child before recording its private-directory authority. */
export function launchDaemonProcess(
input: Readonly<{
Expand All @@ -314,8 +514,7 @@ export function launchDaemonProcess(
throw new AppError('COMMAND_FAILED', 'Replay daemon startup admission is closed.', {
reason: 'daemon_startup_admission_closed',
});
fs.mkdirSync(input.paths.baseDir, { recursive: true, mode: 0o700 });
repairStateMode(input.paths.baseDir, 0o700);
ensureDaemonStateDir(input.paths.baseDir, input.paths.baseDir);
const logFd = fs.openSync(input.paths.logPath, 'a', 0o600);
try {
repairStateMode(input.paths.logPath, 0o600);
Expand Down
27 changes: 27 additions & 0 deletions packages/daemon/src/__tests__/support/script-staging-failure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import fs from 'node:fs';
import { vi } from 'vitest';
import { isAtomicPublishTemporaryPath } from '@agent-device/host-kit/file';

/**
* Makes the staging write of a script publication fail, and only that write.
*
* A publication stages the recording in a private temp sibling of the destination and moves it into place,
* so the seam where the filesystem can refuse a script is that one write. `host-kit`'s temp-path predicate
* says which write it is, so the fixture does not have to know how the name is built.
*
* This replaces a fixture that made the destination's directory `0500`. That one asked the HOST whether a
* write into it is allowed, and a caller the mode bits do not bind — root — writes straight through it, so
* the write succeeded and the test that expected a failure failed with it. The failure injected here is the
* fixture's own, which makes the outcome the same for every caller.
*/
export function failScriptStagingWrite(destination: string): void {
const failure: NodeJS.ErrnoException = Object.assign(
new Error(`EACCES: permission denied, open '${destination}'`),
{ code: 'EACCES', errno: -13, syscall: 'open', path: destination },
);
const realWriteFileSync = fs.writeFileSync;
vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: fs.PathLike | number, ...rest) => {
if (isAtomicPublishTemporaryPath(file, destination)) throw failure;
return (realWriteFileSync as (...args: unknown[]) => unknown)(file, ...rest);
}) as typeof fs.writeFileSync);
}
Loading
Loading