Files
Jyotisha/tests/test_monitor_alerts_2348.py
ClaudeandClaude Opus 5.5 89efc3a7cf
Independent Staging Quality Gate / validate-python (push) Successful in 5m1s
Independent Staging Quality Gate / validate-frontend (push) Failing after 19m45s
Independent Staging Quality Gate / publish (push) Skipped
fix(ops): process alert ignores seconds-old processes; release flow reads production's real revision and says why it stops (BUG-2437, BUG-2438)
- ops-check reads etimes; only processes alive >= 120 s count as CPU-hot; ps/ss/next-server allowlisted.
  Miner-name and pool-port checks unchanged.
- migrate/deploy-production print why they stop when the web container has no GITHUB_SHA.
- ship-release compares migrations against production's running SHA (unknown = migrate), so a rerun
  after a failed migration no longer skips it. README: manual container recreate must carry GITHUB_SHA.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-27 14:21:58 +08:00

493 lines
23 KiB
Python

"""BUG-2348: alert channels, low-volume signals, host checks, installer. Fixtures are fictional."""
from __future__ import annotations
import json
import os
import subprocess
import sys
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from tests.test_beta_safety_net import (
BASH,
DIGEST_SCRIPT,
HEALTH_SCRIPT,
ROOT,
HealthHandler,
HookHandler,
alert_lines,
bash_path,
run_bash,
serve,
uuid,
write_text,
)
MONITOR = ROOT / "deploy" / "monitor"
OPS_SCRIPT = MONITOR / "ops-check.sh"
INSTALL_SCRIPT = MONITOR / "install-production-monitor.sh"
PROBE_WORKFLOW = ROOT / ".gitea" / "workflows" / "monitor-public-health.yml"
FAKE_KEY = "re_fixture_key_should_not_leak"
class ResendHandler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
self.server.requests.append((self.path, dict(self.headers), body))
status = int(getattr(self.server, "status", 200))
reply = json.dumps({"id": "email_fixture"} if status == 200 else {"message": "no"}).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(reply)))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(reply)
def log_message(self, format: str, *args: object) -> None: # noqa: A002
return
def monitor_env(tmp_path: Path, lines: list[str]) -> Path:
env_file = tmp_path / "monitor.env"
write_text(env_file, "".join(f"{line}\n" for line in lines))
os.chmod(env_file, 0o600)
return env_file
def app_env(tmp_path: Path) -> Path:
path = tmp_path / "app.env"
write_text(path, f'RESEND_API_KEY="{FAKE_KEY}"\nRESEND_FROM_EMAIL=Jyotisha <alerts@example.test>\nOTHER_SECRET=nope\n')
return path
def three_health_failures(env: dict[str, str]) -> subprocess.CompletedProcess[str]:
result = None
for _ in range(3):
result = run_bash(HEALTH_SCRIPT, env, ["--mode", "health"])
assert result is not None
return result
def test_email_channel_sends_readable_chinese_alert_without_leaking_the_key(tmp_path: Path) -> None:
resend, _thread = serve(ResendHandler)
resend.requests = []
health, _thread = serve(HealthHandler)
health.kind = "500"
state = tmp_path / "state"
env_file = monitor_env(tmp_path, ["ALERT_EMAIL_TO=owner@example.test"])
env = {
"JYOTISHA_MONITOR_STATE_DIR": bash_path(state),
"JYOTISHA_MONITOR_ENV": bash_path(env_file),
"JYOTISHA_APP_ENV_FILE": bash_path(app_env(tmp_path)),
"JYOTISHA_RESEND_URL": f"http://127.0.0.1:{resend.server_address[1]}/emails",
"JYOTISHA_HEALTH_URL": f"http://127.0.0.1:{health.server_address[1]}/health",
"JYOTISHA_HEALTH_TIMEOUT": "2",
}
try:
completed = three_health_failures(env)
assert completed.returncode == 0, completed.stderr
assert len(resend.requests) == 1
path, headers, body = resend.requests[0]
assert path == "/emails"
lowered = {key.lower(): value for key, value in headers.items()}
assert lowered["authorization"] == f"Bearer {FAKE_KEY}"
payload = json.loads(body.decode("utf-8"))
assert set(payload) == {"from", "to", "subject", "text"}
assert payload["to"] == ["owner@example.test"]
assert payload["from"] == "Jyotisha <alerts@example.test>"
assert payload["subject"] == "Jyotisha 告警:网站打不开(连续探活失败)"
assert "errorCode=health_down" in payload["text"]
assert FAKE_KEY not in payload["text"]
assert FAKE_KEY not in completed.stdout + completed.stderr
assert len(alert_lines(state)) == 1
finally:
resend.shutdown()
health.shutdown()
def test_one_accepting_channel_is_enough_and_both_receive_the_alert(tmp_path: Path) -> None:
resend, _thread = serve(ResendHandler)
resend.requests = []
hook, _thread = serve(HookHandler)
hook.bodies = []
hook.feishu_code = 19001
health, _thread = serve(HealthHandler)
health.kind = "500"
state = tmp_path / "state"
env_file = monitor_env(
tmp_path,
[f"FEISHU_WEBHOOK_URL=http://127.0.0.1:{hook.server_address[1]}/hook", "ALERT_EMAIL_TO=owner@example.test"],
)
env = {
"JYOTISHA_MONITOR_STATE_DIR": bash_path(state),
"JYOTISHA_MONITOR_ENV": bash_path(env_file),
"JYOTISHA_APP_ENV_FILE": bash_path(app_env(tmp_path)),
"JYOTISHA_RESEND_URL": f"http://127.0.0.1:{resend.server_address[1]}/emails",
"JYOTISHA_HEALTH_URL": f"http://127.0.0.1:{health.server_address[1]}/health",
"JYOTISHA_HEALTH_TIMEOUT": "2",
}
try:
completed = three_health_failures(env)
assert completed.returncode == 0, completed.stderr
assert len(hook.bodies) == 1
feishu_text = json.loads(hook.bodies[0].decode("utf-8"))["content"]["text"]
assert feishu_text.startswith("Jyotisha 生产告警")
assert "网站打不开" in feishu_text
assert len(resend.requests) == 1
assert len(alert_lines(state)) == 1
resend.status = 500
state_b = tmp_path / "state-b"
rejected = three_health_failures({**env, "JYOTISHA_MONITOR_STATE_DIR": bash_path(state_b)})
assert rejected.returncode != 0
assert alert_lines(state_b) == []
finally:
resend.shutdown()
hook.shutdown()
health.shutdown()
def run_digest(tmp_path: Path, name: str, lines: list[str]) -> list[str]:
fixture = tmp_path / f"{name}.txt"
write_text(fixture, "\n".join(lines) + "\n")
state = tmp_path / f"state-{name}"
completed = run_bash(
DIGEST_SCRIPT,
{
"JYOTISHA_MONITOR_STATE_DIR": bash_path(state),
"JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"),
"JYOTISHA_LOG_FIXTURE": bash_path(fixture),
"JYOTISHA_NOW": "2026-10-15T01:00:00Z",
},
["--window"],
)
assert completed.returncode == 0, completed.stderr
return alert_lines(state)
def signal(index: int, code: str, route: str = "/api/auth/email-otp") -> str:
return f"2026-10-15T00:00:{index:02d}Z web [ops-signal] {json.dumps({'errorCode': code, 'route': route, 'upstream': 'http_5xx'})}"
def test_low_volume_signals_have_their_own_thresholds(tmp_path: Path) -> None:
assert run_digest(tmp_path, "otp2", [signal(i, "otp_send_failed") for i in range(2)]) == []
rows = run_digest(tmp_path, "otp3", [signal(i, "otp_send_failed") for i in range(3)])
assert len(rows) == 1
assert "errorCode=otp_send_failed" in rows[0]
assert "route=/api/auth/email-otp" in rows[0]
assert "count=3" in rows[0]
spend = run_digest(tmp_path, "spend", [f"2026-10-15T00:00:01Z web [ops-signal] {json.dumps({'errorCode': 'model_spend_alert'})}"])
assert len(spend) == 1 and "errorCode=model_spend_alert" in spend[0]
provider = run_digest(
tmp_path,
"provider",
[f"2026-10-15T00:00:{i:02d}Z web [agent-observability] {json.dumps({'requestId': uuid(i), 'errorCode': 'provider_error'})}" for i in range(1, 4)],
)
assert len(provider) == 1 and "errorCode=provider_error" in provider[0]
def test_api_access_log_429_and_5xx_are_counted_without_the_query(tmp_path: Path) -> None:
limited = [
f'api-1 | 2026-10-15T00:00:{i:02d}.123Z 172.18.0.3 - - [15/Oct/2026 00:00:{i:02d}] "POST /api/chart{i % 3} HTTP/1.1" 429 -'
for i in range(10)
]
rows = run_digest(tmp_path, "429", limited)
assert len(rows) == 1
assert "errorCode=http_429" in rows[0]
assert "route=- " in rows[0]
assert "count=10" in rows[0]
assert run_digest(tmp_path, "429-few", limited[:9]) == []
failing = [
f'api-1 | 2026-10-15T00:01:{i:02d}Z 172.18.0.3 - - [15/Oct/2026 00:01:{i:02d}] "GET /api/chart?birth=1990-01-02&email=a@example.test HTTP/1.1" 500 -'
for i in range(20)
]
rows = run_digest(tmp_path, "500", failing)
joined = "\n".join(rows)
assert "errorCode=http_5xx" in joined and "count=20" in joined
assert "1990-01-02" not in joined and "example.test" not in joined
ok_lines = [f'api-1 | 2026-10-15T00:02:{i:02d}Z x - - [d] "GET /api/health HTTP/1.1" 200 -' for i in range(30)]
assert run_digest(tmp_path, "200", ok_lines) == []
FAKE_DOCKER = r"""#!/usr/bin/env bash
case "$1" in
ps) printf '%s\n' "${FAKE_IDS:-}" ;;
inspect) printf '%s\n' "${FAKE_INSPECT:-}" ;;
exec)
sql="$(cat)"
case "$sql" in
*personal_report_jobs*) printf '%s\n' "${FAKE_QUEUE_WAIT:-0}" ;;
*"count(*)"*) printf '%s\n' "${FAKE_FEEDBACK_ROW:-0|}" ;;
*"now()"*) printf '%s\n' "${FAKE_NOW:-2026-10-15T01:00:00Z}" ;;
esac
;;
esac
"""
FAKE_PS = r"""#!/usr/bin/env bash
printf '%s\n' "${FAKE_PS_OUTPUT:-}"
"""
FAKE_SS = r"""#!/usr/bin/env bash
printf '%s\n' "${FAKE_SS_OUTPUT:-}"
"""
def run_ops(tmp_path: Path, state: Path, **fake: str) -> subprocess.CompletedProcess[str]:
docker = tmp_path / "fake-docker"
if not docker.exists():
write_text(docker, FAKE_DOCKER)
os.chmod(docker, 0o755)
# BUG-2416: the host process, socket, CPU and cgroup reads are fixtures too, so
# the real machine running the tests can never add an alert.
for name, body in (("fake-ps", FAKE_PS), ("fake-ss", FAKE_SS)):
path = tmp_path / name
if not path.exists():
write_text(path, body)
os.chmod(path, 0o755)
meminfo = tmp_path / "meminfo"
available = fake.pop("available_kb", "3000000")
write_text(meminfo, f"MemTotal: 4000000 kB\nMemAvailable: {available} kB\n")
proc_stat = tmp_path / "proc-stat"
write_text(proc_stat, fake.pop("proc_stat", "cpu 100 0 100 800 0 0 0 0 0 0\n"))
env = {
"JYOTISHA_MONITOR_STATE_DIR": bash_path(state),
"JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"),
"JYOTISHA_DOCKER": bash_path(docker),
"JYOTISHA_MEMINFO": bash_path(meminfo),
"JYOTISHA_PS": bash_path(tmp_path / "fake-ps"),
"JYOTISHA_SS": bash_path(tmp_path / "fake-ss"),
"JYOTISHA_PROC_STAT": bash_path(proc_stat),
"JYOTISHA_CGROUP_ROOT": bash_path(tmp_path / "cgroup"),
**{key.upper(): value for key, value in fake.items()},
}
return run_bash(OPS_SCRIPT, env)
def test_ops_check_container_restarts_memory_queue_and_feedback(tmp_path: Path) -> None:
state = tmp_path / "state"
web = "a" * 64
api = "b" * 64
base = {
"fake_ids": f"{web[:12]}\n{api[:12]}",
"fake_inspect": f"{web} /jyotisha-production-web-1 0 false\n{api} /jyotisha-production-api-1 0 false",
}
first = run_ops(tmp_path, state, **base)
assert first.returncode == 0, first.stderr
assert alert_lines(state) == [] # first run only sets the feedback baseline
restarted = {**base, "fake_inspect": f"{web} /jyotisha-production-web-1 0 false\n{api} /jyotisha-production-api-1 2 true"}
assert run_ops(tmp_path, state, **restarted).returncode == 0
lines = alert_lines(state)
assert len(lines) == 1
assert "service=api" in lines[0] and "errorCode=container_oom" in lines[0] and "count=2" in lines[0]
assert run_ops(tmp_path, state, **restarted).returncode == 0
assert len(alert_lines(state)) == 1
assert run_ops(tmp_path, state, **restarted, fake_queue_wait="900", available_kb="200000").returncode == 0
joined = "\n".join(alert_lines(state))
assert "errorCode=report_queue_stuck" in joined and "count=900" in joined
assert "errorCode=memory_high" in joined and "count=95" in joined
count_before = len(alert_lines(state))
assert run_ops(tmp_path, state, **restarted, fake_queue_wait="900", available_kb="200000").returncode == 0
assert len(alert_lines(state)) == count_before
assert run_ops(tmp_path, state, **restarted, fake_queue_wait="5").returncode == 0
recovered = alert_lines(state)[count_before:]
assert sum("errorCode=recovered" in line for line in recovered) == 2
feedback = {**restarted, "fake_feedback_row": "2|2026-10-15T01:03:00.000000Z"}
assert run_ops(tmp_path, state, **feedback).returncode == 0
last = alert_lines(state)[-1]
assert "errorCode=feedback_new" in last and "count=2" in last and "route=/admin/feedback" in last
assert "feedback_seen=2026-10-15T01:03:00.000000Z" in (state / "ops-check.state").read_text(encoding="utf-8")
def run_install(tmp_path: Path, args: list[str], tz: str = "Asia/Shanghai") -> subprocess.CompletedProcess[str]:
base = tmp_path / "opt"
(base / "deploy").mkdir(parents=True, exist_ok=True)
target = base / "deploy" / "monitor"
if not target.exists():
target.symlink_to(MONITOR)
env = {
**os.environ,
"TZ": tz,
"JYOTISHA_MONITOR_INSTALL_ALLOW_NONROOT": "1",
"JYOTISHA_PRODUCTION_PATH": str(base),
"JYOTISHA_MONITOR_CRON_FILE": str(tmp_path / "cron.d-monitor"),
"JYOTISHA_MONITOR_STATE_DIR": str(tmp_path / "state"),
"JYOTISHA_PYTHON": sys.executable,
}
env.pop("FEISHU_WEBHOOK_URL", None)
env.pop("ALERT_EMAIL_TO", None)
return subprocess.run([BASH, str(INSTALL_SCRIPT), *args], env=env, capture_output=True, text=True, encoding="utf-8")
def test_installer_is_idempotent_and_places_the_daily_summary_at_beijing_nine(tmp_path: Path) -> None:
first = run_install(tmp_path, [])
assert first.returncode == 0, first.stderr
cron = (tmp_path / "cron.d-monitor").read_text(encoding="utf-8")
assert "* * * * * root bash" in cron and "healthcheck-alert.sh --mode all" in cron
assert "error-digest.sh --window" in cron and "ops-check.sh" in cron
assert "0 9 * * * root bash" in cron
assert "JYOTISHA_COMMIT_ALERT=off" in cron
env_file = tmp_path / "opt" / ".monitor.env"
assert env_file.exists() and (env_file.stat().st_mode & 0o777) == 0o600
write_text(env_file, "# kept\n")
os.chmod(env_file, 0o600)
again = run_install(tmp_path, [])
assert again.returncode == 0, again.stderr
assert (tmp_path / "cron.d-monitor").read_text(encoding="utf-8") == cron
assert env_file.read_text(encoding="utf-8") == "# kept\n"
utc = run_install(tmp_path, [], tz="UTC")
assert utc.returncode == 0, utc.stderr
assert "0 1 * * * root bash" in (tmp_path / "cron.d-monitor").read_text(encoding="utf-8")
def test_installer_test_alert_without_channels_stays_local(tmp_path: Path) -> None:
assert run_install(tmp_path, []).returncode == 0
test = run_install(tmp_path, ["--test-alert"])
assert test.returncode == 0, test.stderr
lines = alert_lines(tmp_path / "state")
assert len(lines) == 1 and "errorCode=monitor_test" in lines[0]
def test_off_host_probe_workflow_runs_every_five_minutes_from_main() -> None:
text = PROBE_WORKFLOW.read_text(encoding="utf-8")
# 原值: cron 每 5 分钟、timeout-minutes 5、整库浅取、cancel-in-progress false
# 新值: 每 10 分钟、timeout-minutes 3、只取两个监控脚本(镜像或 raw API,每次 20 秒上限)、新运行取消旧运行
# 原因: BUG-2389,整库浅取在 runner 上要 4-8 分钟,每次都被 5 分钟上限取消(exit code -1)并占着 runner
assert 'cron: "*/10 * * * *"' in text
assert "timeout-minutes: 3" in text
assert "cancel-in-progress: true" in text
assert "git fetch" not in text
assert "--max-time 20" in text
assert "if: gitea.ref == 'refs/heads/main'" in text
assert "runs-on: xiaoxin" in text
assert "JYOTISHA_COMMIT_ALERT=off" in text
assert "deploy/monitor/healthcheck-alert.sh --mode health" in text
for name in ("MONITOR_FEISHU_WEBHOOK_URL", "MONITOR_ALERT_EMAIL_TO", "MONITOR_RESEND_API_KEY"):
assert f"secrets.{name}" in text
assert "hook/" not in text.split("on:", 1)[1].replace("hook/<token>", "")
def test_monitor_scripts_pass_bash_n() -> None:
for script in (OPS_SCRIPT, INSTALL_SCRIPT, MONITOR / "notify-feishu.sh", MONITOR / "host-audit.sh"):
completed = subprocess.run([BASH, "-n", str(script)], capture_output=True, text=True)
assert completed.returncode == 0, completed.stderr
def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None:
"""BUG-2416: sustained host/container CPU, miner names, unknown hot processes and pool ports."""
state = tmp_path / "state"
api = "c" * 64
base = {
"fake_ids": api[:12],
"fake_inspect": f"{api} /jyotisha-production-api-1 0 false",
}
cpu_stat = tmp_path / "cgroup" / "system.slice" / f"docker-{api}.scope" / "cpu.stat"
cpu_stat.parent.mkdir(parents=True)
def run(stat_total: int, stat_idle: int, usage_usec: int, now: int, **extra: str):
write_text(cpu_stat, f"usage_usec {usage_usec}\nuser_usec 0\n")
busy = stat_total - stat_idle
return run_ops(
tmp_path, state, **base, **extra,
proc_stat=f"cpu {busy} 0 0 {stat_idle} 0 0 0 0 0 0\n",
jyotisha_now=str(now),
)
t0 = 1_800_000_000
assert run(1000, 900, 0, t0).returncode == 0 # baselines only
assert alert_lines(state) == []
# One hot interval (95 % host, 100 % of a core in the container): not yet.
assert run(2000, 950, 300_000_000, t0 + 300).returncode == 0
assert [line for line in alert_lines(state) if "cpu_high" in line] == []
# Second hot interval in a row: one alert each, then no repeats.
assert run(3000, 1000, 600_000_000, t0 + 600).returncode == 0
lines = alert_lines(state)
assert any("service=host" in line and "errorCode=cpu_high" in line for line in lines)
assert any("service=api" in line and "errorCode=container_cpu_high" in line and "count=100" in line for line in lines)
before = len(alert_lines(state))
assert run(4000, 1050, 900_000_000, t0 + 900).returncode == 0
assert len(alert_lines(state)) == before
# Quiet interval: both recover.
assert run(5000, 1950, 901_000_000, t0 + 1200).returncode == 0
assert sum("errorCode=recovered" in line for line in alert_lines(state)[before:]) == 2
# Miner by name, an unknown hot process, a pool connection; allowlisted node stays quiet.
ps_out = "\n".join([
" 101 9000 99.0 node node server.js",
" 202 30 80.0 kdevtmpfsi /tmp/kdevtmpfsi",
" 303 9000 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443",
" 404 9000 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET",
# BUG-2437: the monitor's own ps and a fresh deploy step read ~100 % in their first seconds;
# Next.js names its process 「next-server (v…)」.
" 505 0 100.0 ps ps -eo pid=,etimes=,pcpu=,comm=,args=",
" 606 5 97.0 unpigz unpigz -d -c",
" 707 9000 60.0 next-server (v16.0.0) next-server (v16.0.0)",
])
ss_out = "\n".join([
"0 0 10.0.0.5:51234 203.0.113.9:4444 users:((\"sysupdate\",pid=303,fd=7))",
"0 0 10.0.0.5:443 198.51.100.7:45700 users:((\"docker-proxy\",pid=55,fd=9))",
])
before = len(alert_lines(state))
assert run(6000, 2900, 902_000_000, t0 + 1500, fake_ps_output=ps_out, fake_ss_output=ss_out).returncode == 0
new = alert_lines(state)[before:]
joined = "\n".join(new)
assert "route=/proc/kdevtmpfsi errorCode=miner_process count=202" in joined
assert "route=/proc/worker errorCode=miner_process count=404" in joined
assert "route=/proc/sysupdate errorCode=suspicious_process count=303" in joined
assert "route=/proc/sysupdate errorCode=mining_pool_connection" not in joined # same pid already reported
assert "/proc/node" not in joined and "docker-proxy" not in joined # allowlisted / inbound
assert "/proc/ps " not in joined and "/proc/unpigz" not in joined and "/proc/next-server" not in joined # BUG-2437
assert "SECRETWALLET" not in joined and "stratum" not in joined and "pool.example" not in joined
# Still running next time: not announced again.
before = len(alert_lines(state))
assert run(7000, 3800, 903_000_000, t0 + 1800, fake_ps_output=ps_out, fake_ss_output=ss_out).returncode == 0
assert len(alert_lines(state)) == before
# A new pool connection from a fresh pid is reported.
ss_new = "0 0 10.0.0.5:51300 203.0.113.9:14444 users:((\"xm\",pid=909,fd=3))"
assert run(8000, 4700, 904_000_000, t0 + 2100, fake_ss_output=ss_new).returncode == 0
assert "route=/proc/xm errorCode=mining_pool_connection count=909" in alert_lines(state)[-1]
def test_host_audit_script_is_read_only_and_masks_secrets_2416() -> None:
script = (MONITOR / "host-audit.sh").read_text(encoding="utf-8")
for forbidden in ("rm -", "systemctl stop", "systemctl disable", "apt-get install", "kill ", "chmod ", "chown ", "sed -i", "> /etc", "useradd", "passwd"):
assert forbidden not in script, forbidden
assert "docker inspect" not in script or "Config.Env" not in script # never prints container environments
for section in ("unattended-upgrades", "fail2ban", "PermitRootLogin", "PasswordAuthentication", "/tmp", "/dev/shm", "crontab", "ss -", "last"):
assert section in script, section
def test_server_compose_hardening_2416() -> None:
"""BUG-2416: api/web unprivileged + read-only with only the writable paths they need; caddy pinned."""
import yaml # noqa: PLC0415
compose = yaml.safe_load((ROOT / "deploy" / "docker-compose.server.yml").read_text(encoding="utf-8"))
services = compose["services"]
api, web, caddy, owner = services["api"], services["web"], services["caddy"], services["api-scratch-owner"]
for service in (api, web):
assert service["read_only"] is True
assert service["cap_drop"] == ["ALL"] and "cap_add" not in service
assert "no-new-privileges:true" in service["security_opt"]
assert service["pids_limit"] > 0 and service["mem_limit"]
assert service["user"] not in ("0", "0:0", "root")
assert api["user"] == "10001:10001"
assert any(entry.startswith("/tmp:") for entry in api["tmpfs"])
assert "api_scratch:/app/scratch/local" in api["volumes"]
assert api["depends_on"]["api-scratch-owner"]["condition"] == "service_completed_successfully"
assert api["environment"]["HOME"] == "/tmp"
assert web["user"] == "1000:1000"
assert any(entry.startswith("/tmp:") for entry in web["tmpfs"])
assert any(entry.startswith("/app/frontend/.next/cache:") and "uid=1000" in entry for entry in web["tmpfs"])
# The volume handover runs as root but only with file-owner capabilities and no network.
assert owner["network_mode"] == "none" and owner["restart"] == "no"
assert set(owner["cap_add"]) <= {"CHOWN", "FOWNER", "DAC_OVERRIDE", "DAC_READ_SEARCH"}
assert "10001:10001" in " ".join(owner["entrypoint"])
assert caddy["image"].startswith("caddy:2-alpine@sha256:") and len(caddy["image"].split("@sha256:")[1]) == 64
assert caddy["cap_add"] == ["NET_BIND_SERVICE"]