Publish a complete PID acknowledgement by private temporary file and same-directory rename. Preserve unknown acknowledgement artifacts and remove only retained owned stale state. Keep malformed acknowledgement failures closed. Cover deterministic publication barriers, shared apply/monitor/qualify launch, foreign artifacts, owned replacement, and private-directory checks. This does not establish hostile root or same-UID writer no-clobber guarantees; the private mode-700 directory is the trust boundary. Co-authored-by: GPT-6 <gpt-6@openai.com>
178 lines
7.9 KiB
Python
178 lines
7.9 KiB
Python
"""Offline deterministic startup guards: python3 deploy/managed-target/check_startup_diagnostics.py."""
|
|
from pathlib import Path
|
|
import os
|
|
import stat
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
entry = (ROOT / 'managed-target-entrypoint.sh').read_text()
|
|
capture = entry[entry.index('capture_monitor_session() {'):entry.index('# Wait with a watchdog:')]
|
|
launch = entry[entry.index('launch_controller() {'):entry.index('run_cycle() {')]
|
|
fixture_launch = launch.replace(' 8<&- 9<&- &', ' 8<&- 9<&-').replace(
|
|
'monitor_ack_deadline=$(($(date +%s) + 5))', 'monitor_ack_deadline=100')
|
|
secret = 'SECRET_SENTINEL'
|
|
roles = ('managed resource-apply --resource-config', 'managed monitor', 'qualify --isolated')
|
|
|
|
# Injected empty/malformed ACKs must still fail closed, not retry the read.
|
|
for role in roles:
|
|
for scenario, diagnostic in (
|
|
('empty', 'ack=read_failed'), ('malformed', 'ack=invalid_pid'),
|
|
('wrong', 'ack=identity_mismatch'), ('session', 'launch=session_mismatch'),
|
|
('gone', 'launch=child_gone'), ('timeout', 'launch=ack_timeout'),
|
|
):
|
|
with tempfile.TemporaryDirectory(prefix='startup-diagnostics-') as tmp:
|
|
script = f'''set -eu
|
|
config_dir='{tmp}'
|
|
monitor_sid=
|
|
scenario={scenario}
|
|
date() {{ echo 100; }}
|
|
setsid() {{
|
|
case "$scenario" in
|
|
empty) : > "$config_dir/monitor-ready" ;;
|
|
malformed) echo '{secret}' > "$config_dir/monitor-ready" ;;
|
|
wrong) echo 1 > "$config_dir/monitor-ready" ;;
|
|
session) echo "$!" > "$config_dir/monitor-ready" ;;
|
|
esac
|
|
}}
|
|
kill() {{ [ "$scenario" != gone ]; }}
|
|
signal_tree() {{ :; }}
|
|
proc_identity() {{ proc_sid=1; }}
|
|
{capture}
|
|
sleep 30 & seed=$!
|
|
{fixture_launch}
|
|
code=0
|
|
launch_controller {role} '{secret}' || code=$?
|
|
[ "$code" -eq 78 ]
|
|
[ -z "$monitor_sid" ]
|
|
command kill "$seed"
|
|
wait "$seed" 2>/dev/null || true
|
|
'''
|
|
result = subprocess.run(['sh', '-c', script], capture_output=True, timeout=3)
|
|
assert result.returncode == 0, (role, scenario, result.stderr)
|
|
assert result.stderr == f'controller-startup: {diagnostic}\n'.encode(), result.stderr
|
|
assert secret.encode() not in result.stdout + result.stderr
|
|
|
|
helper = (ROOT / 'managed-target-supervision.sh').read_text()
|
|
for role in roles:
|
|
with tempfile.TemporaryDirectory(prefix='delayed-ack-') as tmp:
|
|
root = Path(tmp)
|
|
wrapper_path = root / 'wrapper.sh'
|
|
write = ' printf \'%s\\n\' "$$" > "$ack_temp" || return 1'
|
|
assert helper.count(write) == 1
|
|
wrapper_path.write_text(helper.replace(write, ''' : > "$config_dir/barrier"
|
|
while [ ! -e "$config_dir/release" ]; do sleep 0.01; done
|
|
''' + write))
|
|
real_launch = launch.replace('/opt/managed-target-supervision.sh', str(wrapper_path)).replace(
|
|
'/usr/local/bin/zapret-autotune', '/bin/true')
|
|
process = subprocess.Popen(['sh', '-c', f'''set -eu
|
|
config_dir='{tmp}'
|
|
monitor_sid=
|
|
. '{ROOT / 'managed-target-supervision.sh'}'
|
|
{capture}
|
|
{real_launch}
|
|
launch_controller {role} '{secret}'
|
|
[ "$monitor_sid" = "$monitor_pid" ]
|
|
wait "$monitor_pid"
|
|
# An owned completed launch can be replaced for the next controller.
|
|
monitor_sid=
|
|
launch_controller {role} '{secret}'
|
|
[ "$monitor_sid" = "$monitor_pid" ]
|
|
wait "$monitor_pid"
|
|
'''], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
try:
|
|
deadline = time.monotonic() + 2
|
|
while not (root / 'barrier').exists():
|
|
assert process.poll() is None
|
|
assert time.monotonic() < deadline
|
|
time.sleep(0.01)
|
|
assert not (root / 'monitor-ready').exists()
|
|
pending, = root.glob('.monitor-ready.*')
|
|
assert pending.read_bytes() == b''
|
|
assert stat.S_IMODE(pending.stat().st_mode) == 0o600
|
|
(root / 'release').touch()
|
|
stdout, stderr = process.communicate(timeout=3)
|
|
assert process.returncode == 0, stderr
|
|
assert stderr == b'controller-startup: wrapper=exec_pending\n' * 2, stderr
|
|
ready = root / 'monitor-ready'
|
|
assert ready.read_text().strip().isdigit()
|
|
assert ready.read_bytes().endswith(b'\n')
|
|
assert ready.stat().st_nlink == 1
|
|
assert ready.stat().st_uid == os.getuid()
|
|
assert stat.S_IMODE(ready.stat().st_mode) == 0o600
|
|
assert not list(root.glob('.monitor-ready.*'))
|
|
assert secret.encode() not in stdout + stderr
|
|
finally:
|
|
(root / 'release').touch()
|
|
if process.poll() is None:
|
|
process.kill()
|
|
process.communicate(timeout=3)
|
|
|
|
wrapper = helper[helper.index('if [ "${1-}" = --monitor ]; then'):helper.index('elif [ "${1-}" = --watchdog ]; then')] + '\nfi\n'
|
|
for identity, diagnostic, code in (
|
|
('return 1', 'identity_unavailable', 78),
|
|
('proc_sid=1', 'not_session_leader', 78),
|
|
('proc_sid=$$', 'exec_pending', 0),
|
|
):
|
|
with tempfile.TemporaryDirectory(prefix='wrapper-diagnostics-') as tmp:
|
|
result = subprocess.run(['sh', '-c', f'proc_identity() {{ {identity}; }}\n{wrapper}',
|
|
'fixture', '--monitor', tmp, '/bin/true', secret], capture_output=True, timeout=3)
|
|
assert result.returncode == code, result.stderr
|
|
assert result.stderr == f'controller-startup: wrapper={diagnostic}\n'.encode(), result.stderr
|
|
ready = Path(tmp) / 'monitor-ready'
|
|
assert ready.exists() == (code == 0)
|
|
assert secret.encode() not in result.stdout + result.stderr
|
|
|
|
# Both publication and parent cleanup preserve unknown artifacts, including links.
|
|
for artifact in ('file', 'symlink', 'directory'):
|
|
with tempfile.TemporaryDirectory(prefix='foreign-ack-') as tmp:
|
|
root = Path(tmp)
|
|
ready = root / 'monitor-ready'
|
|
if artifact == 'file':
|
|
ready.write_text(secret)
|
|
elif artifact == 'symlink':
|
|
ready.symlink_to(root / 'absent')
|
|
else:
|
|
ready.mkdir()
|
|
before = ready.lstat()
|
|
result = subprocess.run(['sh', '-c', f'proc_identity() {{ proc_sid=$$; }}\n{wrapper}',
|
|
'fixture', '--monitor', tmp, '/bin/true', secret], capture_output=True, timeout=3)
|
|
assert result.returncode == 78, result.stderr
|
|
assert result.stderr == b'controller-startup: wrapper=ack_publish_failed\n', result.stderr
|
|
result = subprocess.run(['sh', '-c', f'''set -eu
|
|
config_dir='{tmp}'
|
|
{launch}
|
|
launch_controller managed monitor
|
|
'''], capture_output=True, timeout=3)
|
|
assert result.returncode == 78, result.stderr
|
|
assert result.stderr == b'controller-startup: launch=ack_conflict\n', result.stderr
|
|
assert ready.lstat() == before
|
|
if artifact == 'file':
|
|
assert ready.read_text() == secret
|
|
assert not list(root.glob('.monitor-ready.*'))
|
|
|
|
with tempfile.TemporaryDirectory(prefix='replaced-ack-') as tmp:
|
|
result = subprocess.run(['sh', '-c', f'''set -eu
|
|
config_dir='{tmp}'
|
|
printf '123\n' > "$config_dir/monitor-ready"
|
|
monitor_ready_identity=$(stat -c '%d:%i:%u:%a:%h' "$config_dir/monitor-ready")
|
|
monitor_ready_pid=123
|
|
printf '{secret}' > "$config_dir/replacement"
|
|
mv "$config_dir/replacement" "$config_dir/monitor-ready"
|
|
{launch}
|
|
launch_controller managed monitor
|
|
'''], capture_output=True, timeout=3)
|
|
assert result.returncode == 78, result.stderr
|
|
assert result.stderr == b'controller-startup: launch=ack_conflict\n'
|
|
assert (Path(tmp) / 'monitor-ready').read_text() == secret
|
|
|
|
with tempfile.TemporaryDirectory(prefix='unsafe-ack-dir-') as tmp:
|
|
os.chmod(tmp, 0o755)
|
|
result = subprocess.run(['sh', '-c', f'proc_identity() {{ proc_sid=$$; }}\n{wrapper}',
|
|
'fixture', '--monitor', tmp, '/bin/true'], capture_output=True, timeout=3)
|
|
assert result.returncode == 78, result.stderr
|
|
assert result.stderr == b'controller-startup: wrapper=ack_publish_failed\n'
|
|
assert not list(Path(tmp).iterdir())
|
|
print('startup diagnostic fixtures passed (shared apply/monitor/qualify launch and atomic wrapper)')
|