diff --git a/BUILD-LOG.md b/BUILD-LOG.md index 9defb4b0f..62cc1d22e 100644 --- a/BUILD-LOG.md +++ b/BUILD-LOG.md @@ -5342,3 +5342,5 @@ Gander: after Duckworth-0100 design approval with C1-C5, prepared the two host-s 2026-10-22T17:42:16Z | Sage | Row 253 (#1758, Gander, Duckworth) LANDED 48e450ce8. Before: refactor at aca16404c; case-sudo calls had no supervised session check and the M21 survivor hid behind a fast-exit fixture (mos-1297). After: a fast-forward of 22 commits; manifest 591020a1 rechecked with 0 mismatches; run 5 whole gate green with M1-M40 killed, the M38 PID equals SID assertion added under mos-1298; Duckworth APPROVE rev 3252, note rev 3253, done rev 3254; #1758 comment 30701 and closed; P19 416 comment 719. N1 (fast child reported as exit 85) is DEFERRED as Vikunja 532. 2026-10-22T18:11:57Z | Sage | Row 275 (#1780, Morgana, Duckworth) LANDED 3410df7c3. Before: refactor at 48e450ce8; viewers had no verb list of their own and board reads were not refused to users. After: a fast-forward of 3 commits; manifest 39847b15 (4 paths) blobs match; gate 17:52:12Z-18:05:00Z green (whole files 7/22/6, bus 834, cli 861, harness 151, business 231, seat 167, 10 scripts with 3 named skips), M6 and M10 killed; Duckworth APPROVE rev 3260 (comment 30717); note and done by sage-2897; #1780 comment 30728 and closed. N1 (board refusal test as a loop over BOARD_VERBS) is non-blocking. + +2026-10-22 18:11:58 UTC | Gander row276 #1781 prepared, gate pending | Before: row253 left5legacy Case1 AS_USER calls unsupervised across sudo pty sessions. After: candidate uses its unchanged supervisor with per-call inner/outer budgets, separate streams, strict display-only failure trailer, fake-only paired process-model cases and15unique mutants. Duckworth0182 B1 corrected the plan before product code;0183 cleared build. Parse-only Bash checks pass; no Node, behavioral test, host, unit or config action. Runtime gate and publication await Sage. diff --git a/docs/plans/DEFERRED.md b/docs/plans/DEFERRED.md index 5e2dff5ff..c0e2519f1 100644 --- a/docs/plans/DEFERRED.md +++ b/docs/plans/DEFERRED.md @@ -607,3 +607,12 @@ Brief: docs/plans/2026-10-22_case-sudo-legacy-followup.md, “Brief: supervised case1-accept.sh's legacy timeout330 around AS_USER talk and its AS_USER precheck, Claude version, PM launches and Node version diagnostics predate the new socket metadata/probe helpers. sudo's pty monitor can move them to a separate session; the old outer timeout does not prove their descendants are killed. The C4 repair in row253 covers only its new config query and peer probe. These legacy paths need the reviewed supervisor or a header explicitly explaining why each remains unsupervised. The follow-up must preserve the 300-second talk/reply contract, concurrent F5 scan, diagnostics and secret-output refusals, with fake-only session-hop tests and Sage's slot. No host or live unit change is authorized. Row 276 / #1781 also owns the case1 root-side capture/tools mutant counterparts (duckworth-0112 N1) and documenting the setuid-member cleanup refusal in the headers (N2). A member that changes uid and cannot be killed causes inner-cleanup refusal, never successful observation. N4 is addressed in row253 by allowing SID confirmation until the existing inner watchdog expires, instead of a separate 200 ms scheduling margin. + + +## Row276 candidate closure of Row253 F5 + +Effective when row276 / #1781 lands after Duckworth review and Sage's gate: all five legacy Case1 calls (F3 talk, F4 precheck, F6 Claude version, F7 PM launches, F10 Node version) use row253's byte-identical after-uid supervisor and their own independent outer bound. No named AS_USER exception remains. Talk retains --wait300 and concurrent F5 observation; stdout and stderr remain separate, with root retaining only stderr's last65536bytes. A trailer can choose only a failure display number, never success. Supervisor0 alone permits pass. + +Row253 N1 closure: row276's M10 checks case1's root-owned/non-writable tool fence through both capture and legacy paths; M11 checks case1's root-side capture byte limit. Each must be killed in the accepted gate. Row253 N2 closure: both case-script headers explicitly state that a uid-changing member which cannot be killed causes inner-cleanup refusal, never successful observation. + +The hostile same-uid setsid-away or killed/stalled-supervisor residual remains as row253 R3. This closes none of that boundary. Instant command exit before SID confirmation remains the fail-closed residual tracked as Vikunja532 (mos-1297); row276 does not change the pinned payload. diff --git a/packages/cli/tests/case-sudo-fixture.mjs b/packages/cli/tests/case-sudo-fixture.mjs index 179bc35ef..866c6c0d2 100644 --- a/packages/cli/tests/case-sudo-fixture.mjs +++ b/packages/cli/tests/case-sudo-fixture.mjs @@ -10,7 +10,8 @@ case_sudo_entry() { here="$BASHPID" read -r sid < <(/bin/ps -o sid= -p "$here") printf "%s %s\n" "$here" "$sid" >> "$record/session-pids" - if { [ -f "$record/stall-config" ] && [[ "$*" == *MOSAIC_TESTER_SOCKET_V1* ]]; } || + if { [ -f "$record/stall-legacy-precheck" ] && [[ "$*" == *MOSAIC_LEGACY_STATUS* ]]; } || + { [ -f "$record/stall-config" ] && [[ "$*" == *MOSAIC_TESTER_SOCKET_V1* ]]; } || { [ -f "$record/stall-probe" ] && [[ "$*" == *SO_PEERCRED* ]]; }; then trap '' TERM HUP [ ! -f "$record/stall-output" ] || /bin/cat "$record/stall-output" @@ -140,3 +141,12 @@ ${kind==='member'?`const c=spawn('/usr/bin/python3',['-I','-S','-c',${JSON.strin Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0); }`; } + +// Row276: production budgets include the existing conversation/precheck bounds. +export const LEGACY_CASES = Object.freeze([ + {tag:'talk',inner:320,outer:330,check:'F3'}, + {tag:'precheck',inner:200,outer:210,check:'F4'}, + {tag:'claude-version',inner:5,outer:7,check:'F6'}, + {tag:'pm-list',inner:10,outer:12,check:'F7'}, + {tag:'node-version',inner:5,outer:7,check:'F10'}, +]); diff --git a/packages/cli/tests/case1-accept.test.mjs b/packages/cli/tests/case1-accept.test.mjs index b2673c325..700011e74 100644 --- a/packages/cli/tests/case1-accept.test.mjs +++ b/packages/cli/tests/case1-accept.test.mjs @@ -5,13 +5,14 @@ // sudo runs the stack's user's commands from the tree. Nothing here reads or writes the real /etc, // /proc or /srv, and the stand-in credential is not a credential. import { test } from "node:test"; +import { createHash } from "node:crypto"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { tmp } from "./helpers.mjs"; -import { CASE_SUDO_SESSION, recordedLivePids, killRecordedPids, fixtureGuard, cleanupFixture, pollFixtureGone, blockingQuerySource } from "./case-sudo-fixture.mjs"; +import { CASE_SUDO_SESSION, recordedLivePids, killRecordedPids, fixtureGuard, cleanupFixture, pollFixtureGone, blockingQuerySource, LEGACY_CASES } from "./case-sudo-fixture.mjs"; const REPO = fileURLToPath(new URL("../../../", import.meta.url)); const SCRIPT = join(REPO, "scripts", "case1-accept.sh"); @@ -68,6 +69,7 @@ esac`, // -l -U USER prints the state file; -u jarvis is the bwrap probe; -u mosaic -H env PATH=... CMD runs // CMD from the tree, with the PATH entries and each absolute argument that exists there moved under it. sudo: `${CASE_SUDO_SESSION} +/usr/bin/python3 -I -S -c 'import json,os,sys;f=open(os.environ["HC"]+"/sudo-argv.jsonl","a");f.write(json.dumps(sys.argv[1:])+chr(10));f.close()' "$@" case "$1" in -l) [ -f "$HC/sudo-l-$3" ] && cat "$HC/sudo-l-$3"; exit 0 ;; -u) ;; @@ -721,7 +723,26 @@ test("row 195 accept: every in-instance call goes through sudo -u mosaic -H env for(const a of isolated) assert.ok(a.startsWith(`-u mosaic -H env -i HOME=${HOME} PATH=/opt/mosaic-stack/node-${NODE_PIN}/bin:/usr/local/bin:/usr/bin:/bin `),a); for (const a of asMosaic.filter(a=>!isolated.includes(a))) assert.ok(a.startsWith(`${AS_MOSAIC} /`), a); const cmds = asMosaic.filter(a=>!isolated.includes(a)).map((a) => a.slice(AS_MOSAIC.length + 1).split(" ")[0]); - assert.deepEqual([...new Set(cmds)].sort(), [CLI, PRECHECK, CLAUDE, NODE].sort()); + assert.equal(asMosaic.length,7,'two metadata/probe calls and five legacy calls'); + assert.deepEqual([...new Set(cmds)].sort(), ['/usr/bin/bash']); + // mos-1326: assert every argv element, not flattened/substr command detection. + const source=read(SCRIPT); + const supervisor=source.split("<<'MOSAIC_TESTER_SUPERVISOR'")[1].split('\n').slice(1).join('\n').split('\nMOSAIC_TESTER_SUPERVISOR')[0]+'\n'; + assert.equal(createHash('sha256').update(supervisor).digest('hex'),'17b881513c35107e26f78c3722bc4a2927d206b197597be0bdbb2c8a8588bb4c'); + const runner=/LEGACY_COMMAND_RUNNER='([\s\S]*?)'\nlegacy_display_rc/.exec(source)[1]; + const f7=/F7_JS='([\s\S]*?)';\ncheck_f7/.exec(source)[1]; + const raw=read(join(h.hc,'sudo-argv.jsonl')).trim().split('\n').map(line=>JSON.parse(line)); + const legacy=raw.filter(a=>a[0]==='-u'&&a[1]==='mosaic'&&a[4].startsWith('PATH=')); + const marker=legacy[0][20].split(':')[0]; + const argv=(tag,inner,command)=>['-u','mosaic','-H','env',`PATH=/opt/mosaic-stack/node-${NODE_PIN}/bin:/usr/local/bin:/usr/bin:/bin`, + '/usr/bin/bash','-c',supervisor,'--',String(inner),'/usr/bin/setsid','/usr/bin/sleep',NODE,'-e',runner,'--',tag,...command]; + assert.deepEqual(legacy,[ + argv('talk',320,[CLI,'talk','chief',marker+': this is the Case 1 acceptance; reply with one short line.','--business','mosaic-stack','--tester','--wait','300']), + argv('precheck',200,[PRECHECK,'--business','mosaic-stack','--profile','factory']), + argv('claude-version',5,[CLAUDE,'--version']), + argv('pm-list',10,[NODE,'-e',f7,'--',`${HOME}/.config/mosaic-dev/businesses/mosaic-stack.json`,CLI,'mosaic-stack']), + argv('node-version',5,[NODE,'--version']), + ]); assert.deepEqual(sudo.filter((a) => !a.startsWith("-u mosaic")).sort(), ["-l -U localadmin", "-l -U mosaic", "-u jarvis /usr/bin/bwrap --version"]); const talk = calls(h, "mosaic").filter((a) => a.startsWith("talk ")); @@ -735,3 +756,107 @@ test("row 195 accept: the host check runs with --check and never --enforce", (t) run(h); assert.deepEqual(calls(h, "hostcheck"), ["--check"]); }); + + +// Row276 exercises the real legacy launcher with fixture-only commands, never sudo. +function legacyBody() { + const source=read(SCRIPT),start=source.indexOf('# row253-supervisor-begin'),end=source.indexOf('# row276-legacy-end'); + assert.ok(start>=0&&end>start,'legacy supervisor block exists'); + return source.slice(start,end); +} +function legacyCall(h,tag,command,{inner='0.5',outer='2',body=legacyBody()}={}) { + return spawnSync('/bin/bash',['-c',body+'\nlegacy_run "$@"','--',tag,String(inner),String(outer),...command],{ + encoding:'utf8',env:{...process.env,PATH:`${h.bin}:${process.env.PATH}`,HC:h.hc,ROOT_DIR:h.root,REAL_NODE:process.execPath,TMPDIR:h.dir, + S_USER:'mosaic',S_HOME:'/srv/mosaic',NODE,WORK:h.dir}, + }); +} +test('row276 legacy call inventory pins every production bound and the conversation contract',()=>{ + const s=read(SCRIPT); + assert.equal(s.includes('${AS_USER[@]}'),false); + for(const x of LEGACY_CASES)assert.ok(s.includes(`legacy_run ${x.tag} ${x.inner} ${x.outer} `),x.tag); + assert.match(s,/legacy_run talk 320 330 .*--tester --wait 300/); + assert.match(s,/legacy_display_rc talk/);assert.match(s,/legacy_display_rc precheck/); +}); +for(const {tag} of LEGACY_CASES)test(`row276 ${tag} legacy inner timeout cleans both sudo models`,async t=>{ + for(const mode of ['exec','hop']){ + const h=host(t),records=join(h.hc,'legacy-pids'),files=[join(h.hc,'session-pids'),records]; + put(join(h.hc,'session-mode'),mode); + const file=join(h.dir,'blocked.mjs');put(file,blockingQuerySource(records,'signals')+'\nloadSystem();'); + const capture=cleanupFixture(t,files),stop=fixtureGuard(t,files,4500); + const start=performance.now(),r=legacyCall(h,tag,[NODE,file]);capture(); + assert.equal(r.status,81,r.stdout+r.stderr); + assert.equal(r.stderr,`case1-accept: ${tag} inner-timeout\n`); + assert.ok((performance.now()-start)/1000<2,mode); + assert.deepEqual(await pollFixtureGone(files),[],mode);await stop(); + } +}); +test('row276 legacy streams and display status preserve failures without granting success',t=>{ + for(const mode of ['exec','hop'])for(const code of [0,1,7,81,137]){ + const h=host(t);put(join(h.hc,'session-mode'),mode); + const r=legacyCall(h,'talk',[NODE,'-e',`process.stdout.write('sent retained\\nreply retained\\n');process.stderr.write('original diagnostic\\n');process.exitCode=${code}`],{inner:3,outer:5}); + assert.equal(r.status,code===0?0:87,r.stderr); + assert.equal(r.stdout,'sent retained\nreply retained\n');assert.equal(r.stderr,'original diagnostic\n'); + assert.equal(read(join(h.dir,'legacy-talk.rc')),String(code===0?0:code)+'\n'); + } +}); +test('row276 trailer grammar cannot make supervisor failure pass',t=>{ + for(const trailer of ['0','256','999','01','+1','-1','1-no-newline','missing']){ + const h=host(t),body=legacyBody().replace('process.stderr.write("\\nMOSAIC_LEGACY_STATUS="+code+"\\n");', + trailer==='missing'?'':trailer==='1-no-newline'?'process.stderr.write("\\nMOSAIC_LEGACY_STATUS=1");':`process.stderr.write("\\nMOSAIC_LEGACY_STATUS=${trailer}\\n");`); + assert.notEqual(body,legacyBody(),'runner trailer seam matched'); + const r=legacyCall(h,'talk',[NODE,'-e','process.exitCode=7'],{body,inner:3,outer:5}); + assert.equal(r.status,87,r.stderr);assert.equal(read(join(h.dir,'legacy-talk.rc')),'87\n'); + assert.ok(r.stderr.endsWith('case1-accept: talk inner-command\n'),r.stderr); + } +}); +test('row276 earlier forged trailer and appended zero remain failures',t=>{ + for(const late of [false,true]){ + const h=host(t);let body=legacyBody(); + if(late)body=body.replace('process.stderr.write("\\nMOSAIC_LEGACY_STATUS="+code+"\\n");','process.stderr.write("\\nMOSAIC_LEGACY_STATUS="+code+"\\nMOSAIC_LEGACY_STATUS=0\\n");'); + const r=legacyCall(h,'talk',[NODE,'-e','process.stderr.write("\\nMOSAIC_LEGACY_STATUS=0\\n");process.exitCode=7'],{body,inner:3,outer:5}); + assert.equal(r.status,87,r.stderr);assert.equal(read(join(h.dir,'legacy-talk.rc')),late?'87\n':'7\n'); + } +}); +test('row276 precheck outer bound discards success status and fixture cleans residual',async t=>{ + for(const mode of ['exec','hop']){ + const h=host(t),files=[join(h.hc,'session-pids')];put(join(h.hc,'session-mode'),mode);put(join(h.hc,'stall-legacy-precheck'),''); + const capture=cleanupFixture(t,files),stop=fixtureGuard(t,files,4500); + const start=performance.now(),r=legacyCall(h,'precheck',[NODE,'-e',''],{inner:0.5,outer:1});capture();const seconds=(performance.now()-start)/1000; + assert.equal(r.status,82,r.stderr);assert.equal(r.stderr,'case1-accept: precheck outer-timeout\n');assert.equal(r.stdout,''); + assert.ok(seconds>=1&&seconds<3,`${mode}:${seconds}s`);assert.equal(read(join(h.dir,'legacy-precheck.rc')),'82\n'); + killRecordedPids(files[0]);assert.deepEqual(await pollFixtureGone(files),[],'explicit same-uid stalled-supervisor residual cleanup');await stop(); + } +}); +test('row276 case1 capture and legacy tools refuse unsafe system tools',t=>{ + for(const legacy of [false,true]){ + const h=host(t),statFile=join(h.bin,'stat');edit(statFile,s=>s.replace('case "${@: -1}" in',`case "\${@: -1}" in\n /usr/bin/timeout) echo '0 777';exit 0 ;;`)); + const body=legacyBody(); + const r=legacy?legacyCall(h,'node-version',[NODE,'--version'],{body}):spawnSync('/bin/bash',['-c',body+'\ntester_capture 0.5 2 128 mosaic /srv/mosaic /usr/bin /usr/bin/true'],{encoding:'utf8',env:{...process.env,PATH:`${h.bin}:${process.env.PATH}`,HC:h.hc,ROOT_DIR:h.root,REAL_NODE:process.execPath,TMPDIR:h.dir}}); + assert.equal(r.status,84,r.stdout+r.stderr);if(legacy)assert.equal(r.stderr,'case1-accept: node-version supervisor-tools\n'); + } +}); + + +test('row276 stderr retention is bounded and keeps the final diagnostic',t=>{ + const h=host(t),r=legacyCall(h,'talk',[NODE,'-e',"process.stderr.write('X'.repeat(70000)+'end diagnostic\\n')"],{inner:3,outer:5}); + assert.equal(r.status,0,r.stderr);assert.ok(Buffer.byteLength(r.stderr)<=65536);assert.ok(r.stderr.endsWith('end diagnostic\n')); +}); +test('row276 version and PM checks refuse successful-looking stdout on supervisor failure',t=>{ + const source=read(SCRIPT),h=host(t); + for(const [name,next,output] of [['check_f6','// The PM check',`${CLAUDE_PIN} (Claude Code)`],['check_f7','check_f8()', 'ok pm run r-0002'],['check_f10','check_f11()',NODE_PIN]]){ + const at=source.indexOf(name+'()'),end=source.indexOf(next,at+1);assert.ok(at>=0&&end>at); + const code=source.slice(at,end)+'\nfpass(){ echo PASS; }; ffail(){ echo FAIL; }; tester_capture_reason(){ echo inner-command; }; legacy_run(){ printf "%s\n" "$OUTPUT"; return 87; }; '+name; + const r=spawnSync('/bin/bash',['-c',code],{encoding:'utf8',env:{...process.env,CLAUDE,CLAUDE_PIN,NODE,NODE_PIN,WORK:h.dir,OUTPUT:output,BUSINESS_FILE:'/fake',COPY:'/fake',BUSINESS:'mosaic-stack'}}); + assert.equal(r.status,0,r.stderr);assert.equal(r.stdout,'FAIL\n',name); + } +}); + + +test('row276 full acceptance keeps all five healthy calls in both sudo models',async t=>{ + for(const mode of ['exec','hop']){ + const h=host(t),files=[join(h.hc,'session-pids')];put(join(h.hc,'session-mode'),mode); + const capture=cleanupFixture(t,files),r=run(h);capture(); + assert.equal(r.status,0,r.out+r.err);assert.deepEqual(failed(r),[],mode); + assert.deepEqual(await pollFixtureGone(files),[],mode); + } +}); diff --git a/scripts/case1-accept.sh b/scripts/case1-accept.sh index 8130ca6d7..5ab553b91 100755 --- a/scripts/case1-accept.sh +++ b/scripts/case1-accept.sh @@ -18,8 +18,12 @@ # fixed system Python, also as the stack user, for a read-only SO_PEERCRED observation. # The config/probe supervisor is fixed root-validated system Bash plus setsid # and sleep, after the uid drop: query inner/outer 5/7 s, probe 2/4 s. Root -# independently bounds its sudo wait. Legacy AS_USER talk and diagnostics below -# retain their old behavior and are NOT covered by this supervisor (F5 follow-up). +# independently bounds its sudo wait. All legacy calls use the same payload: +# talk320/330 s (conversation --wait300), precheck200/210 s (its Claude probe180), +# Claude/Node versions5/7 s, PM launches10/12 s. Stderr retains its last65536bytes, +# stdout streams to the original caller. Supervisor0 alone permits success. +# A member that changes uid and cannot be killed refuses inner-cleanup; hostile +# same-uid setsid-away or a killed/stalled supervisor remains the R3 residual. # # One line per check, ` `, then `count N` for each mark and a # result line. F checks are `pass` or `FAIL`. P checks are `closed`, `accepted ` or @@ -107,8 +111,8 @@ BUS_UNIT="mosaic-bus@$BUSINESS.service" CON_UNIT=mosaic-webui.service HOSTCHECK=/usr/local/lib/mosaic-stack/hostcheck.sh SETTINGS=/etc/claude-code/managed-settings.json LABEL_OUTER='bwrap (enforce)' LABEL_CHILD='bwrap//&unpriv_bwrap (enforce)' -AS_USER=(sudo -u "$S_USER" -H env "PATH=$(dirname "$NODE"):/usr/local/bin:/usr/bin:/bin") WORK="$(mktemp -d)" || refuse "cannot make a temp dir" +chmod 700 "$WORK" || refuse "cannot protect temp dir" trap 'rm -rf -- "$WORK"' EXIT # Row253: bounded unprivileged metadata, parsed by root without running copy code. @@ -196,8 +200,8 @@ MOSAIC_TESTER_SUPERVISOR tester_tools() { local input target p st magic - TS_BASH="" TS_SETSID="" TS_SLEEP="" TS_TIMEOUT="" TS_HEAD="" - for input in /bin/bash /usr/bin/setsid /usr/bin/sleep /usr/bin/timeout /usr/bin/head; do + TS_BASH="" TS_SETSID="" TS_SLEEP="" TS_TIMEOUT="" TS_HEAD="" TS_TAIL="" + for input in /bin/bash /usr/bin/setsid /usr/bin/sleep /usr/bin/timeout /usr/bin/head "$@"; do target="$(realpath -e -- "$input" 2>/dev/null)" || return 1 case "$target" in /home/*|/root/*|/run/user/*) return 1 ;; esac [ -f "$target" ] && [ -x "$target" ] && [ ! -L "$target" ] || return 1 @@ -213,7 +217,7 @@ tester_tools() { case "$input" in /bin/bash) TS_BASH="$target" ;; /usr/bin/setsid) TS_SETSID="$target" ;; /usr/bin/sleep) TS_SLEEP="$target" ;; /usr/bin/timeout) TS_TIMEOUT="$target" ;; - /usr/bin/head) TS_HEAD="$target" ;; + /usr/bin/head) TS_HEAD="$target" ;; /usr/bin/tail) TS_TAIL="$target" ;; esac done } @@ -246,6 +250,68 @@ tester_capture() ( cat -- "$file" ) + +# row276-legacy-begin +# The runner preserves a failed command's display code. Its exit status, not +# this dropped-uid trailer, controls supervisor success. Root reads only a tail. +LEGACY_COMMAND_RUNNER=' +const {spawnSync}=require("node:child_process"); +const {constants}=require("node:os"); +const [tag,command,...args]=process.argv.slice(1); +const r=spawnSync(command,args,{stdio:"inherit"}); +const code=Number.isInteger(r.status)?r.status:r.signal?128+(constants.signals[r.signal]??0):127; +if(r.error)process.stderr.write("legacy command "+(r.error.code??"failed")+"\n"); +process.stderr.write("\nMOSAIC_LEGACY_STATUS="+code+"\n"); +process.exitCode=code; +' +legacy_display_rc() { + local tag="$1" fallback="$2" value="" + [ ! -f "$WORK/legacy-$tag.rc" ] || value="$(<"$WORK/legacy-$tag.rc")" + if [[ "$value" =~ ^[1-9][0-9]{0,2}$ ]] && [ "$value" -le 255 ]; then printf '%s' "$value" + else printf '%s' "$fallback"; fi +} +legacy_run() ( + local tag="$1" inner="$2" outer="$3" notice errors child="" rc=0 raw suffix display=87 valid=0; shift 3 + # WORK is root's private mktemp directory. The dropped uid cannot write it. + printf '%s\n' 84 > "$WORK/legacy-$tag.rc" + tester_tools /usr/bin/tail || { printf 'case1-accept: %s supervisor-tools\n' "$tag" >&2; exit 84; } + notice="$(mktemp "$WORK/legacy-notice.XXXXXX")" || exit 88 + errors="$(mktemp "$WORK/legacy-stderr.XXXXXX")" || { rm -f -- "$notice"; exit 88; } + trap 'if [ -n "$child" ]; then kill -KILL -- "-$child" 2>/dev/null || :; wait "$child" 2>/dev/null || :; fi; rm -f -- "$notice" "$errors"' EXIT + trap 'exit 88' HUP INT TERM + LC_ALL=C "$TS_TIMEOUT" --verbose --signal=KILL "${outer}s" "$TS_BASH" -c ' + errors="$1"; shift + exec "$@" 2> "$errors" + ' -- "$errors" sudo -u "$S_USER" -H env "PATH=$(dirname "$NODE"):/usr/local/bin:/usr/bin:/bin" "$TS_BASH" -c "$TESTER_SUPERVISOR" -- "$inner" "$TS_SETSID" "$TS_SLEEP" "$NODE" -e "$LEGACY_COMMAND_RUNNER" -- "$tag" "$@" 2> "$notice" & + child=$! + wait "$child" 2>/dev/null || rc=$? + kill -KILL -- "-$child" 2>/dev/null || : + if [ "$rc" = 137 ] && [[ "$(<"$notice")" == *': sending signal KILL to command '* ]]; then rc=82; fi + # Sentinel retains the terminal newline through command substitution. + raw="$("$TS_TAIL" -c 65536 -- "$errors" && printf .)" || { raw=""; rc=88; } + raw="${raw%.}" + suffix=$'\nMOSAIC_LEGACY_STATUS=' + if [[ "$raw" =~ $'\nMOSAIC_LEGACY_STATUS='(0|[1-9][0-9]{0,2})$'\n'$ ]] && [ "${BASH_REMATCH[1]}" -le 255 ]; then + display="${BASH_REMATCH[1]}"; valid=1 + raw="${raw%"$suffix"*}" + fi + printf '%s' "$raw" >&2 + if [ "$rc" = 0 ]; then + printf '%s\n' 0 > "$WORK/legacy-$tag.rc" + exit 0 + fi + if [ "$rc" = 87 ] && [ "$valid" = 1 ] && [ "$display" -gt 0 ]; then + printf '%s\n' "$display" > "$WORK/legacy-$tag.rc" + exit 87 + fi + case "$rc" in 81|82|84|85|86|88) ;; *) rc=87 ;; esac + printf '%s\n' "$rc" > "$WORK/legacy-$tag.rc" + if [ -n "$raw" ] && [[ "$raw" != *$'\n' ]]; then printf '\n' >&2; fi + printf 'case1-accept: %s %s\n' "$tag" "$(tester_capture_reason "$rc")" >&2 + exit "$rc" +) +# row276-legacy-end + TESTER_QUERY='import {readFileSync} from "node:fs";import {pathToFileURL} from "node:url";const m=await import(pathToFileURL(process.argv[1]).href);const s=m.loadSystem();console.log(JSON.stringify({dataRoot:s.dataRoot,socket:readFileSync(process.argv[2],"utf8").includes("MOSAIC_TESTER_SOCKET_V1")}));' tester_facts() { local LC_ALL=C pattern='^\{"dataRoot":"([A-Za-z0-9/._@+-]+)","socket":(true|false)\}$' @@ -425,10 +491,10 @@ scan_f5() { # F3 and F5 together: the message goes out in the background and the scan runs until it is answered. check_f3_f5() { - local marker text rc=0 out err n tpid + local marker text rc=0 shown out err n tpid marker="case1-accept-$(od -An -N6 -tx1 /dev/urandom | tr -d ' \n')" text="$marker: this is the Case 1 acceptance; reply with one short line." - timeout 330 "${AS_USER[@]}" "$COPY/scripts/mosaic" talk chief "$text" --business "$BUSINESS" --tester --wait 300 > "$WORK/talk.out" 2> "$WORK/talk.err" & + legacy_run talk 320 330 "$COPY/scripts/mosaic" talk chief "$text" --business "$BUSINESS" --tester --wait 300 > "$WORK/talk.out" 2> "$WORK/talk.err" & tpid=$! while :; do scan_f5 && break @@ -442,24 +508,27 @@ check_f3_f5() { if [ "$rc" = 0 ] && grep -q "^sent [^ ]* to chief" <<< "$out" && [ "$n" -ge 2 ]; then fpass F3 tester-reply "chief replied to $marker" else - ffail F3 tester-reply "talk exited $rc with $n lines on stdout; last: $(clean "$(tail -n 1 <<< "${err:-$out}")")" + shown="$(legacy_display_rc talk "$rc")" + ffail F3 tester-reply "talk exited $shown with $n lines on stdout; last: $(clean "$(tail -n 1 <<< "${err:-$out}")")" fi if [ -n "$F5_OK" ]; then F5_LINE=(fpass "$F5_OK"); else F5_LINE=(ffail "$F5_WHY"); fi } check_f4() { - local rc=0 out - out="$("${AS_USER[@]}" "$COPY/scripts/case2-precheck.sh" --business "$BUSINESS" --profile factory 2>&1)" || rc=$? + local rc=0 shown out + out="$(legacy_run precheck 200 210 "$COPY/scripts/case2-precheck.sh" --business "$BUSINESS" --profile factory 2>&1)" || rc=$? if [ "$rc" = 0 ]; then fpass F4 precheck "case2-precheck.sh --profile factory exits 0" - else ffail F4 precheck "case2-precheck.sh --profile factory exited $rc; last: $(clean "$(tail -n 1 <<< "$out")")"; fi + else shown="$(legacy_display_rc precheck "$rc")"; ffail F4 precheck "case2-precheck.sh --profile factory exited $shown; last: $(clean "$(tail -n 1 <<< "$out")")"; fi } check_f6() { - local want="/opt/mosaic-stack/claude-$CLAUDE_PIN/" v + local want="/opt/mosaic-stack/claude-$CLAUDE_PIN/" v rc=0 [[ "$CLAUDE" == "$want"* ]] || { ffail F6 claude-pin "--claude $CLAUDE is not under $want"; return; } [[ "$CLAUDE/" != */../* ]] || { ffail F6 claude-pin "--claude $CLAUDE has a .. segment"; return; } - v="$("${AS_USER[@]}" "$CLAUDE" --version 2>/dev/null | sed -n 1p)" - if [ "$v" = "$CLAUDE_PIN (Claude Code)" ]; then fpass F6 claude-pin "$CLAUDE prints '$v'" + v="$(legacy_run claude-version 5 7 "$CLAUDE" --version 2> "$WORK/claude-version.err")" || rc=$? + v="$(sed -n 1p <<< "$v")" + if [ "$rc" = 0 ] && [ "$v" = "$CLAUDE_PIN (Claude Code)" ]; then fpass F6 claude-pin "$CLAUDE prints '$v'" + elif [ "$rc" != 0 ]; then ffail F6 claude-pin "claude-version $(tester_capture_reason "$rc"); last: $(clean "$(tail -c 200 "$WORK/claude-version.err")")" else ffail F6 claude-pin "$CLAUDE --version prints '$(clean "$v")', not '$CLAUDE_PIN (Claude Code)'"; fi } @@ -477,9 +546,11 @@ let l;try{l=JSON.parse(r.stdout)}catch{console.log("fail launches list printed n const live=Array.isArray(l)?l.filter((x)=>x&&x.instance===by&&x.live===true):[]; console.log(live.length!==1?`fail ${live.length} live launches of ${by}`:live[0].business!==b?`fail the live launch of ${by} is for ${live[0].business}`:`ok ${by} run ${live[0].run}`);' check_f7() { - local out - out="$("${AS_USER[@]}" "$NODE" -e "$F7_JS" -- "$BUSINESS_FILE" "$COPY/scripts/mosaic" "$BUSINESS" 2>/dev/null | sed -n 1p)" - if [[ "$out" =~ ^ok\ [a-z0-9][a-z0-9-]*\ run\ [A-Za-z0-9._-]+$ ]]; then fpass F7 pm-live "one live launch: ${out#ok }" + local out rc=0 + out="$(legacy_run pm-list 10 12 "$NODE" -e "$F7_JS" -- "$BUSINESS_FILE" "$COPY/scripts/mosaic" "$BUSINESS" 2> "$WORK/pm-list.err")" || rc=$? + out="$(sed -n 1p <<< "$out")" + if [ "$rc" = 0 ] && [[ "$out" =~ ^ok\ [a-z0-9][a-z0-9-]*\ run\ [A-Za-z0-9._-]+$ ]]; then fpass F7 pm-live "one live launch: ${out#ok }" + elif [ "$rc" != 0 ]; then ffail F7 pm-live "pm-list $(tester_capture_reason "$rc"); last: $(clean "$(tail -c 200 "$WORK/pm-list.err")")" else ffail F7 pm-live "$(clean "${out#fail }")"; fi } @@ -517,10 +588,12 @@ check_f9() { } check_f10() { - local want="/opt/mosaic-stack/node-$NODE_PIN/bin/node" v + local want="/opt/mosaic-stack/node-$NODE_PIN/bin/node" v rc=0 [ "$NODE" = "$want" ] || { ffail F10 node-pin "--node $NODE is not $want"; return; } - v="$("${AS_USER[@]}" "$NODE" --version 2>/dev/null | sed -n 1p)" - if [ "$v" = "$NODE_PIN" ]; then fpass F10 node-pin "$NODE prints $v" + v="$(legacy_run node-version 5 7 "$NODE" --version 2> "$WORK/node-version.err")" || rc=$? + v="$(sed -n 1p <<< "$v")" + if [ "$rc" = 0 ] && [ "$v" = "$NODE_PIN" ]; then fpass F10 node-pin "$NODE prints $v" + elif [ "$rc" != 0 ]; then ffail F10 node-pin "node-version $(tester_capture_reason "$rc"); last: $(clean "$(tail -c 200 "$WORK/node-version.err")")" else ffail F10 node-pin "$NODE --version prints '$(clean "$v")', not $NODE_PIN"; fi } diff --git a/scripts/case2-unit.sh b/scripts/case2-unit.sh index 99864196f..2a471a9ab 100755 --- a/scripts/case2-unit.sh +++ b/scripts/case2-unit.sh @@ -23,6 +23,7 @@ # # The library profile takes exactly these serve flags, each once: # --port N (1..1023) --business ID (the unit's) --public-host NAME +# A member that changes uid and cannot be killed refuses inner-cleanup, never success. # --auth-header HEADER --allow-user ID --send # --proof-header NAME --proof-file PATH # The factory profile takes --port N (1..1023) and --business ID, and an