Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pmoves/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <internal-error> 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.
67 changes: 67 additions & 0 deletions pmoves/env.mesh-bind.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down Expand Up @@ -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 `<this-node-tailnet-ip>` 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=<this-node-tailnet-ip>
# openroom 5173
#OPENROOM_BIND=<this-node-tailnet-ip>
# presign 8088
#PRESIGN_BIND=<this-node-tailnet-ip>
# render-webhook 8085
#RENDER_WEBHOOK_BIND=<this-node-tailnet-ip>
# extract-worker 8083
#EXTRACT_WORKER_BIND=<this-node-tailnet-ip>
# mcp-gateway 8189
#MCP_GATEWAY_BIND=<this-node-tailnet-ip>
# model-registry 8110
#MODEL_REGISTRY_BIND=<this-node-tailnet-ip>
# 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=<this-node-tailnet-ip>
# grafana 3002
#GRAFANA_BIND=<this-node-tailnet-ip>
# loki 3100
#LOKI_BIND=<this-node-tailnet-ip>
# blackbox-exporter 9115
#BLACKBOX_BIND=<this-node-tailnet-ip>
# Open Notebook (docker-compose.open-notebook.yml) -- same: no host-ip today.
# open-notebook API 5055
#OPEN_NOTEBOOK_API_BIND=<this-node-tailnet-ip>
# open-notebook UI 8503
#OPEN_NOTEBOOK_UI_BIND=<this-node-tailnet-ip>

# -----------------------------------------------------------------------------
# Already mesh-default in base compose (documented here so operators do not
# cargo-cult them into broader blanket edits)
Expand Down
11 changes: 6 additions & 5 deletions pmoves/mk/infra.mk
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
74 changes: 74 additions & 0 deletions pmoves/tests/unit/test_makefile_mesh_bind_overlay.py
Original file line number Diff line number Diff line change
@@ -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"
119 changes: 119 additions & 0 deletions pmoves/tests/unit/test_port_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
main,
parse_compose_config,
print_report,
read_config_json,
)


Expand Down Expand Up @@ -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
Loading
Loading