diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index a7f4c2937b..211c771bcf 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -207,7 +207,30 @@ It adds no state name, command, or flag: A batch whose steps would close an armed remote recording is refused before any step runs (`remote_script_batch_close_unsupported`), because a batch delivers no script versions from its steps. - The daemon reports the `script-artifacts` capability in `/health`, through a proxy in its upstream health; the client refuses a remote `--save-script` before dispatch without it. -The destination keeps local `--save-script` semantics: the client creates a missing parent directory and checks no ancestor ownership, so another local user who can write an ancestor directory can redirect the file, locally and remotely alike (#4565). +The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can change. The rule closes the window with PERMISSIONS, not with timing. +A destination is accepted only when no other non-root local user can modify any directory the publish traverses. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. +The walk emulates the kernel's own path resolution, because that is the set of directories that has to be safe. It starts at `/` (or at the process's resolved working directory for a relative spelling) with the spelled components on a queue, and takes one component at a time: `.` is skipped; `..` moves to the parent of the directory PHYSICALLY stood in, never to the parent of the spelled string; any other component is looked up with `lstat` inside that directory. A directory is judged and entered. A symbolic link is judged where it physically stands and its target's components go on the front of the queue, restarting from `/` for an absolute target. An absent component ends the walk, and the directory stood in is where the entry is created. Nothing calls `realpath`: it answers only with the final directory, so every directory stepped through on the way can disappear from the answer, and a JS `realpath` simplifies `..` lexically while the kernel applies it to the link's target. +Three shapes this closes, each of which an earlier shape of the rule accepted: +- A plain directory under a shared one can hold a link into a private destination, so the destination looks private while the ground it stands on is shared: `rec -> shared/relay/sub`, `shared` at 0777 and not sticky, `shared/relay -> chosen`. Judging each lookup catches `shared`. +- A link inside a link target hides its own directory, and a followed link's owner was never asked: `~/rec -> /tmp/relay -> ~/chosen`, `relay` another user's file in sticky `/tmp`. Every followed link is judged with `untrustedLinkExposure` against the directory that holds it, at any depth, so spelling the target directly and arriving through a link answer the same way. +- `..` applies to the directory the walk is in: with `home/work -> priv/x` and `priv/y` at 0777, `home/work/../y` lands in `priv/y`, not in the private `home/y` the normalized spelling names. +A link hop count is kept and refused at `link_loop_exceeded` below the limit the kernel applies (macOS 32, Linux 40), so a walk that ran out of hops is a refusal rather than a pass, and a loop can never be trusted. A component that is neither a directory nor a link is refused as `not_a_directory`: the kernel cannot travel through it either. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. +The sticky bit excuses a directory the walk passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. The link's own mode is never consulted: a link's bits say nothing about access on Linux, so what is judged is the directory the walk lands in, plus the ownership of the link and of the directory that holds it. +A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories. This is the one place the rule reads `/etc/group` and `/etc/passwd`, and it is admitted only where those two files can be shown to be the whole story: `/etc/nsswitch.conf` must exist, be readable, and list `files` as the only source for both `passwd` and `group`. `systemd` is not admitted either, because `systemd-userdbd` answers membership from records those files never show. Otherwise the exception is refused and a group-writable directory is treated as shared. Every group record carrying that numeric gid is then read, because a directory group-writable by gid 1000 is writable by the members of each group that holds the number, however it is named: `ada:x:1000:` beside `team:x:1000:grace` reaches grace. +The script file is created 0600, locally and remotely alike, so a recording is not world-readable in a directory that is merely shared. +The publisher compares the destination directory's captured `dev:ino` before publishing. The ownership rule above already excludes anyone able to swap that directory, so the comparison is defense in depth against a host whose ownership or modes moved during the download, not the check that closes the window. +Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the permissions rule is what substitutes for it. + +### What the guarantee does not cover + +The rule judges ownership bits, mode bits and link shape. Three things sit outside it, and no combination of them is a reason to expect confidentiality: + +- **ACLs.** macOS and Linux filesystem ACLs are consulted ahead of the mode bits, and the rule does not read them. A directory at 0700 can still grant `everyone` write through an ACL, letting another user plant or swap a component; a 0600 file can still inherit an `everyone` read entry, so the file's mode is not a promise about who can read it. Checking ACLs is deliberately not implemented. Callers who need that guarantee on such a host choose the destination's permissions and ACLs together. +- **Network filesystems.** NFS, SMB and FUSE mounts answer ownership, mode and link questions however the server pleases, and an unverified server can change any of them while the publish runs. Uids on a mount are usually not the uids on this host either. A script destination on a network mount is outside the guarantee. +- **Bind mounts and mounts in general.** A directory can be mounted over another after the judgment, and the publish writes into whatever stands there. The `dev:ino` comparison notices a replaced destination directory on the same route that captured its identity; it cannot notice a mount that was already there and was never judged. + +So the guarantee is: on a local filesystem with no ACLs on the directories the walk judges, no other non-root local user can steer where the recording is written or create that file. It is not a promise that nobody else can read the file. +A local write fails with `script_ancestor_untrusted` or `script_ancestry_replaced`; a remote version keeps its command's success and carries that reason as the `scriptDeliveryFailure` cause. Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions. Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol. Rejected: delivery only at close, because a session that an external owner closes would lose its recording. diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts new file mode 100644 index 0000000000..19578d277a --- /dev/null +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -0,0 +1,404 @@ +import { afterEach, expect, test, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { + FOREIGN_UID, + createLiveTestHostEnvironment, + mkdtempForTestSync, + serveHostOwnership, +} from '@agent-device/test-kit'; +import { SessionScriptWriter } from '../session-script-writer.ts'; +import { makeAuthoringSession } from '../../__tests__/support/session-factories.ts'; + +const hostCwd = createLiveTestHostEnvironment().cwd; +const skipOnWindows = process.platform === 'win32' ? test.skip : test; + +const realReadFileSync = fs.readFileSync; +/** The account the fixtures name for this process, the same one the rule reads back out of passwd. */ +const currentUser = process.env.USER ?? ''; + +/** This process's ids. Windows has neither, and every test that uses them is skipped there. */ +const currentUid = process.getuid?.() ?? -1; +const currentGid = process.getgid?.() ?? -1; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * Serves `groups` and `passwd` for the two group files and the real host for everything else, so the + * private-group decision is the fixture's and this file's assertions run on every POSIX host instead of + * only on one whose `/etc/group` happens to agree. + */ +function serveGroupDatabase(groups: readonly string[], passwd: readonly string[]): void { + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { + if (file === '/etc/group') return `${groups.join('\n')}\n`; + if (file === '/etc/passwd') return `${passwd.join('\n')}\n`; + // The private-group exception is admitted only where the host's own databases are the whole story. + if (file === '/etc/nsswitch.conf') return 'passwd: files\ngroup: files\n'; + return realReadFileSync(file as never, options as never) as never; + }) as typeof fs.readFileSync); +} + +/** This host's user owning `currentGid` alone, plus a team group that holds someone else. */ +function privateGroupDatabase(): void { + serveGroupDatabase( + ['root:x:0:root', `${currentUser}:x:${currentGid}:`, 'team:x:4321:ada'], + ['root:x:0:0', `${currentUser}:x:${currentUid}:${currentGid}:`], + ); +} + +/** The same ids, with this host's group named after somebody else, so it is not private. */ +function foreignGroupNameDatabase(): void { + serveGroupDatabase( + ['root:x:0:root', `${currentUser}:x:${currentGid + 1}:`, 'team:x:4321:ada'], + ['root:x:0:0', `${currentUser}:x:${currentUid}:${currentGid}:`], + ); +} + +function action(command: string): { + ts: number; + command: string; + positionals: string[]; + flags: Record; +} { + return { ts: Date.now(), command, positionals: ['Demo'], flags: {} }; +} + +function recordingTo(destination: string) { + return makeAuthoringSession('journey', { + scriptPublication: { + kind: 'authoring', + status: 'armed', + target: { kind: 'explicit', path: destination, force: false }, + }, + actions: [action('open')], + }); +} + +function root(): string { + return fs.realpathSync(mkdtempForTestSync('agent-device-script-ancestry-')); +} + +function sharedDirectory(directory: string, mode: number): string { + fs.mkdirSync(directory); + fs.chmodSync(directory, mode); + return directory; +} + +/** A scratch directory in this host's own primary group, at `mode`. */ +function homeDirectory(directory: string, mode: number): string { + fs.mkdirSync(directory); + fs.chownSync(directory, currentUid, currentGid); + fs.chmodSync(directory, mode); + return directory; +} + +function writerFor(directory: string): SessionScriptWriter { + return new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); +} + +function refusal(result: ReturnType): Record { + expect(result.written).toBe(false); + if (result.written || !result.error) throw new Error('expected a refused write'); + return result.error.details as Record; +} + +skipOnWindows('an ordinary recording saves under a chain only this user can write', () => { + const directory = root(); + const destination = path.join(directory, 'workflows', 'journey.ad'); + + const result = writerFor(directory).write(recordingTo(destination)); + + expect(result.written).toBe(true); + expect(fs.readFileSync(destination, 'utf8')).toContain('open'); +}); + +skipOnWindows('a recording saves a script no other local user can read', () => { + const directory = root(); + const destination = path.join(directory, 'workflows', 'journey.ad'); + + const result = writerFor(directory).write(recordingTo(destination)); + + expect(result.written).toBe(true); + expect(fs.lstatSync(destination).mode & 0o777).toBe(0o600); +}); + +skipOnWindows('a recording refuses a destination under a world-writable directory', () => { + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const destination = path.join(shared, 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); + expect(fs.existsSync(destination)).toBe(false); +}); + +skipOnWindows('a recording refuses a destination inside a directory another user owns', () => { + const directory = root(); + const foreign = path.join(directory, 'foreign'); + fs.mkdirSync(foreign); + fs.chmodSync(foreign, 0o755); + const destination = path.join(foreign, 'journey.ad'); + // The directory is this test user's own, so the rule is run as somebody else: a real second local + // user looking at a directory they cannot own but can read. + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); + expect(fs.existsSync(destination)).toBe(false); +}); + +skipOnWindows('a recording refuses a directory another user made sticky and owns', () => { + const directory = root(); + // `chmod 1777` on a directory of THEIRS: the sticky bit keeps me from clearing their entries, and does + // nothing to stop them renaming the component my path runs through. + const team = path.join(directory, 'team'); + fs.mkdirSync(team); + fs.chmodSync(team, 0o1777); + const destination = path.join(team, 'journey.ad'); + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); + expect(fs.readdirSync(team)).toEqual([]); +}); + +skipOnWindows('a recording refuses a shared directory another user claimed first', () => { + const directory = root(); + // The `mkdir -p /recordings` shape in a sticky shared directory: whoever creates it owns it, + // and the owner can swap it for one of their own whenever they like. + const tmp = path.join(directory, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + const recordings = path.join(tmp, 'recordings'); + fs.mkdirSync(recordings); + fs.chmodSync(recordings, 0o755); + const destination = path.join(recordings, 'journey.ad'); + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); + expect(fs.readdirSync(recordings)).toEqual([]); +}); + +skipOnWindows('a recording refuses an ancestor swapped out for a symbolic link', () => { + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + const destination = path.join(shared, 'work', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + // The shared ground itself is the first exposure: anyone can rename `work` aside there, sticky or not. + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + +skipOnWindows('a recording refuses an ancestor whose target is a writable directory', () => { + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const privateWork = path.join(shared, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(directory, 'link')); + const destination = path.join(directory, 'link', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + +skipOnWindows('a recording refuses an ancestor swapped out for a writable directory', () => { + const directory = root(); + const work = path.join(directory, 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + // Another local user replaces the destination directory by name before this write runs. + fs.rmSync(work, { recursive: true }); + fs.mkdirSync(work); + fs.chmodSync(work, 0o777); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); + expect(fs.readdirSync(work)).toEqual([]); +}); + +skipOnWindows('a recording refuses a private link standing on shared ground two levels up', () => { + // `/shared` is 0777 and not sticky, `/shared/mine` is 0700, and `mine/rec` links to a + // private directory. Every directory the destination's real path names is private, so only judging + // each prefix the kernel traverses sees that another local user owns the ground under `mine` and `rec`. + const directory = root(); + const shared = path.join(directory, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const mine = path.join(shared, 'mine'); + fs.mkdirSync(mine); + fs.chmodSync(mine, 0o700); + const privateWork = path.join(directory, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + const destination = path.join(mine, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + +skipOnWindows('a recording refuses a chain that leaves a shared directory through a link', () => { + // `~/rec -> /srv/team/relay -> ~/chosen`. The team ground is 0777, and any teammate can swap the + // `relay` link for a target of their own, though the destination's real path never names it. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const team = path.join(directory, 'srv', 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = path.join(directory, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: team, + }); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('a recording refuses the directory a .. steps back into', () => { + // `home/work -> priv/x`, and `priv/y` at 0777 while `home/y` is private. Normalizing the spelling first + // answers `home/y`, so it accepts a write that the kernel lands in `priv/y`, where any local user can + // take the recording. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + fs.chmodSync(home, 0o700); + const priv = path.join(directory, 'priv'); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX, { recursive: true }); + const privY = path.join(priv, 'y'); + fs.mkdirSync(privY); + fs.chmodSync(privY, 0o777); + fs.mkdirSync(path.join(home, 'y')); + fs.symlinkSync(privX, path.join(home, 'work')); + const destination = `${home}/work/../y/journey.ad`; + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: privY, + }); + expect(fs.readdirSync(privY)).toEqual([]); +}); + +skipOnWindows('a recording refuses the ground a link target crosses on the way in', () => { + // `home/rec -> /shared/relay/sub`, with `shared` at 0777 and not sticky and `shared/relay` a link + // into a directory of mine. Every directory at the destination looks private; only walking the target + // component by component shows that getting there crossed `shared`, where any other local user can swap + // `relay` for one of their own. + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const relayTarget = path.join(directory, 'chosen'); + fs.mkdirSync(relayTarget); + fs.chmodSync(relayTarget, 0o700); + fs.symlinkSync(relayTarget, path.join(shared, 'relay')); + const sub = path.join(relayTarget, 'sub'); + fs.mkdirSync(sub); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + fs.chmodSync(home, 0o700); + fs.symlinkSync(path.join(shared, 'relay', 'sub'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(relayTarget)).toEqual(['sub']); +}); + +skipOnWindows('a recording refuses a link another local user owns on the way in', () => { + // `~/rec -> /tmp/relay -> ~/chosen`, with `relay` another user's file in a sticky shared + // directory: they can unlink it and leave one of their own, and the second hop is theirs to choose. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const chosen = path.join(directory, 'chosen'); + fs.mkdirSync(chosen); + const relay = path.join(directory, 'relay'); + fs.symlinkSync(chosen, relay); + const tmp = path.join(directory, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + fs.renameSync(relay, path.join(tmp, 'relay')); + fs.symlinkSync(path.join(tmp, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + serveHostOwnership({ [path.join(tmp, 'relay')]: FOREIGN_UID }); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'planted_link' }); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('a recording still saves to a group-writable private-group home', () => { + privateGroupDatabase(); + const directory = root(); + const home = homeDirectory(path.join(directory, 'home'), 0o775); + const destination = path.join(home, 'journey.ad'); + + const result = writerFor(directory).write(recordingTo(destination)); + + expect(result.written).toBe(true); + expect(fs.readFileSync(destination, 'utf8')).toContain('open'); +}); + +skipOnWindows("a recording refuses the same home once the group is not this user's own", () => { + foreignGroupNameDatabase(); + const directory = root(); + const home = homeDirectory(path.join(directory, 'home'), 0o775); + + const details = refusal(writerFor(directory).write(recordingTo(path.join(home, 'journey.ad')))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'shared_group_writable', + ancestor: home, + }); +}); diff --git a/packages/daemon/src/core/__tests__/session-script-writer.test.ts b/packages/daemon/src/core/__tests__/session-script-writer.test.ts index 054b1ce2e0..7d0ae670d3 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer.test.ts @@ -696,8 +696,11 @@ test('an ordinary (non-repair) recording now refuses an existing target too (beh test('an ordinary recording returns a filesystem write failure as a typed error, never a quiet skip', () => { const root = mkdtempForTestSync('agent-device-script-writer-ordinary-fs-failure-'); const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd); + // A directory this user owns but cannot write: the ancestry rule has nothing to refuse there, so the + // failure the caller sees is the filesystem's own, not an ancestry verdict. const blocker = path.join(root, 'blocker'); - fs.writeFileSync(blocker, ''); + fs.mkdirSync(blocker); + fs.chmodSync(blocker, 0o500); const outPath = path.join(blocker, 'flow.ad'); const session = makeAuthoringSession('default', { scriptPublication: authoringPublication('armed', { path: outPath }), diff --git a/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts b/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts index 7bff2bfb17..b7a4a0ece5 100644 --- a/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts +++ b/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts @@ -81,7 +81,8 @@ test.skipIf(process.platform === 'win32')( expect(fs.statSync(result.path).mode & 0o777).toBe(0o600); } expect(localWrite).toMatchObject({ written: true, path: local }); - const umask = process.umask(); - expect(fs.statSync(local).mode & 0o777).toBe(0o666 & ~umask); + // A recording is a transcript of what someone did on this machine, so the caller's own file is + // private too, whatever the umask would have allowed (#4565). + expect(fs.statSync(local).mode & 0o777).toBe(0o600); }, ); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index be5050e645..0d26cfed63 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -19,7 +19,7 @@ import { stripRecordedRefGeneration, } from '@agent-device/ad-script'; import { expandSessionPath, safeSessionName } from '@agent-device/host-kit/session-paths'; -import { publishFileSync } from '@agent-device/host-kit/file'; +import { publishDirectoryIdentity, publishScriptFileSync } from '@agent-device/host-kit/file'; import type { SessionState } from './session-state.ts'; import { NO_SCRIPT_PUBLICATION, @@ -143,7 +143,7 @@ export class SessionScriptWriter { scriptPath, script: prepared.script, force: options?.force, - ...(remote ? { mode: 0o600 } : {}), + parentIdentity: publishDirectoryIdentity(scriptDir), }); // COMMITTED: idempotent guard above + teardown's abort/tombstone routing. if (repairArmed) { @@ -165,8 +165,9 @@ export class SessionScriptWriter { /** * A remote recording's caller downloads each version once, so every version, the close-time - * script included, gets a fresh private (0600) file in a private (0700) directory that only the - * daemon user can read. + * script included, gets a fresh file of its own in a private (0700) directory that only the daemon + * user can enter. The file itself is private (0600) like every other published script, which + * `publishScriptFileSync` decides. */ private remoteScriptPath(): string { const directory = path.join(this.sessionsDir, 'remote-scripts'); @@ -231,21 +232,40 @@ function handleSessionScriptWriteFailure(params: { return { written: false, error: toOrdinaryWriteFailure(error, scriptPath) }; } -function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError { - if (error instanceof AppError) return error; +/** + * A filesystem failure that has to reach the caller as its own typed error: an ordinary recording + * carries `script_write_failed` with the path it could not be written to, and both name what was being + * written, because the same writer publishes a recording and a healed repair. + */ +function toScriptWriteFailure( + error: unknown, + scriptPath: string | undefined, + subject: Readonly<{ noun: string; hint: string; reportsPath?: boolean }>, +): AppError { const detail = error instanceof Error ? error.message : String(error); + const where = scriptPath === undefined ? '' : ` to ${scriptPath}`; return new AppError( 'COMMAND_FAILED', - `Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, + `Failed to write the ${subject.noun}${where}: ${detail}`, { - reason: 'script_write_failed', - ...(scriptPath ? { path: scriptPath } : {}), - hint: 'Check the target path and its permissions, then re-record with open --save-script.', + ...(subject.reportsPath === true && scriptPath !== undefined + ? { reason: 'script_write_failed' as const, path: scriptPath } + : {}), + hint: subject.hint, }, error, ); } +function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError { + if (error instanceof AppError) return error; + return toScriptWriteFailure(error, scriptPath, { + noun: 'session script', + reportsPath: true, + hint: 'Check the target path and its permissions, then re-record with open --save-script.', + }); +} + /** * ADR 0012 decision 6 (BLOCKER 2c): normalizes a repair-commit failure into a * distinct, surfaceable AppError. A no-clobber refusal or a bare-`@ref` failure @@ -255,14 +275,10 @@ function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): */ function toRepairCommitFailure(error: unknown, scriptPath: string | undefined): AppError { if (error instanceof AppError) return error; - const detail = error instanceof Error ? error.message : String(error); - return new AppError( - 'COMMAND_FAILED', - `Failed to write the healed script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, - { - hint: 'The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.', - }, - ); + return toScriptWriteFailure(error, scriptPath, { + noun: 'healed script', + hint: 'The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.', + }); } /** @@ -301,15 +317,15 @@ function publishHealedScriptAtomically(params: { scriptPath: string; script: string; force?: boolean; - mode?: number; + parentIdentity?: string; }): void { - const { scriptPath, script, force, mode } = params; + const { scriptPath, script, force, parentIdentity } = params; try { - publishFileSync({ + publishScriptFileSync({ destination: scriptPath, contents: script, publish: force ? 'replace' : 'link-exclusive', - ...(mode === undefined ? {} : { mode }), + ...(parentIdentity === undefined ? {} : { parentIdentity }), }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; diff --git a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts index 5629f2cc37..84a5d57d70 100644 --- a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts +++ b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts @@ -23,7 +23,7 @@ const PROCESS_LOCK_SOURCE = new URL( test('simple same-directory publishers use the shared atomic publish owner', () => { for (const sourcePath of SIMPLE_PUBLISHERS) { const source = fs.readFileSync(sourcePath, 'utf8'); - assert.match(source, /publishFileSync/); + assert.match(source, /publish(?:Script)?FileSync/); assert.doesNotMatch(source, /fs\.(?:writeFileSync|renameSync)\s*\(/); } }); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts index 0b38fb0b83..42466b9f80 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts @@ -195,9 +195,11 @@ test('#1533: an ordinary armed authoring session still publishes on bare close', test('ordinary close reports a filesystem failure of its script write instead of a quiet success', () => { const root = mkdtempForTestSync('agent-device-session-close-script-fs-'); roots.push(root); - // A regular file where the target directory must be: publishing into it fails with ENOTDIR. + // A directory this user owns but cannot write: publishing into it fails with EACCES, and the ancestry + // rule has nothing to refuse there, so the caller sees the filesystem's own failure. const blocker = path.join(root, 'blocker'); - fs.writeFileSync(blocker, ''); + fs.mkdirSync(blocker); + fs.chmodSync(blocker, 0o500); const targetPath = path.join(blocker, 'flow.ad'); const { req, ref, sessionStore } = setup( 'fs-failure', diff --git a/packages/host-kit/src/file.ts b/packages/host-kit/src/file.ts index fd0b251e09..8779eccfb5 100644 --- a/packages/host-kit/src/file.ts +++ b/packages/host-kit/src/file.ts @@ -1,7 +1,10 @@ export { + assertPrivateScriptDestination, isAtomicPublishTemporaryPath, + publishDirectoryIdentity, publishDurableFileSync, publishFileSync, + publishScriptFileSync, type DurableFilePublishMode, } from './internal/atomic-file.ts'; export { diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts new file mode 100644 index 0000000000..54314a81ac --- /dev/null +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -0,0 +1,872 @@ +import { afterEach, expect, test, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; +import { + assertPrivateScriptDestination, + othersCreateEntriesIn, + publishDirectoryIdentity, + publishScriptFileSync, + untrustedAncestryExposure, + untrustedLinkExposure, + MAX_SCRIPT_PATH_LINK_HOPS, + type DirectoryAuthority, +} from './atomic-file.ts'; + +const skipOnWindows = process.platform === 'win32' ? test.skip : test; + +/** The group database a test stands in for `/etc/group` and `/etc/passwd`. */ +type Database = Readonly<{ + groups: readonly string[] | undefined; + passwd: readonly string[] | undefined; + /** `undefined` means "only files"; an empty array means "the file cannot be read". */ + nsswitch?: readonly string[] | undefined; +}>; + +const realReadFileSync = fs.readFileSync; +/** + * The account the fixture's databases name for this process. `readCurrentUser()` reads it from + * `passwdFile` below, so the fixture and the rule agree without a second host lookup. + */ +const currentUser = process.env.USER ?? ''; +/** The unmocked `stat` calls, so a second fixture here never wraps the first one's mock. */ +const realLstatSync = fs.lstatSync.bind(fs); +const realStatSync = fs.statSync.bind(fs); + +/** This process's ids. Windows has neither, and every test that uses them is skipped there. */ +const currentUid = process.getuid?.() ?? -1; +const currentGid = process.getgid?.() ?? -1; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * Serves `database` for the two group files and the real host for everything else, so the + * private-group decision is the fixture's and not the CI image's user list. + */ +function serveGroupDatabase(database: Database): void { + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { + if (file === '/etc/group') { + if (!database.groups) throw new Error('simulated unreadable group file'); + return `${database.groups.join('\n')}\n`; + } + if (file === '/etc/passwd') { + if (!database.passwd) throw new Error('simulated unreadable passwd file'); + return `${database.passwd.join('\n')}\n`; + } + if (file === '/etc/nsswitch.conf') return nsswitchContents(database.nsswitch); + return realReadFileSync(file as never, options as never) as never; + }) as typeof fs.readFileSync); +} + +/** The name-service lines of the fixture host: `files` only, unless the test asks for more. */ +function nsswitchContents(sources: readonly string[] | undefined): string { + if (sources === undefined) return 'passwd: files\ngroup: files\n'; + if (sources.length === 0) throw new Error('simulated unreadable nsswitch.conf'); + return `${sources.join('\n')}\n`; +} + +/** This host's user with a group of their own, and a team group that holds someone else. */ +function hostDatabase(privateGid: number, sharedGid: number): Database { + return { + groups: ['root:x:0:root', `${currentUser}:x:${privateGid}:`, `team:x:${sharedGid}:ada`], + passwd: [`root:x:0:0`, `${currentUser}:x:${currentUid}:${privateGid}:`], + nsswitch: undefined, + }; +} + +/** The database of a host whose group files cannot be read at all. */ +function unreadableDatabases(): Database { + return { groups: undefined, passwd: undefined }; +} + +/** + * Reports `owners` for the named paths and the real host for everything else, so the ownership rule is + * the fixture's and not the CI image's directory tree. Only the ids move: modes and inode numbers stay + * what they are on disk. A real foreign owner would need privileges this test does not have. + */ +function serveOwnership(owners: Readonly>): void { + const withUid = (stats: fs.Stats, pathname: string): fs.Stats => { + const uid = owners[pathname]; + if (uid === undefined || stats.uid === uid) return stats; + return Object.assign(Object.create(Object.getPrototypeOf(stats)), stats, { uid }) as fs.Stats; + }; + vi.spyOn(fs, 'lstatSync').mockImplementation(((pathname: never, ...rest: never[]) => + withUid(realLstatSync(pathname, ...rest), String(pathname))) as typeof fs.lstatSync); + vi.spyOn(fs, 'statSync').mockImplementation(((pathname: never, ...rest: never[]) => + withUid(realStatSync(pathname, ...rest), String(pathname))) as typeof fs.statSync); +} + +/** Some other local user, not this one and not root. */ +const FOREIGN_UID = 65534; + +function root(): string { + return fs.realpathSync(mkdtempForTestSync('host-kit-ancestry-')); +} + +/** + * A directory carrying `mode` and `gid`, so the rule reads the group the test chose. The group is set + * explicitly because a scratch directory inherits one from its parent, not necessarily this user's. + */ +function directoryWith(directory: string, mode: number, gid = currentGid): string { + fs.mkdirSync(directory); + fs.chownSync(directory, currentUid, gid); + fs.chmodSync(directory, mode); + return directory; +} + +function publish(destination: string, parentIdentity?: string): void { + publishScriptFileSync({ + destination, + contents: 'context\n', + ...(parentIdentity === undefined ? {} : { parentIdentity }), + }); +} + +function expectUntrusted(run: () => void, exposure: string, ancestor: string): void { + expectRefusal(run, 'script_ancestor_untrusted', exposure, ancestor); +} + +function expectUntrustedReplaced(run: () => void, ancestor: string): void { + expectRefusal(run, 'script_ancestry_replaced', 'parent_replaced', ancestor); +} + +function expectRefusal(run: () => void, reason: string, exposure: string, ancestor: string): void { + let details: Record | undefined; + try { + run(); + } catch (error) { + expect(error).toBeInstanceOf(AppError); + details = (error as AppError).details as Record; + } + expect(details).toMatchObject({ reason, exposure, ancestor }); +} + +function modeOf(pathname: string): number { + return fs.lstatSync(pathname).mode & 0o777; +} + +// --- a directory another user owns, or that others can write, is refused --- + +skipOnWindows('publishes to a chain only this user can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const workflows = path.join(root(), 'workflows'); + fs.mkdirSync(workflows); + + publish(path.join(workflows, 'journey.ad')); + + expect(fs.readFileSync(path.join(workflows, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('creates the script so that only this user can read it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const workflows = path.join(root(), 'workflows'); + fs.mkdirSync(workflows); + const destination = path.join(workflows, 'journey.ad'); + + publish(destination); + + expect(modeOf(destination)).toBe(0o600); +}); + +skipOnWindows('refuses a destination under a world-writable directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o777); + const destination = path.join(shared, 'journey.ad'); + + expectUntrusted(() => publish(destination), 'world_writable', shared); + expect(fs.existsSync(destination)).toBe(false); +}); + +skipOnWindows('refuses a destination created inside a directory others can add entries to', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o777 | 0o1000); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'journey.ad')), + 'shared_parent', + shared, + ); + expect(fs.existsSync(path.join(shared, 'journey.ad'))).toBe(false); +}); + +skipOnWindows('refuses a destination under a group-writable shared directory', () => { + serveGroupDatabase(hostDatabase(4321, currentGid)); + const team = directoryWith(path.join(root(), 'team'), 0o775, currentGid); + const sub = path.join(team, 'sub'); + fs.mkdirSync(sub); + + expectUntrusted(() => publish(path.join(sub, 'journey.ad')), 'shared_group_writable', team); + expect(fs.readdirSync(sub)).toEqual([]); +}); + +// --- ownership decides, not the mode alone --- + +skipOnWindows('refuses a directory another user owns, whatever the mode', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const work = directoryWith(path.join(root(), 'foreign'), 0o755); + serveOwnership({ [work]: FOREIGN_UID }); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), + 'foreign_owned', + work, + ); +}); + +skipOnWindows( + 'refuses a sticky directory another user owns, since both bits shield others from them', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The reviewer's case: a teammate runs `chmod 1777` on a directory of THEIRS. The sticky bit keeps me + // from deleting their entries; it does nothing to stop them replacing mine. + const team = directoryWith(path.join(root(), 'team'), 0o1777); + serveOwnership({ [team]: FOREIGN_UID }); + const work = path.join(team, 'work'); + fs.mkdirSync(work); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), + 'foreign_owned', + team, + ); + }, +); + +skipOnWindows( + 'refuses a recordings directory another local user created first in a sticky /tmp', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `mkdir -p /tmp/recordings` is the shape: `/tmp` is sticky so nobody can touch anyone else's entry, + // and whoever creates that directory first owns it. The owner can rename it aside and put their own in + // place, whatever its mode says, so the destination has to be refused. + const systemTmp = directoryWith(path.join(root(), 'tmp'), 0o1777); + const recordings = path.join(systemTmp, 'recordings'); + fs.mkdirSync(recordings); + fs.chmodSync(recordings, 0o755); + serveOwnership({ [systemTmp]: 0, [recordings]: FOREIGN_UID }); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(recordings, 'journey.ad')), + 'foreign_owned', + recordings, + ); + }, +); + +skipOnWindows('refuses a link standing in a private-mode directory another user owns', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The third input the reviewer names. `/teammate` is theirs at 0755, `link` is a component of my + // path, and the target is a directory of mine nothing could object to. Nothing about the target chain + // looks wrong: the exposure is that the OWNER of the directory the link stands in can rename that + // component and leave one of their own there, pointing wherever they like. + const directory = root(); + const teammate = directoryWith(path.join(directory, 'teammate'), 0o755); + serveOwnership({ [teammate]: FOREIGN_UID }); + const mine = directoryWith(path.join(directory, 'mine'), 0o700); + fs.symlinkSync(mine, path.join(teammate, 'link')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(teammate, 'link', 'journey.ad')), + 'foreign_owned', + teammate, + ); + expect(fs.readdirSync(mine)).toEqual([]); +}); + +skipOnWindows('refuses a private link standing on shared ground two levels up', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/shared` is 0777 and not sticky, `/shared/mine` is mine at 0700, and `mine/rec` is a + // link to my private directory. The final chain is all mine, and the link stands in ground only I can + // write, so neither the link rule nor the resolved-final-chain rule sees anything wrong. What they miss + // is that another local user owns the ground `mine` and `rec` stand on: they rename `mine` aside and + // put their own there, with a `rec` of their choosing. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const mine = directoryWith(path.join(shared, 'mine'), 0o700); + const privateWork = directoryWith(path.join(directory, 'private'), 0o700); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(mine, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + +skipOnWindows('refuses a chain that leaves a shared directory through an intermediate link', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /srv/team/relay`, and `relay` is a link back into a directory of mine. Every directory the + // final chain names is trusted; the walk still passes through `/srv/team`, which the team can write, + // and its owner — or any teammate — can swap `relay` for a target of their own. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const srv = path.join(directory, 'srv'); + const team = path.join(srv, 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + team, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('judges the directory a .. steps back into', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/private/link` points at `/elsewhere/dir`, and the caller spells `/link/../x`. + // The kernel walks `link` into its target and steps back from THERE, so the entry is created in + // `/elsewhere`, not in `/private`. Normalizing the spelling first would answer + // `/private/x` and judge the wrong directory: `` is open to others, `` is not. + const directory = root(); + const privateHome = directoryWith(path.join(directory, 'private'), 0o700); + const elsewhere = directoryWith(path.join(directory, 'elsewhere'), 0o777); + const dir = path.join(elsewhere, 'dir'); + fs.mkdirSync(dir); + fs.symlinkSync(dir, path.join(privateHome, 'link')); + + expectUntrusted( + () => assertPrivateScriptDestination(`${privateHome}/link/../x/journey.ad`), + 'world_writable', + elsewhere, + ); + expect(fs.readdirSync(dir)).toEqual([]); +}); + +skipOnWindows('refuses the ground under a link that leads into a shared directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/shared` is 0777 and not sticky, `/home/rec` is a link spelled `shared/mine/relay/subdir` + // whose `relay` is a link back into a private directory. Nothing at the destination looks wrong: the + // final chain is `/shared/mine/chosen/subdir`, and every one of those is private-looking. What + // the walk sees is that getting there crossed `/shared`, where any other local user can rename + // `mine` aside and put their own `relay` under it. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const mine = directoryWith(path.join(shared, 'mine'), 0o700); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + fs.symlinkSync(chosen, path.join(mine, 'relay')); + const home = directoryWith(path.join(directory, 'home'), 0o700); + fs.symlinkSync(path.join(shared, 'mine', 'relay', 'subdir'), path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('refuses the spelled spelling of a link the walk also follows', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The same target reached two ways has to answer the same way: spelling the shared directory out is + // refused, so arriving at it through a link cannot be accepted. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const work = path.join(home, 'work'); + fs.mkdirSync(work); + fs.symlinkSync(shared, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'journey.ad')), + 'world_writable', + shared, + ); +}); + +skipOnWindows('applies .. to the directory the walk is in, not to the spelling', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `home/work -> priv/x`, `priv/y` is open to others, `home/y` is private. A lexical simplification of + // the spelling answers `home/y`, which is safe, so it accepts a write that lands in `priv/y`, where any + // local user can take the file. The kernel steps into the link and steps back from its TARGET. + const directory = root(); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const priv = directoryWith(path.join(directory, 'priv'), 0o700); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX); + const privY = directoryWith(path.join(priv, 'y'), 0o777); + fs.mkdirSync(path.join(home, 'y')); + fs.symlinkSync(privX, path.join(home, 'work')); + + expectUntrusted( + () => assertPrivateScriptDestination(`${home}/work/../y/journey.ad`), + 'world_writable', + privY, + ); + expect(fs.readdirSync(privY)).toEqual([]); +}); + +skipOnWindows('refuses a link whose target stands in ground another local user owns', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /tmp/relay -> ~/chosen`, and `relay` is another user's file in a sticky shared + // directory. Sticky or not, they can unlink it and put one of their own there, so the second hop is + // theirs to choose. The judgment the expanded hop used to skip is the one on the link itself. + const directory = root(); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + const tmp = directoryWith(path.join(directory, 'tmp'), 0o1777); + const relay = path.join(tmp, 'relay'); + fs.symlinkSync(chosen, relay); + serveOwnership({ [tmp]: 0, [relay]: FOREIGN_UID }); + fs.symlinkSync(relay, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'planted_link', + relay, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('follows a link whatever mode it carries, judging the directory it lands in', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // A link's own mode means nothing for access: the kernel reads its target. An alias at 0777 leading to + // a directory only this user can write is therefore safe, and the refusal has to come from the + // directory, not from the link's bits. + const directory = root(); + const real = directoryWith(path.join(directory, 'real'), 0o700); + const alias = path.join(directory, 'current'); + fs.symlinkSync(real, alias); + // `lchmod` on a link is what a mode-carrying alias looks like; where the host reports one mode for all + // links, as Linux does, the walk has to be moved by the directory it lands in either way. + try { + fs.lchmodSync(alias, 0o777); + } catch { + /* this host gives every link the same mode */ + } + + publish(path.join(alias, 'journey.ad')); + + expect(fs.readFileSync(path.join(real, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('refuses a link loop instead of trusting where the walk ran out', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const loop = path.join(work, 'loop'); + fs.symlinkSync(loop, loop); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(loop, 'journey.ad')), + 'link_loop_exceeded', + loop, + ); + expect(fs.readdirSync(work)).toEqual(['loop']); +}); + +skipOnWindows('follows exactly as many link hops as the walk allows, and refuses one more', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const real = directoryWith(path.join(directory, 'real'), 0o700); + // `link0 -> link1 -> ... -> `, so the walk expands `count` links to reach the destination. + const chain = (count: number): string => { + let next = real; + for (let hop = count - 1; hop >= 0; hop -= 1) { + const link = path.join(work, `link${hop}`); + fs.rmSync(link, { force: true }); + fs.symlinkSync(next, link); + next = link; + } + return next; + }; + + publish(path.join(chain(MAX_SCRIPT_PATH_LINK_HOPS), 'journey.ad')); + expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); + fs.rmSync(path.join(real, 'journey.ad'), { force: true }); + + expectUntrusted( + () => + assertPrivateScriptDestination(path.join(chain(MAX_SCRIPT_PATH_LINK_HOPS + 1), 'journey.ad')), + 'link_loop_exceeded', + path.join(work, `link${MAX_SCRIPT_PATH_LINK_HOPS}`), + ); + expect(fs.readdirSync(real)).toEqual([]); +}); + +skipOnWindows('refuses a path component that cannot carry a publish', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const blocker = path.join(work, 'blocker'); + fs.writeFileSync(blocker, 'not a directory\n'); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(blocker, 'journey.ad')), + 'not_a_directory', + blocker, + ); +}); + +skipOnWindows('refuses a directory its owner opened up while the file was staged', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const work = path.join(root(), 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + const realWriteFileSync = fs.writeFileSync; + vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { + const result = (realWriteFileSync as (...args: unknown[]) => unknown)(file, ...rest); + fs.chmodSync(work, 0o777); + return result; + }) as typeof fs.writeFileSync); + + expectUntrusted(() => publish(destination), 'world_writable', work); + expect(fs.readdirSync(work)).toEqual([]); +}); + +// --- the Ubuntu and Debian private-group home keeps working --- + +skipOnWindows('publishes to a group-writable home directory of a private group', () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(gid, 4321)); + const home = directoryWith(path.join(root(), 'home'), 0o775, gid); + + publish(path.join(home, 'journey.ad')); + + expect(fs.readFileSync(path.join(home, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows("refuses the same mode and group once the group is not the user's own", () => { + serveGroupDatabase(hostDatabase(4321, currentGid)); + const home = directoryWith(path.join(root(), 'home'), 0o775, currentGid); + + expectUntrusted(() => publish(path.join(home, 'journey.ad')), 'shared_group_writable', home); +}); + +skipOnWindows('refuses the same mode and group once the group database cannot be read', () => { + serveGroupDatabase(unreadableDatabases()); + const home = directoryWith(path.join(root(), 'home'), 0o775, currentGid); + + expectUntrusted(() => publish(path.join(home, 'journey.ad')), 'shared_group_writable', home); +}); + +skipOnWindows('publishes to a setgid group-writable private-group home', () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(gid, 4321)); + const home = directoryWith(path.join(root(), 'home'), 0o2775, gid); + + publish(path.join(home, 'journey.ad')); + + expect(fs.existsSync(path.join(home, 'journey.ad'))).toBe(true); +}); + +// --- a link is judged as the link it is, and its target is judged too --- + +skipOnWindows('follows a symbolic link inside a directory only this user can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const real = path.join(directory, 'real'); + fs.mkdirSync(real); + fs.symlinkSync(real, path.join(directory, 'link')); + + publish(path.join(directory, 'link', 'journey.ad')); + + expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); +}); + +skipOnWindows('refuses a link planted in a directory others can add entries to', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The shared ground is refused where the walk enters it, one step before the link inside it: that + // directory is itself the exposure, since anyone can rename `work` aside as well as plant it. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), + 'world_writable', + shared, + ); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + +skipOnWindows('refuses a private link whose target chain is a shared directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /srv/team/rec`, with `/srv/team` open to the team. The link itself is this user's own in + // their own home, so nothing about it looks wrong; only the resolved chain shows the destination + // would sit in ground the whole team can write. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const srv = path.join(directory, 'srv'); + const team = path.join(srv, 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const rec = path.join(team, 'rec'); + fs.mkdirSync(rec); + fs.symlinkSync(rec, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + team, + ); +}); + +skipOnWindows('refuses a symbolic link whose target is a directory others can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const privateWork = path.join(shared, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(directory, 'link')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(directory, 'link', 'journey.ad')), + 'world_writable', + shared, + ); +}); + +skipOnWindows( + 'refuses a symbolic link another local user owns in a sticky shared directory', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The link's OWNER is the whole question, so it is the fixture's: root holds the sticky directory and + // somebody else owns the link. Moving only the caller's uid would decide the test by the accident of + // who runs the suite, and would say nothing when the suite runs as root. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o1777); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + const link = path.join(shared, 'work'); + fs.symlinkSync(attacker, link); + serveOwnership({ [shared]: 0, [link]: FOREIGN_UID }); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), + 'planted_link', + link, + ); + expect(fs.readdirSync(attacker)).toEqual([]); + }, +); + +skipOnWindows('keeps working through a root-owned alias whose target is sticky', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const alias = path.join(directory, 'alias'); + const target = path.join(directory, 'target'); + fs.mkdirSync(target); + fs.chmodSync(target, 0o1777); + fs.symlinkSync(target, alias); + const work = path.join(alias, 'work'); + fs.mkdirSync(work); + fs.chmodSync(work, 0o700); + + publish(path.join(work, 'journey.ad')); + + expect(fs.existsSync(path.join(target, 'work', 'journey.ad'))).toBe(true); +}); + +skipOnWindows('publishes under the host root-owned system temporary directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // macOS reaches `/private/tmp` through `/tmp`, Linux mounts `/tmp` directly. Both are sticky and + // root-owned, and the script is created in a private directory under it, so neither spelling may + // stop the publish. + const work = fs.mkdtempSync('/tmp/agent-device-ancestry-'); + fs.chmodSync(work, 0o700); + const destination = path.join(work, 'journey.ad'); + try { + publish(destination); + expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } +}); + +skipOnWindows('publishes to a path spelled through an alias of the directory that holds it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The caller passes a path whose parent is a link, in a chain only this user can write. The alias + // leads somewhere legal, so the publish follows it instead of refusing it. + const directory = root(); + const real = path.join(directory, 'workflows'); + fs.mkdirSync(real); + fs.symlinkSync(real, path.join(directory, 'current')); + const destination = path.join(directory, 'current', 'journey.ad'); + + publish(destination); + + expect(fs.readFileSync(path.join(real, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('publishes to a scratch path exactly as the host spelled it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The scratch root keeps the host's own spelling of its temporary directory: an alias on macOS, where + // `/var` stands for `/private/var`, and no alias at all on Linux. Neither spelling may stop a publish, + // so this asserts the outcome rather than what the host happens to name. + const directory = mkdtempForTestSync('host-kit-ancestry-spelled-'); + const destination = path.join(directory, 'journey.ad'); + + publish(destination); + + expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); +}); + +// --- the destination directory swapped out while the file was staged --- + +skipOnWindows('refuses a parent replaced by name while the file was staged', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const staged = path.join(directory, 'work'); + fs.mkdirSync(staged); + const parentIdentity = publishDirectoryIdentity(staged); + const destination = path.join(staged, 'journey.ad'); + // The replacement is a link to another real directory. Removing the directory and creating the same + // name again is not enough to make the two differ: a filesystem may hand back the inode it just + // freed, and the identity would match by luck. + const elsewhere = path.join(directory, 'elsewhere'); + fs.mkdirSync(elsewhere); + fs.rmSync(staged, { recursive: true }); + fs.symlinkSync(elsewhere, staged); + + expectUntrustedReplaced(() => publish(destination, parentIdentity), staged); + expect(fs.readdirSync(elsewhere)).toEqual([]); +}); + +skipOnWindows('re-checks the chain after staging the file, before the entry is created', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const staged = path.join(directory, 'work'); + fs.mkdirSync(staged); + const destination = path.join(staged, 'journey.ad'); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + const writeFileSync = fs.writeFileSync; + vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { + const result = (writeFileSync as (...args: unknown[]) => unknown)(file, ...rest); + // The directory the file was staged in is gone and its name is somebody else's now. A filesystem + // hands back a freed inode, so the swap has to be to a directory that is really another one. + fs.rmSync(staged, { recursive: true, force: true }); + fs.symlinkSync(attacker, staged); + return result; + }) as typeof fs.writeFileSync); + + expectUntrustedReplaced(() => publish(destination), staged); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + +skipOnWindows('publishes into the parent the captured identity still names', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const staged = path.join(root(), 'work'); + fs.mkdirSync(staged); + + publish(path.join(staged, 'journey.ad'), publishDirectoryIdentity(staged)); + + expect(fs.existsSync(path.join(staged, 'journey.ad'))).toBe(true); +}); + +// --- untrustedAncestryExposure: what makes one directory unsafe to publish inside --- + +const OWN = { uid: currentUid, gid: currentGid, mode: 0o755 }; +const TRUST = { uid: currentUid, privateGid: currentGid }; + +function directoryOf(overrides: Partial): DirectoryAuthority { + return { ...OWN, ...overrides }; +} + +test('refuses a directory another user owns, whatever its mode', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o700 }), TRUST)).toBe( + 'foreign_owned', + ); + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o755 }), TRUST)).toBe( + 'foreign_owned', + ); +}); + +test('refuses a directory that is world-writable', () => { + expect(untrustedAncestryExposure(directoryOf({ mode: 0o777 }), TRUST)).toBe('world_writable'); +}); + +test('refuses a directory that is group-writable by a group that is not this user', () => { + expect(untrustedAncestryExposure(directoryOf({ gid: 4321, mode: 0o775 }), TRUST)).toBe( + 'shared_group_writable', + ); +}); + +test('accepts a directory group-writable by this user', () => { + expect(untrustedAncestryExposure(directoryOf({ mode: 0o775 }), TRUST)).toBeUndefined(); +}); + +test('accepts a root-owned directory and a directory this user owns', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 0 }), TRUST)).toBeUndefined(); + expect(untrustedAncestryExposure(directoryOf({}), TRUST)).toBeUndefined(); +}); + +test('accepts a sticky directory this user or root owns for passing through', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 0, mode: 0o1777 }), TRUST)).toBeUndefined(); + expect(untrustedAncestryExposure(directoryOf({ mode: 0o1777 }), TRUST)).toBeUndefined(); +}); + +test('refuses a sticky directory another user owns, since both bits shield others FROM that owner', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o1777 }), TRUST)).toBe( + 'foreign_owned', + ); + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o2775 }), TRUST)).toBe( + 'foreign_owned', + ); +}); + +// --- untrustedLinkExposure: which link on the path belongs to somebody else --- + +test('accepts a link in a directory only this user or root can add entries to', () => { + const link = { uid: currentUid }; + expect(untrustedLinkExposure(link, directoryOf({ mode: 0o755 }), TRUST)).toBeUndefined(); + expect(untrustedLinkExposure(link, directoryOf({ mode: 0o775 }), TRUST)).toBeUndefined(); +}); + +test('refuses a link in a shared directory unless the sticky bit and its owner hold it in place', () => { + expect(untrustedLinkExposure({ uid: currentUid }, directoryOf({ mode: 0o777 }), TRUST)).toBe( + 'planted_link', + ); + expect(untrustedLinkExposure({ uid: 65534 }, directoryOf({ mode: 0o1777 }), TRUST)).toBe( + 'planted_link', + ); +}); + +test('accepts a link this user or root owns in a sticky shared directory', () => { + const sticky = directoryOf({ mode: 0o1777 }); + expect(untrustedLinkExposure({ uid: currentUid }, sticky, TRUST)).toBeUndefined(); + expect(untrustedLinkExposure({ uid: 0 }, sticky, TRUST)).toBeUndefined(); +}); + +// --- othersCreateEntriesIn: where another local user could claim the entry --- + +test('names a directory others can add entries in, sticky bit or no sticky bit', () => { + expect(othersCreateEntriesIn(directoryOf({ mode: 0o777 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o1777 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ gid: 4321, mode: 0o775 }), TRUST)).toBe(true); +}); + +test('names no directory whose group is this user', () => { + expect(othersCreateEntriesIn(directoryOf({ mode: 0o775 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o1775 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o755 }), TRUST)).toBe(false); +}); + +test('names a directory another user owns, whatever its mode', () => { + expect(othersCreateEntriesIn(directoryOf({ uid: 65534, mode: 0o755 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ uid: 65534, mode: 0o1777 }), TRUST)).toBe(true); +}); + +test('names no directory this user or root owns that others cannot write', () => { + expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o755 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o1777 }), TRUST)).toBe(true); +}); diff --git a/packages/host-kit/src/internal/atomic-file-private-group.test.ts b/packages/host-kit/src/internal/atomic-file-private-group.test.ts new file mode 100644 index 0000000000..440c702e31 --- /dev/null +++ b/packages/host-kit/src/internal/atomic-file-private-group.test.ts @@ -0,0 +1,134 @@ +// privateGroupId: the one group shape the destination-ancestry rule admits, and what a name service +// does to that claim. Both are pure decisions over host account records, so they are judged here rather +// than through a filesystem. + +import { expect, test } from 'vitest'; +import { nameServiceListsOnlyFiles, privateGroupId } from './atomic-file.ts'; + +const ADA = { uid: 1000, gid: 1000, name: 'ada' }; + +const FILES = ['passwd: files', 'group: files']; + +function database(groups: readonly string[] | undefined, passwd: readonly string[] | undefined) { + return { groups, passwd, nsswitch: FILES }; +} + +const PRIVATE = ['ada:x:1000:', 'staff:x:20:root']; +const PRIVATE_PASSWD = ['ada:x:1000:1000:', 'root:x:0:0']; + +test('admits the group named after the user, holding only them, as their primary group', () => { + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), ADA)).toBe(1000); +}); + +test('admits root named among the members, the account the whole rule trusts', () => { + expect( + privateGroupId(database(['ada:x:1000:root'], ['ada:x:1000:1000:', 'root:x:0:0']), ADA), + ).toBe(1000); +}); + +test('refuses a second group carrying the same gid when it lists another user', () => { + // `ada:x:1000:` looks private on its own, and the group named after the user is the only one the + // exception used to read. A directory group-writable by gid 1000 is writable by grace too, because + // `team` carries the same number. + expect( + privateGroupId( + database( + ['ada:x:1000:', 'team:x:1000:grace'], + ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], + ), + ADA, + ), + ).toBeUndefined(); +}); + +test('admits a second group carrying the same gid when it reaches nobody else', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'ada-alias:x:1000:'], ['ada:x:1000:1000:', 'root:x:0:0']), + ADA, + ), + ).toBe(1000); +}); + +test('refuses it once a second group sharing the gid has another user as its primary group', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'team:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), + ADA, + ), + ).toBeUndefined(); +}); + +test('refuses it once another user is a member', () => { + expect( + privateGroupId( + database(['ada:x:1000:grace'], ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0']), + ADA, + ), + ).toBeUndefined(); +}); + +test('refuses it once another user has it as their primary group', () => { + expect( + privateGroupId(database(['ada:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), ADA), + ).toBeUndefined(); +}); + +test('refuses a group that is not the primary group of the user, however few members it lists', () => { + expect(privateGroupId(database(['ada:x:4321:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses a group that does not carry the name of the user', () => { + expect(privateGroupId(database(['team:x:1000:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses it when the group file cannot be read', () => { + expect(privateGroupId(database(undefined, PRIVATE_PASSWD), ADA)).toBeUndefined(); +}); + +test('refuses it when the passwd file cannot be read', () => { + expect(privateGroupId(database(PRIVATE, undefined), ADA)).toBeUndefined(); +}); + +test('refuses it when the user has no passwd record', () => { + expect(privateGroupId(database(PRIVATE, ['root:x:0:0']), ADA)).toBeUndefined(); +}); + +test('refuses it when the passwd record names another uid or gid', () => { + const other = { uid: 1002, gid: 1000, name: 'ada' }; + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), other)).toBeUndefined(); +}); + +test('refuses it when /etc/nsswitch.conf cannot be read', () => { + expect( + privateGroupId({ groups: PRIVATE, passwd: PRIVATE_PASSWD, nsswitch: undefined }, ADA), + ).toBeUndefined(); +}); + +test('refuses it when nsswitch.conf adds a name service to either database', () => { + const withNameService = (databaseLines: string[]) => + privateGroupId({ groups: PRIVATE, passwd: PRIVATE_PASSWD, nsswitch: databaseLines }, ADA); + + expect(withNameService(['passwd: files ldap', 'group: files'])).toBeUndefined(); + expect(withNameService(['passwd: files', 'group: files sss'])).toBeUndefined(); + // `systemd` is the default on some distributions and is still refused: userdbd answers membership from + // records these two files never show. + expect(withNameService(['passwd: files systemd', 'group: files systemd'])).toBeUndefined(); + expect(withNameService(['passwd: files', 'group:'])).toBeUndefined(); + expect(withNameService(['# no database lines here'])).toBeUndefined(); +}); + +test('admits a name service line that names only files, actions and comments aside', () => { + expect( + nameServiceListsOnlyFiles(['passwd: [NOTFOUND=return] files # local only', 'group: files']), + ).toBe(true); + expect(nameServiceListsOnlyFiles(['passwd: files', 'group: files db'])).toBe(false); + expect(nameServiceListsOnlyFiles(undefined)).toBe(false); +}); + +test('gives a caller without a full identity no private group', () => { + const groups = database(PRIVATE, PRIVATE_PASSWD); + expect(privateGroupId(groups, { uid: undefined, gid: 1000, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: undefined, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: 1000, name: undefined })).toBeUndefined(); +}); diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index bb00b26944..1adabb0a20 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -1,6 +1,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; import { emitDiagnostic } from './diagnostics.ts'; export type AtomicPublishMode = 'replace' | 'link-exclusive'; @@ -42,6 +43,39 @@ export function publishFileSync(options: { }); } +/** + * Publishes a session script, and nothing else, from a same-directory temporary sibling. + * + * This is `publishFileSync` plus the destination-ancestry rule (#4565): the chain is refused before + * anything is staged, and it is judged again immediately before the link or rename. The file is created + * private, because a recording is a transcript of what someone did on this machine. + * + * `parentIdentity` is what {@link publishDirectoryIdentity} returned for a parent the caller created or + * checked before it staged this file. + */ +export function publishScriptFileSync(options: { + destination: string; + contents: string; + publish?: AtomicPublishMode; + parentIdentity?: string; +}): void { + const expected = + options.parentIdentity ?? publishDirectoryIdentity(path.dirname(options.destination)); + withAtomicPublishTempPathSync(options.destination, (temporaryPath) => { + assertPrivateScriptDestination(options.destination, expected); + fs.writeFileSync(temporaryPath, options.contents, { encoding: 'utf8', mode: SCRIPT_FILE_MODE }); + assertPrivateScriptDestination(options.destination, expected); + if (options.publish === 'link-exclusive') { + fs.linkSync(temporaryPath, options.destination); + } else { + fs.renameSync(temporaryPath, options.destination); + } + }); +} + +/** A recording holds literals a `fill` did not parameterize (ADR 0017), so it is written private. */ +const SCRIPT_FILE_MODE = 0o600; + export type DurableFilePublishMode = 'replace' | 'link-exclusive'; /** Publishes complete UTF-8 contents with a durable file and directory fence. */ @@ -148,6 +182,580 @@ export function isAtomicPublishTemporaryPath(value: unknown, destination: string return name.startsWith(`.${path.basename(destination)}.`) && name.endsWith('.tmp'); } +/** + * Refuses a script destination unless every directory on its fully resolved chain is one no other + * non-root local user can change (#4565). + * + * Node exposes no `openat` or `renameat`, so a publisher cannot resolve a destination relative to a + * directory handle. The window is closed by PERMISSIONS instead of by timing: once no other non-root + * user can add or remove an entry in any directory on the chain, nobody can swap a component out or + * plant one, so the path this rule judged is the path the publish reaches. Nothing here depends on when + * the directory was judged, and no re-check is what makes the write safe. + * + * The existing prefix of the destination is resolved once, and every directory of that resolved chain + * is judged, so a symbolic link's target is judged too: `/home/me/link` standing for a shared directory + * is refused for the same reason that directory would be if the caller had spelled it out. Each + * directory then has to satisfy: + * + * - It is owned by this user or by root. A directory another user owns is theirs to chmod, to empty, and + * to repopulate, whatever its mode says today, and both the sticky bit and the group bits shield other + * users FROM that owner rather than the reverse. + * - Its mode opens its contents to nobody else. The sticky bit is the one exception, and only for + * passing THROUGH a directory: it stops anyone but an entry's owner or root from removing or replacing + * that entry, which is how macOS `/tmp` and `/var` stay usable. It cannot refuse a NEW entry by name, + * so nothing may be created inside a directory others can add entries to; that is asked separately. + * - A symbolic link the path passes through is one others could not have planted or swapped: in a + * directory where they can add entries, it stands there only because the sticky bit and its owner + * hold it in place. + * + * A group-writable directory this user owns stays acceptable when its group is this user's own private + * group, the shape Ubuntu and Debian give every home directory. {@link privateGroupId} says what that + * takes to establish, and what it cannot. + * + * A component that exists and is neither a directory nor a link is left alone: the filesystem refuses a + * publish through it. On Windows, access is an ACL rather than a mode, so this is a no-op there. + * + * `parentIdentity` is what {@link publishDirectoryIdentity} returned for the parent the caller created + * or checked before it staged this file. The rule above already excludes anyone who could swap that + * parent, so the comparison is defense in depth against a host whose ownership or modes moved meanwhile; + * it is not what closes the window. + */ +export function assertPrivateScriptDestination(destination: string, parentIdentity?: string): void { + if (process.platform === 'win32') return; + const parent = spelledParent(destination); + if (parentIdentity !== undefined && publishDirectoryIdentity(parent) !== parentIdentity) { + throw scriptAncestryFailure(destination, parent, 'parent_replaced'); + } + const trust = readScriptTrust(); + const walk = walkParent(destination, trust); + if (walk.reject !== undefined) throw walk.reject; + // The script entry is created inside the deepest directory the walk reached, or below it through + // directories that do not exist yet. Where other local users can add entries, one of them can add + // this entry first and the recording is theirs, so the creation has to be refused. + const deepest = statDirectoryChain(walk.deepest); + if (deepest && othersCreateEntriesIn(deepest, trust)) { + throw scriptAncestryFailure(destination, walk.deepest, 'shared_parent'); + } +} + +/** + * The parent of `destination`, made absolute but never normalized. + * + * `path.resolve` folds a `..` away, which is the one simplification this may not make: the kernel does + * not make it either, so `.../work/../x` lands its entry beside the target of the link named `work`. The + * spelled components are what the walk resolves; a relative destination keeps its relative spelling and + * starts from the working directory, which is how it reaches the filesystem. + */ +function spelledParent(destination: string): string { + if (path.isAbsolute(destination)) return path.dirname(destination); + const parent = path.dirname(destination); + return parent === '.' ? '' : parent; +} + +/** + * Where the walk stands: a directory it has already judged and physically reached, plus the names still + * to resolve. `deepest` is the directory the entry is created in when the walk stops here. + */ +type WalkState = Readonly<{ + deepest: string; + authority: DirectoryAuthority; + /** Path components left to resolve, nearest first. */ + queue: readonly string[]; + /** Link targets expanded so far. */ + hops: number; +}>; + +type WalkStep = + | Readonly<{ kind: 'reject'; path: string; exposure: ScriptAncestryExposure }> + | Readonly<{ kind: 'stop'; deepest: string }> + | Readonly<{ kind: 'stand'; state: WalkState }>; + +/** A walk that ended: the deepest directory reached, or the typed refusal. */ +type WalkOutcome = Readonly<{ reject: AppError | undefined; deepest: string }>; + +/** + * Walks the spelled parent exactly as the kernel resolves a path, judging every step, and refuses at the + * first step another local user could steer. + * + * No `realpath` is involved anywhere. `realpathSync` answers only with the FINAL directory, so any + * directory the resolution stepped through can vanish from the answer, and from the judgment, whenever a + * link leads on to another link, or a spelled prefix names a plain directory whose ground is shared. + * Instead each component is resolved against the directory physically reached: + * + * - `.` is skipped; `..` moves to the parent of the directory physically stood in, which is judged like + * any other directory. Neither one is a name that has to exist. + * - Any other component is lstat'ed in that directory. An absent component ends the walk, because the + * publish creates what is missing below here. + * - A directory is judged and entered. + * - A symbolic link is judged itself, against the directory that physically holds it, and its target's + * components go in front of the queue — restarting from `/` for an absolute target. Hops are counted + * against {@link MAX_SCRIPT_PATH_LINK_HOPS}, and crossing it is refused rather than trusted. + * - A component that is neither a directory nor a link cannot carry a publish, and is refused. + * + * A relative destination starts from the process's resolved working directory: the caller already stands + * there, and the walk cannot step above it. + */ +function walkParent(destination: string, trust: ScriptDestinationTrust): WalkOutcome { + let step = startWalk(spelledParent(destination), trust); + // Every step consumes a component, and every link hop counts against a fixed limit, so this ends. + for (;;) { + if (step.kind === 'reject') return { reject: refusalAt(destination, step), deepest: '/' }; + if (step.kind === 'stop') return { reject: undefined, deepest: step.deepest }; + const { state } = step; + if (state.queue.length === 0) return { reject: undefined, deepest: state.deepest }; + step = stepWalk(state, trust); + } +} + +function refusalAt( + destination: string, + step: Readonly<{ path: string; exposure: ScriptAncestryExposure }>, +): AppError { + return scriptAncestryFailure(destination, step.path, step.exposure); +} + +/** The first state: `/` for an absolute spelling, the resolved working directory otherwise. */ +function startWalk(parent: string, trust: ScriptDestinationTrust): WalkStep { + const queue = pathComponents(parent); + // A relative destination starts from the working directory as the kernel sees it, symlink-free: the + // caller already stands there, so it is where the walk starts rather than a step it has to earn. + if (parent !== '' && !path.isAbsolute(parent)) return standIn(path.resolve(''), queue, trust, 0); + return standIn('/', queue, trust, 0); +} + +/** Judges `directory` and stands the walk there, or refuses it. */ +function standIn( + directory: string, + queue: readonly string[], + trust: ScriptDestinationTrust, + hops: number, +): WalkStep { + const stats = statDirectoryChain(directory); + if (stats === undefined) return { kind: 'reject', path: directory, exposure: 'not_a_directory' }; + const authority: DirectoryAuthority = { uid: stats.uid, gid: stats.gid, mode: stats.mode }; + const exposure = untrustedAncestryExposure(authority, trust); + if (exposure) return { kind: 'reject', path: directory, exposure }; + return { kind: 'stand', state: { deepest: directory, authority, queue, hops } }; +} + +/** The names of `directory`, with every `.` resolved away the way the kernel resolves it. */ +function pathComponents(directory: string): string[] { + return directory.split('/').filter((component) => component.length > 0 && component !== '.'); +} + +/** Advances one component of the queue. */ +function stepWalk(state: WalkState, trust: ScriptDestinationTrust): WalkStep { + const [component, ...rest] = state.queue; + if (component === undefined) return { kind: 'stop', deepest: state.deepest }; + // `..` is the parent of the directory PHYSICALLY stood in, not of the spelling: where `work` is a link, + // `.../work/../x` steps back from the link's target and lands beside it. + if (component === '..') return standIn(path.dirname(state.deepest), rest, trust, state.hops); + return stepIntoEntry(state, component, rest, trust); +} + +/** Resolves one named entry inside the directory the walk stands in. */ +function stepIntoEntry( + state: WalkState, + component: string, + rest: readonly string[], + trust: ScriptDestinationTrust, +): WalkStep { + const entry = path.join(state.deepest, component); + const stats = lstatIfPresentSync(entry); + // Nothing below here exists yet, so the publish creates it inside the directory the walk reached. + if (stats === undefined) return { kind: 'stop', deepest: state.deepest }; + if (stats.isSymbolicLink()) return stepThroughLink(state, entry, stats, rest, trust); + return standIn(entry, rest, trust, state.hops); +} + +/** + * One hop. The link is judged where it physically stands: inside a directory others may add entries to, + * only a link this user or root owns, held by the sticky bit, is theirs to keep. Its target's components + * then enter the queue, because the kernel steps into them next. + */ +function stepThroughLink( + state: WalkState, + link: string, + stats: fs.Stats, + rest: readonly string[], + trust: ScriptDestinationTrust, +): WalkStep { + const exposure = untrustedLinkExposure({ uid: stats.uid }, state.authority, trust); + if (exposure) return { kind: 'reject', path: link, exposure }; + if (state.hops >= MAX_SCRIPT_PATH_LINK_HOPS) { + return { kind: 'reject', path: link, exposure: 'link_loop_exceeded' }; + } + const target = fs.readlinkSync(link); + const queue = [ + ...pathComponents(path.isAbsolute(target) ? target : path.join(state.deepest, target)), + ...rest, + ]; + // An absolute target restarts the walk at the root; a relative one continues from where the walk is. + const home = path.isAbsolute(target) ? '/' : state.deepest; + return standIn(home, queue, trust, state.hops + 1); +} + +/** + * How many link targets one destination walk expands before it refuses. + * + * Kept BELOW the smallest limit the supported kernels apply to a path of their own (macOS 32, Linux 40), + * so this rule always reaches its own limit first and answers with its own typed reason. The walk counts + * hops rather than letting the kernel answer `ELOOP`, because a walk that ran out of hops has NOT + * established where the entry lands, and that is a refusal, not a pass. + */ +export const MAX_SCRIPT_PATH_LINK_HOPS = 30; + +/** + * One directory's identity on its filesystem, for a caller that must publish into the same one it + * created or checked. `undefined` when the directory is absent or is not a directory. + */ +export function publishDirectoryIdentity(directory: string): string | undefined { + if (process.platform === 'win32') return 'windows'; + const stats = statDirectoryChain(directory); + return stats ? `${stats.dev}:${stats.ino}` : undefined; +} + +/** The host files the private-group exception reads, in `/etc/group` field order. */ +type HostGroupDatabase = Readonly<{ + /** `undefined` when the file could not be read, which is not the same as a file with no records. */ + groups: readonly string[] | undefined; + passwd: readonly string[] | undefined; + /** `/etc/nsswitch.conf`, which says whether the two files above are the whole story. */ + nsswitch: readonly string[] | undefined; +}>; + +/** One `group:` or `passwd:` line of `/etc/nsswitch.conf`, or `undefined` when none was found. */ +type NsswitchLine = Readonly<{ database: string; sources: readonly string[] }>; + +/** + * Whether `/etc/nsswitch.conf` establishes that the group and passwd files are the whole story. + * + * `files` is the only source admitted. `systemd` is deliberately NOT admitted, even though it is the + * default on some distributions: `systemd-userdbd` answers group membership from user records the two + * files never see, which is exactly the member this rule could not read. Bracketed actions such as + * `[NOTFOUND=return]` steer a lookup and add no source, so they are ignored. A missing line, an + * unparseable line, or an unreadable file establishes nothing, and the exception is refused. + */ +export function nameServiceListsOnlyFiles(nsswitch: readonly string[] | undefined): boolean { + if (nsswitch === undefined) return false; + for (const database of ['passwd', 'group']) { + const line = nsswitchLine(nsswitch, database); + if (line === undefined) return false; + if (!line.sources.every((source) => source === 'files')) return false; + if (line.sources.length === 0) return false; + } + return true; +} + +function nsswitchLine(lines: readonly string[], database: string): NsswitchLine | undefined { + for (const raw of lines) { + const source = (raw.split('#')[0] ?? '').trimStart(); + const [name, ...rest] = source.split(/[\s:]+/); + if (name !== database) continue; + // A bracketed action steers a lookup and lists no source. + const sources = rest.filter((token) => token.length > 0 && !token.startsWith('[')); + return { database, sources }; + } + return undefined; +} + +/** One `/etc/group` record. A line without a numeric gid cannot be used to judge membership. */ +type GroupRecord = Readonly<{ name: string; gid: number; members: readonly string[] }>; + +/** One `/etc/passwd` record. */ +type PasswdRecord = Readonly<{ name: string; uid: number; gid: number }>; + +function parseGroupRecord(line: string): GroupRecord | undefined { + const [name, , rawGid, rawMembers = ''] = line.split(':'); + const gid = Number(rawGid); + if (name === undefined || name === '' || rawGid === '' || !Number.isInteger(gid)) + return undefined; + return { name, gid, members: rawMembers.split(',').filter((member) => member.length > 0) }; +} + +function parsePasswdRecord(line: string): PasswdRecord | undefined { + const [name, , rawUid, rawGid] = line.split(':'); + if (name === undefined || name === '') return undefined; + return { name, uid: Number(rawUid), gid: Number(rawGid) }; +} + +/** This process's own account: the uid and primary gid the kernel reports, and the name it maps to. */ +type CurrentAccount = Readonly<{ + uid: number | undefined; + gid: number | undefined; + name: string | undefined; +}>; + +/** + * The single group the private-group exception admits, or `undefined` when nothing was established. + * + * Ubuntu and Debian create one group per user, named after them, and set up that user's home directory + * with it, often group-writable and owned by that user. Such a home is shared with no other local user, + * so it stays a valid script destination. Every other group stays outside the exception, and the rule + * fails closed wherever completeness cannot be established: + * + * - `/etc/nsswitch.conf` must exist, be readable, and name `files` as the ONLY source for both `passwd` + * and `group`. Otherwise a name service could hold a member no file shows, and nothing here could see + * it. {@link nameServiceListsOnlyFiles} says what a name service may say. + * - Both database files must have been READ. An unreadable file is not an empty one, and an empty + * member list proves nothing. + * - The gid must be the one this process holds as its PRIMARY group, which `getgid` answers from the + * kernel rather than from a file, and at least one record carrying that gid must bear this user's name. + * - EVERY record carrying that gid is read, because a directory group-writable by gid 1000 is writable + * by the members of each group holding the number, however they are named: `ada:x:1000:` beside + * `team:x:1000:grace` reaches grace. Any of them naming a member who is neither this user nor root + * ends the claim, without lookup or forgiveness — macOS lists only part of `staff` in `/etc/group` + * while every local user holds it. + * - No other passwd record may hold this gid as its primary group, and the caller's own record must + * exist there with this uid and this gid. + */ +export function privateGroupId( + database: HostGroupDatabase, + current: CurrentAccount, +): number | undefined { + if (!nameServiceListsOnlyFiles(database.nsswitch)) return undefined; + const records = parseHostGroupDatabase(database); + if (records === undefined) return undefined; + return admittedPrivateGid(records, current); +} + +/** The host's two databases, parsed, or `undefined` when either file could not be read. */ +type HostAccounts = Readonly<{ + groups: readonly GroupRecord[]; + passwd: readonly PasswdRecord[]; +}>; + +function parseHostGroupDatabase(database: HostGroupDatabase): HostAccounts | undefined { + if (!database.groups || !database.passwd) return undefined; + return { + groups: database.groups.flatMap((line) => { + const record = parseGroupRecord(line); + return record === undefined ? [] : [record]; + }), + passwd: database.passwd.flatMap((line) => { + const record = parsePasswdRecord(line); + return record === undefined ? [] : [record]; + }), + }; +} + +/** The decision the parsed databases allow: this gid, when it is the caller's own private group. */ +function admittedPrivateGid(accounts: HostAccounts, current: CurrentAccount): number | undefined { + const { uid, gid, name } = current; + if (uid === undefined || gid === undefined || name === undefined) return undefined; + const own = accounts.passwd.find((record) => record.name === name); + if (own === undefined || own.uid !== uid || own.gid !== gid) return undefined; + const carrying = accounts.groups.filter((record) => record.gid === gid); + if (!carrying.some((record) => record.name === name)) return undefined; + // EVERY record carrying this gid decides together: a directory group-writable by gid 1000 is writable + // by the members of each of them, however they are named. + const reachesAnybodyElse = carrying.some((record) => + record.members.some((member) => !memberIsTrusted(member, accounts, name)), + ); + if (reachesAnybodyElse) return undefined; + const sharesPrimary = accounts.passwd.some( + (record) => record.name !== name && record.gid === gid && record.uid !== 0, + ); + return sharesPrimary ? undefined : gid; +} + +/** Whether a member of a candidate private group is the user or root, the two accounts the rule trusts. */ +function memberIsTrusted(member: string, accounts: HostAccounts, name: string): boolean { + if (member === name) return true; + const record = accounts.passwd.find((other) => other.name === member); + return record !== undefined && record.uid === 0; +} + +/** + * The account name this process's uid maps to, read from the host account database. The name comes from + * the same file the group records come from, so a caller standing in for that file and this name stays in + * agreement. No `os.userInfo()`: that answers from a different source than the records being judged. + */ +function readCurrentUser( + passwd: readonly string[] | undefined, + uid: number | undefined, +): string | undefined { + if (passwd === undefined || uid === undefined) return undefined; + for (const line of passwd) { + const record = parsePasswdRecord(line); + if (record?.uid === uid) return record.name; + } + return undefined; +} + +/** This process's identity and the private group its host databases establish, if any. */ +function readScriptTrust(): ScriptDestinationTrust { + const passwd = readSystemFile('/etc/passwd'); + const uid = process.getuid?.(); + return { + uid: uid ?? -1, + privateGid: privateGroupId( + { + groups: readSystemFile('/etc/group'), + passwd, + nsswitch: readSystemFile(NSSWITCH_FILE), + }, + { uid, gid: process.getgid?.(), name: readCurrentUser(passwd, uid) }, + ), + }; +} + +/** The file that says which sources the host looks in for accounts and groups. */ +const NSSWITCH_FILE = '/etc/nsswitch.conf'; + +/** + * The ways a step of the walk can be unsafe: somebody else can change what is in that directory, they + * can create the entry the destination names, they can put the link there, or the step cannot be trusted + * at all. + * + * `foreign_owned` — some other user owns it and can chmod, empty, or repopulate it whatever its mode. + * `world_writable` / `shared_group_writable` — its mode opens its contents to others. + * `shared_parent` — nobody else can change what is in it today, but they can add the missing entry. + * `planted_link` — a symbolic link another user could have put in place of a directory, or could replace. + * `link_loop_exceeded` — the walk expanded as many links as the kernel allows, so where it lands is not + * established. A loop is refused, never trusted. + * `not_a_directory` — a step of the path is something a publish cannot travel through. + * `parent_replaced` — the directory the caller staged against is not the one it was. + */ +export type ScriptAncestryExposure = + | 'foreign_owned' + | 'world_writable' + | 'shared_group_writable' + | 'shared_parent' + | 'planted_link' + | 'link_loop_exceeded' + | 'not_a_directory' + | 'parent_replaced'; + +/** What this process can rely on when it judges a directory: its identity and its private group. */ +export type ScriptDestinationTrust = Readonly<{ + uid: number; + privateGid: number | undefined; +}>; + +/** The fields of a directory the ancestry rule reads, so the decision is testable without a filesystem. */ +export type DirectoryAuthority = Readonly<{ uid: number; gid: number; mode: number }>; + +/** + * Whether this directory is one this user can rely on a destination being inside of, and why not if it + * is not. + * + * Ownership is asked first: a directory another user owns is theirs to chmod, to empty, and to + * repopulate whatever its mode says today, and no race is needed to do it. Then the mode, because + * group- or other-writable contents are open to those users directly. The sticky bit is the one mode + * exception, and it is sound only for PASSING THROUGH a directory: it stops anyone but an entry's owner + * or root from removing or replacing that entry, so the entries already on the path hold. It cannot + * refuse a NEW entry by name, so {@link othersCreateEntriesIn} is asked separately before anything is + * created inside. + */ +export function untrustedAncestryExposure( + directory: DirectoryAuthority, + trust: ScriptDestinationTrust, +): ScriptAncestryExposure | undefined { + if (directory.uid !== 0 && directory.uid !== trust.uid) return 'foreign_owned'; + if (directory.mode & 0o1000) return undefined; + if (directory.mode & 0o002) return 'world_writable'; + if (directory.mode & 0o020 && directory.gid !== trust.privateGid) return 'shared_group_writable'; + return undefined; +} + +/** + * Whether other local users can add an entry here, which is how the destination's own name, or a + * directory below it, becomes theirs. + * + * A directory somebody else owns counts: they can create, rename, or replace any entry in it whatever + * its mode says, sticky bit included, since both of those protect other people's entries from them, not + * their own. The sticky bit is otherwise deliberately not consulted here — it cannot refuse a NEW entry + * by name. + */ +export function othersCreateEntriesIn( + directory: DirectoryAuthority, + trust: ScriptDestinationTrust, +): boolean { + if (directory.uid !== 0 && directory.uid !== trust.uid) return true; + if (directory.mode & 0o002) return true; + return Boolean(directory.mode & 0o020) && directory.gid !== trust.privateGid; +} + +/** The fields of a symbolic link the ancestry rule reads. */ +export type LinkAuthority = Readonly<{ uid: number }>; + +/** + * Whether a symbolic link on the path is one another local user could have put there, or could replace, + * and whose target is therefore theirs to choose. + * + * Where nobody but this user or root can add entries, a link cannot appear or change behind this rule. + * Where others CAN add entries, the sticky bit is the only thing holding an existing entry in place: it + * stops anyone but the entry's owner or root from unlinking and replacing it, so a link this user or root + * owns stands, and one anybody else owns does not — it may be theirs, and without the sticky bit any of + * them can swap it for one pointing wherever they like. + * + * A component the path steps back over with `..` is asked as a directory rather than as a link: there + * the caller is not publishing through it, only walking across it, and the directory it lands in is + * judged on its own. + */ +export function untrustedLinkExposure( + link: LinkAuthority, + home: DirectoryAuthority, + trust: ScriptDestinationTrust, +): ScriptAncestryExposure | undefined { + if (!othersCreateEntriesIn(home, trust)) return undefined; + if (home.mode & 0o1000 && (link.uid === 0 || link.uid === trust.uid)) return undefined; + return 'planted_link'; +} + +function scriptAncestryFailure( + destination: string, + ancestor: string, + exposure: ScriptAncestryExposure, +): AppError { + const replaced = exposure === 'parent_replaced'; + return new AppError( + 'COMMAND_FAILED', + replaced + ? `The directory for ${destination} changed while the script was staged, so the script was not saved.` + : `Refusing to save the script under ${ancestor}: another local user owns or can write that part of the path.`, + { + reason: replaced ? 'script_ancestry_replaced' : 'script_ancestor_untrusted', + exposure, + path: destination, + ancestor, + hint: replaced + ? 'Re-record with open --save-script, or save under a directory nobody else can write.' + : 'Save the script under a directory you own that only you can write, and keep the path out of directories other users own.', + }, + ); +} + +function readSystemFile(file: string): string[] | undefined { + try { + return fs.readFileSync(file, 'utf8').split('\n'); + } catch { + return undefined; + } +} + +/** `lstat` where absence is `undefined`; any other failure propagates. */ +function lstatIfPresentSync(pathname: string): fs.Stats | undefined { + try { + return fs.lstatSync(pathname); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } +} + +/** `stat` of the directory a path names, or `undefined` when it is absent or is not a directory. */ +function statDirectoryChain(pathname: string): fs.Stats | undefined { + let stats: fs.Stats | undefined; + try { + stats = fs.statSync(pathname); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } + return stats.isDirectory() ? stats : undefined; +} function assertSafeDestination(destination: string): void { const stats = lstatIfPresent(destination); if (stats?.isSymbolicLink()) { diff --git a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts index 8fe6668d8d..7a7a6305ad 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts @@ -6,10 +6,12 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonArtifact, DaemonResponse } from '@agent-device/kernel/contracts'; import * as file from '@agent-device/host-kit/file'; import { + FOREIGN_UID, closeLoopbackServer, createTestHostEnvironment, listenOnLoopback, mkdtempForTestSync, + serveHostOwnership, } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; @@ -465,6 +467,286 @@ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([ }, ); +test.skipIf(process.platform === 'win32')( + 'a remote recording creates a missing parent in a sticky directory and publishes there', + async () => { + // `open --save-script /tmp/rec/journey.ad` with `rec` absent is the ordinary shape, and `/tmp` is + // sticky. Judging the chain before the parent exists asks the question about `/tmp` and refuses a + // recording the local writer accepts, so the parent is created first on both routes (#4565). + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-mkdir-')); + const stateDir = path.join(root, 'state'); + const sticky = path.join(root, 'tmp'); + fs.mkdirSync(sticky); + fs.chmodSync(sticky, 0o1777); + const destination = path.join(sticky, 'recordings', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.not.objectContaining({ scriptDeliveryFailure: expect.anything() }), + }), + ); + expect(fs.readFileSync(destination, 'utf8')).toBe('open Demo\n'); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses the ground a link target crosses on the way in', + async () => { + // `rec -> /shared/relay/sub`, `shared` at 0777 and not sticky, `shared/relay -> /chosen`. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-target-')); + const stateDir = path.join(root, 'state'); + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(shared, 'relay')); + const sub = path.join(chosen, 'sub'); + fs.mkdirSync(sub); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + fs.symlinkSync(path.join(shared, 'relay', 'sub'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(sub)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a link another local user owns on the way in', + async () => { + // `~/rec -> /tmp/relay -> ~/chosen`, `relay` another user's file in a sticky shared directory. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-hopowner-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + const tmp = path.join(root, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + const relay = path.join(tmp, 'relay'); + fs.symlinkSync(chosen, relay); + fs.symlinkSync(relay, path.join(home, 'rec')); + serveHostOwnership({ [relay]: FOREIGN_UID }); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(chosen)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses the directory a .. steps back into', + async () => { + // `home/work -> priv/x`, `priv/y` at 0777: the write lands in `priv/y`, not in the `home/y` the + // normalized spelling names. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-dotdot-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const priv = path.join(root, 'priv'); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX, { recursive: true }); + const privY = path.join(priv, 'y'); + fs.mkdirSync(privY); + fs.chmodSync(privY, 0o777); + fs.symlinkSync(privX, path.join(home, 'work')); + const destination = `${home}/work/../y/journey.ad`; + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(privY)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a private link standing on shared ground two levels up', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-traverse-')); + const stateDir = path.join(root, 'state'); + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const mine = path.join(shared, 'mine'); + fs.mkdirSync(mine); + fs.chmodSync(mine, 0o700); + const privateWork = path.join(root, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + const destination = path.join(mine, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.readdirSync(privateWork)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a chain that leaves a shared directory through a link', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-relay-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const team = path.join(root, 'srv', 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.readdirSync(chosen)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32').each([ + { + name: 'a symbolic link planted where the script should land', + plant: (root: string) => { + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const attacker = path.join(root, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + return { + destination: path.join(shared, 'work', 'journey.ad'), + untouched: attacker, + }; + }, + }, + { + name: 'a world-writable directory', + plant: (root: string) => { + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + return { destination: path.join(shared, 'journey.ad'), untouched: shared }; + }, + }, +])('a remote recording refuses a destination under $name', async ({ plant }) => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-')); + const stateDir = path.join(root, 'state'); + const { destination, untouched } = plant(root); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.existsSync(destination)).toBe(false); + expect(fs.readdirSync(untouched)).toEqual([]); +}); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a destination whose directory was swapped while the version downloaded', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-')); + const stateDir = path.join(root, 'state'); + const work = path.join(root, 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + const realOpen = fs.promises.open.bind(fs.promises); + // The replacement is a private directory, so only the parent's identity can catch it. The swap + // happens once the staged file is open: after the parent's identity was captured. + const spyOpen = vi.spyOn(fs.promises, 'open').mockImplementation(async (file, ...rest) => { + const handle = await realOpen(file as never, ...(rest as unknown as never[])); + fs.rmSync(work, { recursive: true, force: true }); + fs.mkdirSync(work); + return handle; + }); + + let response: DaemonResponse; + try { + response = (await open(baseUrl, stateDir, destination)).response; + } finally { + spyOpen.mockRestore(); + } + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestry_replaced' }), + }), + }), + ); + expect(fs.readdirSync(work)).toEqual([]); + }, +); + test('retiring a record removes the staging a crashed download left behind', async () => { const { stateDir, destination } = journey(); const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); diff --git a/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index a91c1bca70..6b79ac0a5d 100644 --- a/packages/remote/src/session-script-destination.ts +++ b/packages/remote/src/session-script-destination.ts @@ -8,9 +8,16 @@ import type { ScriptDeliveryFailure, } from '@agent-device/kernel/contracts'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; +import { AppError } from '@agent-device/kernel/errors'; import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; +import { + acquireProcessLock, + assertPrivateScriptDestination, + publishDirectoryIdentity, + publishFileSync, + withProcessLock, +} from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import type { DaemonArtifactEndpoint, downloadRemoteArtifact } from './daemon-artifacts.ts'; @@ -191,13 +198,18 @@ async function publishScriptVersion( return { published: undefined }; } if ((revision as number) <= record.revision) return { published: record.destination }; - const directory = path.dirname(record.destination); const pending = { named: false }; let staging: string | undefined; try { - await fs.promises.mkdir(directory, { recursive: true }); - staging = await withRecordLock(file, async () => allocateStaging(file, directory)); - if (!staging) return { published: undefined }; + // The missing parent is created first, so this route judges the chain at the same point the local + // writer does: the rule needs the directory the entry is really created in, which does not exist + // until this line has run (#4565). + await fs.promises.mkdir(path.dirname(record.destination), { recursive: true }); + const allocated = await withRecordLock(file, async () => + allocateStaging(file, record.destination), + ); + staging = allocated?.staging; + if (!staging || !allocated) return { published: undefined }; const staged = path.join(staging, 'script.ad'); await context.download({ ...endpoint, @@ -206,7 +218,13 @@ async function publishScriptVersion( requestScope: req.meta, privateFile: { maxBytes: MAX_SCRIPT_BYTES }, }); - const version = { revision: revision as number, staging, staged, pending }; + const version = { + revision: revision as number, + staging, + staged, + parentIdentity: allocated.parentIdentity, + pending, + }; return { published: await withRecordLock(file, async () => publishStaged(file, version)) }; } catch (error) { const closing = req.command === 'close'; @@ -223,18 +241,29 @@ async function publishScriptVersion( } } -/** Creates a staging directory and lists it in the record before any script bytes reach it. */ -function allocateStaging(file: string, directory: string): string | undefined { +/** + * Creates a staging directory beside the destination and lists it in the record before any script + * bytes reach it, and reports the destination directory's identity so the publish can confirm it is + * still the same one. Refuses an ancestor another local user can write (#4565), so nothing is + * downloaded into a directory they control. + */ +function allocateStaging( + file: string, + destination: string, +): { staging: string; parentIdentity: string | undefined } | undefined { const record = readRecord(file); if (!record) return undefined; + assertPrivateScriptDestination(destination); + const directory = path.dirname(destination); const staging = fs.mkdtempSync(path.join(directory, '.agent-device-script-')); + const parentIdentity = publishDirectoryIdentity(directory); try { writeRecord(file, { ...record, staging: [...(record.staging ?? []), staging] }); } catch (error) { fs.rmSync(staging, { recursive: true, force: true }); throw error; } - return staging; + return { staging, parentIdentity }; } /** @@ -275,10 +304,11 @@ function publishStaged( revision: number; staging: string; staged: string; + parentIdentity: string | undefined; pending: { named: boolean }; }>, ): string | undefined { - const { revision, staging, staged, pending } = version; + const { revision, staging, staged, parentIdentity, pending } = version; const record = readRecord(file); if (!record) return undefined; let current = settlePublishing(record); @@ -289,6 +319,9 @@ function publishStaged( current = withoutStaging(current, record.publishing.staging); } if (revision <= current.revision) return current.destination; + // Re-asked here, under the record lock and right before the entry is created: whoever could write + // an ancestor while the version was downloaded cannot move it now (#4565). + assertPrivateScriptDestination(current.destination, parentIdentity); const publishing = { revision, file: fileIdentity(staged) ?? 'missing', staging }; // A second name keeps the inode on disk after the rename while the record may name it. fs.linkSync(staged, `${staged}.anchor`); @@ -329,6 +362,19 @@ function scriptDeliveryFailure( ): ScriptDeliveryFailure { // Only the exclusive link of the first version can find an existing entry. const exists = (error as NodeJS.ErrnoException | undefined)?.code === 'EEXIST'; + const refusal = scriptAncestryRefusal(error); + if (refusal) { + return { + reason: 'script_delivery_failed', + cause: refusal, + publicationId, + message: + error instanceof AppError + ? error.message + : `The remote script could not be saved to ${destination}.`, + hint: error instanceof AppError ? (error.details?.hint ?? '') : '', + }; + } const recovery = closing ? 'The session is closed, so no later version follows.' : 'The next recorded action or close delivers the full recording again.'; @@ -349,6 +395,18 @@ function scriptDeliveryFailure( }; } +/** + * The typed reason a destination-ancestry refusal reported (#4565), so a caller can tell an unsafe + * destination from a download that failed. Anything else is `undefined`. + */ +function scriptAncestryRefusal(error: unknown): string | undefined { + if (!(error instanceof AppError)) return undefined; + const reason = error.details?.reason; + return reason === 'script_ancestor_untrusted' || reason === 'script_ancestry_replaced' + ? reason + : undefined; +} + function recordPath( stateDir: string, baseUrl: string, diff --git a/packages/test-kit/src/host-ownership.fixtures.ts b/packages/test-kit/src/host-ownership.fixtures.ts new file mode 100644 index 0000000000..ae945c1966 --- /dev/null +++ b/packages/test-kit/src/host-ownership.fixtures.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs'; +import { vi } from 'vitest'; + +/** Some other local user: not the one running the suite, and not root. */ +export const FOREIGN_UID = 65534; + +/** + * Reports the ids in `owners` for the paths named there, and the real host for every other path, so an + * ownership rule is decided by the fixture rather than by the account the suite happens to run under. + * + * Only the ids move: modes and inode numbers stay what they are on disk. A real foreign owner needs + * privileges a test does not have — an unprivileged process cannot `chown` to another uid — and moving + * the CALLER's uid instead decides the test by which directories the scratch tree happens to sit under. + */ +export function serveHostOwnership(owners: Readonly>): void { + const realLstat = fs.lstatSync.bind(fs); + const realStat = fs.statSync.bind(fs); + const reuid = (stats: fs.Stats, pathname: string): fs.Stats => { + const uid = owners[pathname]; + if (uid === undefined || stats.uid === uid) return stats; + return Object.assign(Object.create(Object.getPrototypeOf(stats)), stats, { uid }) as fs.Stats; + }; + vi.spyOn(fs, 'lstatSync').mockImplementation(((pathname: never, ...rest: never[]) => + reuid(realLstat(pathname, ...rest), String(pathname))) as typeof fs.lstatSync); + vi.spyOn(fs, 'statSync').mockImplementation(((pathname: never, ...rest: never[]) => + reuid(realStat(pathname, ...rest), String(pathname))) as typeof fs.statSync); +} diff --git a/packages/test-kit/src/index.ts b/packages/test-kit/src/index.ts index 5d74593d59..fbd6c01e3e 100644 --- a/packages/test-kit/src/index.ts +++ b/packages/test-kit/src/index.ts @@ -122,6 +122,7 @@ export { unavailableDeploymentSnapshotAndShutdownOperationFacts, } from './runtime-operation-facts.ts'; export { createTestRuntimeStateHandle, type TestRuntimeStateHandle } from './runtime-state.ts'; +export { FOREIGN_UID, serveHostOwnership } from './host-ownership.fixtures.ts'; export { buildNodes } from './snapshot-builders.ts'; export { bottomTabsRealCaptureFixture, diff --git a/test/wire-compat/closure-policy.ts b/test/wire-compat/closure-policy.ts index 84a93c1a70..5e1533e455 100644 --- a/test/wire-compat/closure-policy.ts +++ b/test/wire-compat/closure-policy.ts @@ -49,6 +49,8 @@ export const WIRE_CLOSURE_WAIVERS: Readonly> = { 'Server-side narrowing of the listed kernel DaemonRequest; the declaration that fixes the shape is packages/kernel/src/contracts.ts#DaemonRequest.', 'packages/contracts/src/daemon-wire-request.ts#DaemonWireRequest': 'Client-side narrowing of the listed kernel DaemonRequest (token and session required, flags typed as CommandFlags); the declaration that fixes the shape is packages/kernel/src/contracts.ts#DaemonRequest.', + 'packages/remote/src/session-script-destination.ts#PublishOutcome': + "The CLIENT'S OWN result of one publish attempt: the published path, or a failure plus the local error object behind it. Only the failure half is ever serialized, into `data.scriptDeliveryFailure`, and that payload is the listed packages/kernel/src/contracts.ts#ScriptDeliveryFailure; the `error` member is a local unknown thrown value that never reaches the peer.", 'packages/remote/src/upload-stream.ts#UploadStreamProgressOptions': 'Byte-progress callback options for local upload rendering. The bytes counted are digested through the request/response declarations; these options never cross the wire.', 'packages/remote/src/upload-progress.ts#UploadProgressSink': diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 0eba21ea2f..64bb24943c 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -33,6 +33,7 @@ "packages/kernel/src/contracts.ts#RESPONSE_LEVELS": "sha256:cef29c3b56c299e35a7fee8058b90dc4a6f65a46a420e4f11f77c8ca7d0359c8", "packages/kernel/src/contracts.ts#ResponseCost": "sha256:2a44de54e8b5c886b36da1500e22d634ec7e12961d2c93b689d2b1aa8c15f186", "packages/kernel/src/contracts.ts#ResponseLevel": "sha256:c7329d28e745b5e69b86aa1a686befa314b98248afbe5e0e2d7d395f0d777f9b", + "packages/kernel/src/contracts.ts#ScriptDeliveryFailure": "sha256:186881f8b2e6a0227a6d1a2c802d8f7356fee39d4137800a0c9fa65401aa2765", "packages/kernel/src/contracts.ts#SESSION_ISOLATION_MODES": "sha256:3d4b3048e22bb0ceccc98cf8fd93a87a1a1e2dad96fa03cffff6d0ecedb58689", "packages/kernel/src/contracts.ts#SessionIsolationMode": "sha256:beea941fe57b000902da28af15a27aa18d0c957408209e3ec372fcf7f605fa7c", "packages/kernel/src/contracts.ts#SESSION_RUNTIME_PLATFORMS": "sha256:6164fc8ca226b5beb3ba52a8dddd3c11633a8accec58b9f8972c44c8339a1bf7", @@ -213,7 +214,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:42d78f01311e3e0c5f9099ef72e3c6258241e66204747aa176a55cd5191a2145", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", - "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:9d6ceb538019c0ce30813fcf98d2484c5abc2d8fd7a3dfdd4141cf6430f086ff", + "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:cc3b263e1a19cb76256217395f81f54e4fffa6a5755693e1efef1e5e931d50f6", "packages/remote/src/session-script-destination.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:10ab07a6f276c7b03996c6b46fa218e03e7b1d21e2c95df5515dfb88095416b6", "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15" diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 2cfffa7015..aae60264a0 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -108,6 +108,11 @@ Outside a macOS app lease, a fresh `open --save-script=` records the sessi your machine. Each response that records an action returns a `session-script` artifact, and the client replaces the file with it. `close` returns the final script. The client writes only to the path that its own `open` named. If the file already exists, `open` fails unless you pass `--force`. +Every directory the write travels through must be one that no other local user can change; see +[Record a replay script](replay-e2e.md#record-a-replay-script). That check reads owners, permission +bits and link shape on your machine, so an access control list, a network mount, or a mount that +appears over a checked directory is outside it: the file is written at mode `0600`, but that is not +a promise that nobody else can read it. Choose a directory only you can write. The daemon must report the `script-artifacts` capability in its `/health` response; through a proxy, the upstream daemon's health response must report it. Otherwise `open --save-script` is refused before the session starts. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 5a96d58ea4..15139a6863 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -70,7 +70,13 @@ To choose the output file, pass a path to `--save-script`: agent-device open Settings --platform ios --session e2e --save-script ./workflows/e2e-settings.ad ``` -- Missing parent directories are created. +- Missing parent directories are created. The script file is created at mode `0600`, so its own permissions open it to nobody but you. What those permissions do not settle for you is listed under the limits below. +- Every directory the write travels through must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. +- The check follows the path the way the system does, one name at a time, and judges every directory it looks a name up in. So a plain directory that is open to others cannot hide a link into a private destination (`rec -> shared/relay/sub`, where `shared/relay` is itself a link), and a link inside a link cannot hide the directory it crosses. A `..` is applied to the directory the walk actually reached, not to the text you typed: where `work` is a link, `work/../x` lands beside the link's target, and that is the directory judged. Following more links than the system allows is refused rather than trusted. +- Every symbolic link the path follows is checked wherever it leads, at any depth, not only the ones you typed. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Its own permission bits are not consulted: on Linux every link reports the same mode. Root-owned system links such as macOS `/tmp` and `/var` keep working. +- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories, and only where `/etc/nsswitch.conf` shows that `/etc/group` and `/etc/passwd` are the whole story: a name service could hold a member those files never show. Every group carrying that group number is considered, so a second group with the same number that lists somebody else closes this exception. +- Limits. The checks read owners, permission bits and link shape, and three things sit outside them. An access control list is consulted before the permission bits, so a directory at `0700` can still grant everyone write through an ACL, and a file at `0600` can still grant everyone read; the checks do not read ACLs. On a network mount (NFS, SMB, FUSE), ownership and mode are whatever the server answers, and the user ids there are usually not the ones on this machine. A mount can also appear over a checked directory. So these checks mean that no other local user can steer where the recording is written on a local filesystem without ACLs on that path; they are not a promise that nobody else can read the file. On a host like that, choose a directory only you can write. +- A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choose a directory you own that only you can write. - With a local daemon, the script is written on the daemon host when the session closes. - With a remote daemon, outside a macOS app lease, the path is on your machine. The file appears when `open` returns, and each later recorded action in the session replaces it with the recording so far. `close` writes the final script there. A session that another process closes keeps the version from the last action. - A bare remote `open --save-script` writes `recording-.ad` in your working directory.