From 09fa5520f26805ece71d8ad85df9552daead3740 Mon Sep 17 00:00:00 2001 From: POWERFULMOVES <142271328+POWERFULMOVES@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:38:12 -0500 Subject: [PATCH 1/3] docs(register): CLAIM fix/node-branded-bind-defaults-2026-11-27 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016aNs4rDG3Hx25i9J38nSX6 --- pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md | 1 + 1 file changed, 1 insertion(+) diff --git a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md index 668ee2dfe..44102bbb0 100644 --- a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md +++ b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md @@ -3698,3 +3698,4 @@ VILLAGE RULE: delivery delegated to a delivery-agent body; control and memory ar - `2026-11-24T13:36:51Z` RELEASE `5090-CLAUDE` branch: `fix/openroom-root-redirect-2026-11-23` · scope: DELIVERED PR #3527: PMOVES-OpenRoom gitlink 9233894 -> aec292e (fork #19 merged: absolute_redirect off). Root cause: nginx absolute redirects carried the CONTAINER port 3000 through the 5173:3000 publish mapping, so the operator's bare-root URL landed on the wrong host service. Reviewed APPROVE by code-review body with live nginx A/B on the Dockerfile image; two nits taken (topology trimmed from public comment, PR body records the implicit directory-redirect fix); lint-and-build green. 5090 rebuilt via build-svc + recreate-svc: GET / -> 301 Location: /webuiapps/ -> 200, same via the tailnet name. Awaiting checks + Control ACK + closeout merge. - `2026-11-25T07:20:02Z` NOTE `5090-CLAUDE` branch: `fix/httpx-stub-test-pollution` · scope: Scope correction for the 06:23:56Z CLAIM: the 11 semantic-cache entries the Merge Gate reported STALE at bcc2619 are NOT fixed and will NOT be dropped. Measured locally with the ratchet chunking (pytest 9.2.0, 20-file chunks of the pmoves group): the new test file shifts chunk boundaries, moving test_cache.py into chunk [4], and pmoves/tools/test_all_tts_engines.py calls sys.exit(1) at import when gradio_client is absent, so chunk [4] aborts with INTERNALERROR during collection and pytest writes a partial junit (3 sso-auth collection errors, nothing else). The ratchet reads absence as fixed. On main that chunk has never produced a test result (19 files unmeasured every run). Lane now also: guard that script so it skips under pytest, make the ratchet treat pytest exit 3 as a lost chunk (isolate per file, record an finding), and baseline what CI then surfaces, with a header note. The test_cache errors themselves are an alias gap (pmoves.services.semantic_cache is not in the services shim), separate issue to follow. - `2026-11-25T08:21:30Z` RELEASE `5090-CLAUDE` branch: `fix/httpx-stub-test-pollution` · scope: PR #3517 merged 14899a3 (closes #3510). tests (3.11) green on main again, so the standing advisory waivers stop. Also landed: the python-tests ratchet treats pytest exit 3 as a lost chunk (isolate per file, record the aborting file; a session-wide abort is one dead group), pmoves/tools/test_all_tts_engines.py skips under pytest instead of sys.exit, and chunk pmoves [4] was measured for the first time: 17 real semantic-cache failures recorded in the baseline with a header note, stale ERROR|pytest|internal dropped (151 -> 167). Alias gap behind all 28 semantic-cache findings filed as #3529. RELEASE row rides PR #3521 because the lane merged before it was filed. +- `2026-11-27T23:38:11Z` CLAIM `B850-CLAUDE (Knuckles)` branch: `fix/node-branded-bind-defaults-2026-11-27` · **TTL 48h (expires `2026-11-29T23:38:11Z`)** · scope: Node-branded bind defaults (operator go 2026-11-27). (1) Load pmoves/env.mesh-bind.local, the gitignored per-node bind overlay that port_audit already reads, as the LAST compose env file in the Makefile COMPOSE_ENV_FILES when present. (2) Flip the unreviewed wide defaults to loopback, keeping the services env.mesh-bind.example documents as deliberately mesh-default (NATS, BoTZ, publisher-discord, pmoves-ui). Targets: tensorzero-ui, openroom, presign, render-webhook, extract-worker, mcp-gateway, model-registry, the monitoring stack and open-notebook. Any node that needs them wide opts in through its own mesh-bind file. (3) The port-audit target calls a bare docker compose config with no env files, so it can never pass on a node. Make it use the Makefile compose invocation. (4) Document the overlay in env.mesh-bind.example. Code and docs only: no recreate, no env-file edits, no live change. The knuckles recreate after merge is a separate operator-gated step. From 2920781e86797e9cfae3fcf9473fcd824d20942f Mon Sep 17 00:00:00 2001 From: POWERFULMOVES <142271328+POWERFULMOVES@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:41:23 -0500 Subject: [PATCH 2/3] fix(net): load env.mesh-bind.local last into compose; port-audit resolves through $(DC) The node's gitignored env.mesh-bind.local is now appended as the LAST compose env file, so a node's bind opt-ins override every tier file. port_audit.py already reads that file as its allowlist (only exact 0.0.0.0 values count), so the two stay in step. port-audit ran a bare `docker compose config` with no env files and aborted on every node. It now pipes `$(DC) config --format json` into port_audit.py --config-json -, never writing resolved config to disk; empty or invalid input fails closed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016aNs4rDG3Hx25i9J38nSX6 --- pmoves/Makefile | 11 +++++++++ pmoves/mk/infra.mk | 11 +++++---- pmoves/tools/port_audit.py | 48 ++++++++++++++++++++++++++++++++++---- 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/pmoves/Makefile b/pmoves/Makefile index 716b35b71..b3b155a34 100644 --- a/pmoves/Makefile +++ b/pmoves/Makefile @@ -154,6 +154,17 @@ endif ifneq ("$(wildcard env.tier-supabase.urlencoded)","") COMPOSE_ENV_FILES += --env-file env.tier-supabase.urlencoded endif +# Node-branded bind overlay. Source defaults every *_BIND to 127.0.0.1 unless a +# reviewed decision made it mesh-default (see env.mesh-bind.example). A node that +# must accept traffic from another host opts in HERE, in its own gitignored +# env.mesh-bind.local -- never by editing a compose default. It MUST stay the +# LAST env file so the node's decision overrides every tier file above it. +# tools/port_audit.py reads the same file as its allowlist (only values that are +# exactly 0.0.0.0 count there), so loading it into compose keeps the two in step. +# tests/unit/test_makefile_mesh_bind_overlay.py pins the ordering. +ifneq ("$(wildcard env.mesh-bind.local)","") + COMPOSE_ENV_FILES += --env-file env.mesh-bind.local +endif # -------- Service Discovery Helper ---------- # Resolve service URL using PMOVES service discovery (hybrid support) diff --git a/pmoves/mk/infra.mk b/pmoves/mk/infra.mk index 027552809..2c982ef72 100644 --- a/pmoves/mk/infra.mk +++ b/pmoves/mk/infra.mk @@ -694,11 +694,12 @@ gpu-status: ## Show GPU VRAM usage and loaded models # ── Port Binding Security ──────────────────────────────────────────── port-audit: ## Audit Docker port bindings for unexpected 0.0.0.0 exposure @echo "=== Port Binding Security Audit ===" - @docker compose config --format json >/dev/null 2>&1 || { \ - echo "ERROR: docker compose config failed; aborting port audit."; \ - exit 1; \ - } - @$(PYTHON) tools/port_audit.py + @# Resolve through $(DC) -- the SAME env-file set (tiers + the node's + @# env.mesh-bind.local overlay, last) and stack files every `up` uses. A bare + @# `docker compose config` reads no env files, so it aborted on every node and + @# would audit binds no recreate ever produces. The JSON is piped, never + @# written to disk: resolved config carries secret values. + @$(DC) config --format json | $(PYTHON) tools/port_audit.py --config-json - @echo "=== Port audit complete ===" safe-opening-audit: ## Audit reachable surfaces for the bind->auth coupling (Safe-Activation Contract Clause 3) diff --git a/pmoves/tools/port_audit.py b/pmoves/tools/port_audit.py index 75a4390ec..57935de1c 100644 --- a/pmoves/tools/port_audit.py +++ b/pmoves/tools/port_audit.py @@ -6,9 +6,16 @@ 0.0.0.0 bindings not in the mesh allowlist. Usage: - python tools/port_audit.py # audit from pmoves/ - make -C pmoves port-audit # via Makefile + make -C pmoves port-audit # canonical: resolves via $(DC) + $(DC) config --format json | python tools/port_audit.py --config-json - + python tools/port_audit.py # bare `docker compose config` + +The bare form reads NO env files, so on a real node it either fails or audits +binds that no recreate produces. `make port-audit` pipes the config resolved +through the Makefile's $(DC) (tier env files + the node's env.mesh-bind.local +overlay, loaded last) into --config-json, so the audit sees what `up` sees. """ +import argparse import json import os import subprocess @@ -92,6 +99,28 @@ def parse_compose_config(): return None +def read_config_json(source: str): + """Read an already-resolved compose config (JSON) from a path or '-' (stdin). + + Returns None on empty or unparseable input so main() fails closed: when the + upstream `$(DC) config` fails it writes nothing to stdout, and an empty + document must never read as "no ports, all clean". + """ + try: + text = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8") + except OSError as exc: + print(f"WARNING: Could not read compose config JSON from {source}: {exc}", file=sys.stderr) + return None + if not text.strip(): + print("WARNING: compose config JSON input was empty (did `docker compose config` fail?)", file=sys.stderr) + return None + try: + return json.loads(text) + except json.JSONDecodeError as exc: + print(f"WARNING: compose config JSON input is not valid JSON: {exc}", file=sys.stderr) + return None + + def audit_ports(config: dict, mesh_allowed_services: set[str]) -> list[dict]: """Extract and classify port bindings from compose config.""" findings = [] @@ -179,8 +208,17 @@ def print_report( return 0 -def main() -> int: - config = parse_compose_config() +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Audit compose port bindings.") + parser.add_argument( + "--config-json", + metavar="PATH", + help="read resolved compose config JSON from PATH ('-' = stdin) " + "instead of running a bare `docker compose config`", + ) + args = parser.parse_args([] if argv is None else argv) + + config = read_config_json(args.config_json) if args.config_json else parse_compose_config() if config is None: print("ERROR: dynamic compose parsing failed — failing closed.", file=sys.stderr) print("Run 'docker compose config' manually to diagnose.", file=sys.stderr) @@ -195,4 +233,4 @@ def main() -> int: if __name__ == "__main__": - sys.exit(main()) + sys.exit(main(sys.argv[1:])) From 14b7941a73b6176c61b0f9f1c4dc53792b812309 Mon Sep 17 00:00:00 2001 From: POWERFULMOVES <142271328+POWERFULMOVES@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:43:15 -0500 Subject: [PATCH 3/3] docs(net): env.mesh-bind.example documents the branded-default rule; tests pin overlay order + literal-wildcard allowlist - env.mesh-bind.example: the file is now loaded into compose LAST; prefer the node's tailnet IP over 0.0.0.0; commented opt-in lines for every surface being moved to loopback (flips pending a compose Known Road grant, stated in the file). Values kept alone on their line: port_audit compares the whole text after '=', so a trailing comment would defeat a 0.0.0.0 opt-in. - test_makefile_mesh_bind_overlay.py: overlay appended once, guarded, LAST; port-audit pipes $(DC) config. All 4 fail against the pre-change files. - test_port_audit.py: non-literal-wildcard values (specific IP, blank, 0.0.0.0 with trailing comment, ::, 0.0.0.0/0) never allowlist, with a positive control; --config-json stdin/path, empty/invalid input fails closed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016aNs4rDG3Hx25i9J38nSX6 --- pmoves/env.mesh-bind.example | 67 ++++++++++ .../unit/test_makefile_mesh_bind_overlay.py | 74 +++++++++++ pmoves/tests/unit/test_port_audit.py | 119 ++++++++++++++++++ 3 files changed, 260 insertions(+) create mode 100644 pmoves/tests/unit/test_makefile_mesh_bind_overlay.py diff --git a/pmoves/env.mesh-bind.example b/pmoves/env.mesh-bind.example index 12947aeb0..14fb1e287 100644 --- a/pmoves/env.mesh-bind.example +++ b/pmoves/env.mesh-bind.example @@ -4,6 +4,30 @@ # Copy only the lines you need into `pmoves/env.mesh-bind.local` (ignored). # Do not commit live bind overrides with secrets. # +# THE RULE -- node-branded bind defaults: +# * Source (compose) defaults every *_BIND to 127.0.0.1, except the reviewed +# mesh-default surfaces listed near the bottom of this file. +# * A node that must be reached from another host opts in through ITS OWN +# `pmoves/env.mesh-bind.local`. Nobody widens a compose default for one node. +# +# HOW IT IS LOADED: +# * The Makefile appends `--env-file env.mesh-bind.local` as the LAST compose +# env file (after env.shared and every env.tier-* file), so a value here +# overrides the tiers for every `$(DC)` target (up, recreate, config, ...). +# * A raw `docker compose ...` that bypasses the Makefile does NOT read it. +# * `make port-audit` (tools/port_audit.py) reads the same file as its +# allowlist. Only a value that is EXACTLY 0.0.0.0 allowlists a service there. +# * Nothing changes on a running node until its containers are recreated. +# +# PREFER THE TAILNET IP OVER 0.0.0.0. A node that needs mesh reach should bind +# to its own tailnet IP (as env.shared.example advises for NATS_BIND), so the +# surface is reachable over the mesh but not on every interface. Never write a +# real IP into a committed file -- only into your gitignored .local copy. +# CAVEAT: port_audit.py only allowlists the literal 0.0.0.0. A tailnet-IP bind +# is reported as a VIOLATION (expected 127.0.0.1) until the audit learns to +# accept a specific interface address -- read that finding as "bound to a +# specific interface", not "exposed on all interfaces". +# # This file is the safe split from the abandoned "flip everything to 0.0.0.0" # stash. It intentionally carries only reviewed service surfaces. # @@ -35,6 +59,49 @@ # ----------------------------------------------------------------------------- #TTS_BIND=0.0.0.0 +# ----------------------------------------------------------------------------- +# Loopback-default surfaces with no prior review record (opt in per node) +# ----------------------------------------------------------------------------- +# These defaulted to 0.0.0.0 in source with no review record and are being +# moved to 127.0.0.1 (PR fix/node-branded-bind-defaults-2026-11-27). STATUS: +# the compose default flips are PENDING a compose Known Road grant -- until +# they land, source still defaults these to 0.0.0.0. Opting in here is safe +# either way. Use `` where you can, 0.0.0.0 only if the +# surface must answer on every interface. Keep each value ALONE on its line: +# port_audit.py compares the whole text after `=`, so a trailing `# comment` +# would stop a 0.0.0.0 value from allowlisting. +# tensorzero-ui 4000 +#TENSORZERO_UI_BIND= +# openroom 5173 +#OPENROOM_BIND= +# presign 8088 +#PRESIGN_BIND= +# render-webhook 8085 +#RENDER_WEBHOOK_BIND= +# extract-worker 8083 +#EXTRACT_WORKER_BIND= +# mcp-gateway 8189 +#MCP_GATEWAY_BIND= +# model-registry 8110 +#MODEL_REGISTRY_BIND= +# Monitoring stack (monitoring/docker-compose.monitoring.yml) -- today these +# publish with NO host-ip at all, which Docker treats as 0.0.0.0. The bind +# vars below are the names the pending flip introduces; they have no effect +# until it lands. +# prometheus 9090 +#PROMETHEUS_BIND= +# grafana 3002 +#GRAFANA_BIND= +# loki 3100 +#LOKI_BIND= +# blackbox-exporter 9115 +#BLACKBOX_BIND= +# Open Notebook (docker-compose.open-notebook.yml) -- same: no host-ip today. +# open-notebook API 5055 +#OPEN_NOTEBOOK_API_BIND= +# open-notebook UI 8503 +#OPEN_NOTEBOOK_UI_BIND= + # ----------------------------------------------------------------------------- # Already mesh-default in base compose (documented here so operators do not # cargo-cult them into broader blanket edits) diff --git a/pmoves/tests/unit/test_makefile_mesh_bind_overlay.py b/pmoves/tests/unit/test_makefile_mesh_bind_overlay.py new file mode 100644 index 000000000..e90cd6796 --- /dev/null +++ b/pmoves/tests/unit/test_makefile_mesh_bind_overlay.py @@ -0,0 +1,74 @@ +"""The node's bind overlay (env.mesh-bind.local) must be the LAST compose env file. + +Node-branded bind defaults: compose source defaults *_BIND to loopback, and a +node opts in to wider binds through its own gitignored env.mesh-bind.local. +That only works if the overlay is appended AFTER env.shared and every +env.tier-* file -- compose lets a later --env-file override an earlier one, so +an overlay loaded earlier would be silently overridden by the tiers. + +This is a static check over the Makefile text on purpose: evaluating the +Makefile with a real env.mesh-bind.local would mean creating that file inside +the checkout, which would clobber a node's real overlay. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +PMOVES = Path(__file__).resolve().parents[2] +MAKEFILE = PMOVES / "Makefile" +INFRA_MK = PMOVES / "mk" / "infra.mk" +OVERLAY = "env.mesh-bind.local" + +APPEND = re.compile(r"^\s*COMPOSE_ENV_FILES\s*\+=\s*(.*)$") + + +def _appends() -> list[tuple[int, str]]: + out = [] + for lineno, line in enumerate(MAKEFILE.read_text(encoding="utf-8").splitlines(), 1): + if line.lstrip().startswith("#"): + continue + m = APPEND.match(line) + if m: + out.append((lineno, m.group(1).strip())) + return out + + +def test_overlay_is_appended_to_compose_env_files() -> None: + appends = _appends() + assert appends, "no COMPOSE_ENV_FILES += lines found -- Makefile layout changed" + hits = [value for _, value in appends if OVERLAY in value] + assert hits == [f"--env-file {OVERLAY}"], ( + f"{OVERLAY} must be appended exactly once as `--env-file {OVERLAY}`; " + f"found {hits!r} among {len(appends)} appends" + ) + + +def test_overlay_is_the_last_env_file_appended() -> None: + appends = _appends() + last_lineno, last_value = appends[-1] + assert OVERLAY in last_value, ( + f"the last COMPOSE_ENV_FILES append (Makefile:{last_lineno}) is " + f"{last_value!r}; {OVERLAY} must come last so the node's bind decision " + f"overrides the tier files ({len(appends)} appends inspected)" + ) + + +def test_overlay_append_is_guarded_by_existence() -> None: + """A node with no overlay must not get a missing --env-file (compose errors).""" + text = MAKEFILE.read_text(encoding="utf-8") + assert f'ifneq ("$(wildcard {OVERLAY})","")' in text + + +def test_port_audit_resolves_through_dc_not_bare_compose() -> None: + """port-audit must see the same env files as `up`, so it pipes $(DC) config.""" + text = INFRA_MK.read_text(encoding="utf-8") + m = re.search(r"^port-audit:.*?(?=^\S)", text, re.S | re.M) + assert m, "port-audit target not found in mk/infra.mk" + recipe = "\n".join( + ln for ln in m.group(0).splitlines() if not ln.strip().startswith("@#") + ) + assert "$(DC) config --format json" in recipe + assert "--config-json -" in recipe + assert "@docker compose config" not in recipe, "bare compose reads no env files" diff --git a/pmoves/tests/unit/test_port_audit.py b/pmoves/tests/unit/test_port_audit.py index 9eb2bf353..3b2140bd1 100644 --- a/pmoves/tests/unit/test_port_audit.py +++ b/pmoves/tests/unit/test_port_audit.py @@ -21,6 +21,7 @@ main, parse_compose_config, print_report, + read_config_json, ) @@ -672,3 +673,121 @@ def test_returns_parsed_dict_on_success(self) -> None: mock_run.return_value.stdout = json.dumps(expected) result = parse_compose_config() assert result == expected + + +# ============================================================================ +# Node-branded bind overlay: only a literal 0.0.0.0 allowlists +# ============================================================================ + + +class TestBindFileOnlyLiteralWildcardAllowlists: + """env.mesh-bind.local is now ALSO loaded into compose (last env file). + + The audit still treats it as an allowlist, and only a value that is + exactly 0.0.0.0 may allowlist a service. A node binding to one specific + interface (its tailnet IP, per env.mesh-bind.example) must NOT silently + widen what the audit accepts -- the audit expects loopback for it and + reports the specific-interface bind, so nothing is waved through. + + Addresses are RFC 5737 documentation ranges, never a real host. + """ + + @pytest.fixture(autouse=True) + def _isolate_bind_file_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(PORT_AUDIT_BIND_FILE_ENV, raising=False) + + @pytest.mark.parametrize( + "value", + [ + "198.51.100.7", # a specific interface (tailnet-IP shape) + '"198.51.100.7"', + "127.0.0.1", + "", # blank = compose default, not an opt-in + "0.0.0.0 # trailing", # an inline comment is not a bare wildcard + "0.0.0.0/0", + "::", + "0.0.0.00", + ], + ) + def test_non_wildcard_value_is_not_allowlisted(self, tmp_path: Path, value: str) -> None: + bind_file = tmp_path / "env.mesh-bind.local" + bind_file.write_text(f"NATS_BIND={value}\nOPENROOM_BIND={value}\n") + with patch("pmoves.tools.port_audit.DEFAULT_BIND_FILE", bind_file): + _, allowed, unmapped = load_mesh_allowed_services() + assert allowed == set(), f"value {value!r} allowlisted {allowed}" + assert unmapped == set(), f"value {value!r} reported unmapped {unmapped}" + + def test_specific_interface_bind_is_reported_not_waved_through(self, tmp_path: Path) -> None: + bind_file = tmp_path / "env.mesh-bind.local" + bind_file.write_text("NATS_BIND=198.51.100.7\n") + with patch("pmoves.tools.port_audit.DEFAULT_BIND_FILE", bind_file): + _, allowed, _ = load_mesh_allowed_services() + config = {"services": {"nats": {"ports": [ + {"host_ip": "198.51.100.7", "published": "4222", "target": "4222"}, + ]}}} + findings = audit_ports(config, allowed) + assert [f["status"] for f in findings] == ["VIOLATION"] + assert findings[0]["expected"] == "127.0.0.1" + + def test_literal_wildcard_still_allowlists(self, tmp_path: Path) -> None: + """Positive control: the parametrized negatives are not vacuous.""" + bind_file = tmp_path / "env.mesh-bind.local" + bind_file.write_text("NATS_BIND=0.0.0.0\n") + with patch("pmoves.tools.port_audit.DEFAULT_BIND_FILE", bind_file): + _, allowed, _ = load_mesh_allowed_services() + assert allowed == {"nats"} + + +# ============================================================================ +# --config-json: config resolved by $(DC), piped in +# ============================================================================ + + +class TestConfigJsonInput: + """`make port-audit` pipes `$(DC) config --format json` into --config-json -.""" + + CLEAN = {"services": {"web": {"ports": [{"host_ip": "127.0.0.1", "published": "8080", "target": "80"}]}}} + WIDE = {"services": {"web": {"ports": [{"host_ip": "0.0.0.0", "published": "8080", "target": "80"}]}}} + + def _no_bind_file(self): + return patch( + "pmoves.tools.port_audit.load_mesh_allowed_services", + return_value=(Path("/nonexistent"), set(), set()), + ) + + def test_stdin_clean_config_returns_0(self, monkeypatch: pytest.MonkeyPatch) -> None: + import io + import json + monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(self.CLEAN))) + with self._no_bind_file(), patch("pmoves.tools.port_audit.parse_compose_config") as bare: + rc = main(["--config-json", "-"]) + assert rc == 0 + bare.assert_not_called() + + def test_stdin_violation_returns_1(self, monkeypatch: pytest.MonkeyPatch) -> None: + import io + import json + monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(self.WIDE))) + with self._no_bind_file(): + assert main(["--config-json", "-"]) == 1 + + @pytest.mark.parametrize("payload", ["", " \n", "not json {{"]) + def test_empty_or_invalid_stdin_fails_closed( + self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, payload: str + ) -> None: + """Upstream `$(DC) config` failing writes nothing: that must not read as clean.""" + import io + monkeypatch.setattr("sys.stdin", io.StringIO(payload)) + with self._no_bind_file(): + rc = main(["--config-json", "-"]) + assert rc == 1 + assert "failing closed" in capsys.readouterr().err + + def test_reads_from_path(self, tmp_path: Path) -> None: + import json + cfg = tmp_path / "config.json" + cfg.write_text(json.dumps(self.CLEAN)) + assert read_config_json(str(cfg)) == self.CLEAN + + def test_missing_path_returns_none(self, tmp_path: Path) -> None: + assert read_config_json(str(tmp_path / "absent.json")) is None