feat(deploy): add scoped Mission Core map gateway access

This commit is contained in:
Codex
2026-09-10 20:48:04 +03:00
parent 6e2baf16fc
commit 11b73e6468
4 changed files with 347 additions and 1 deletions
+203 -1
View File
@@ -14,6 +14,7 @@ import pwd
import re
import secrets
import shutil
import signal
import socket
import sqlite3
import stat
@@ -2919,6 +2920,12 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
)
COMPONENTS = {
"mission-core-map-access": {
"payload_root": Path("/volume1/docker/nodedc-platform/mission-core-map-access"),
"bootstrap_root": True,
"artifact_only": True,
"services": (),
},
"engine": {
"payload_root": Path("/volume2/nodedc-demo"),
"compose_root": Path("/volume2/nodedc-demo"),
@@ -4894,6 +4901,11 @@ def allowed_payload_path(component, rel):
if reason:
die(f"path rejected: {rel}: {reason}")
if component == "mission-core-map-access":
if rel == "access.json":
return True
die("Mission Core Map Access accepts only access.json")
if component == "engine":
if rel in ("nodedc-source/package.json", "nodedc-source/package-lock.json"):
return True
@@ -11490,6 +11502,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "mission-core-map-access":
read_map_access_descriptor(payload_dir, entries)
if is_gitea_fresh_install_slice(manifest["component"], entries):
validate_gitea_fresh_install_payload(payload_dir, entries)
elif is_gitea_incident_salvage_slice(manifest["component"], entries):
@@ -31181,6 +31195,172 @@ def accept_engine_n8n_runtime(descriptor):
}
MAP_ACCESS_CONFIG = Path("/etc/ssh/sshd_config")
MAP_ACCESS_SSHD = Path("/usr/bin/sshd")
MAP_ACCESS_PID = Path("/var/run/sshd.pid")
MAP_ACCESS_BASE_SHA = "adf3da038acb21e30a1b79089f53917e7e82b469183889567b7d22f7b83163ba"
MAP_ACCESS_APPEND = (
b"\n# BEGIN NODEDC MISSION CORE MAP ACCESS v1\n"
b"Match User dctouch\n"
b" AllowTcpForwarding local\n"
b" PermitOpen 127.0.0.1:18103\n"
b"Match all\n"
b"# END NODEDC MISSION CORE MAP ACCESS v1\n"
)
def read_map_access_descriptor(root, entries):
if tuple(entries) != ("access.json",):
die("Map access file selection mismatch")
value = read_strict_json(root / "access.json", "Map access descriptor", max_bytes=1024)
if (set(value) != {"schemaVersion", "state"}
or value["schemaVersion"] != "nodedc.mission-core-map-access.v1"
or value["state"] not in ("enabled", "disabled")):
die("Map access descriptor mismatch")
return value["state"]
def map_access_policy(raw, desired):
base = raw[:-len(MAP_ACCESS_APPEND)] if raw.endswith(MAP_ACCESS_APPEND) else raw
if hashlib.sha256(base).hexdigest() != MAP_ACCESS_BASE_SHA:
die("Map access SSH policy predecessor drift")
return base + MAP_ACCESS_APPEND if desired == "enabled" else base
def map_access_read_config():
metadata = MAP_ACCESS_CONFIG.lstat()
if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0
or metadata.st_mode & 0o022 or metadata.st_size > 65536):
die("Map access SSH configuration metadata rejected")
return MAP_ACCESS_CONFIG.read_bytes()
def map_access_effective(config, user, address):
result = subprocess.run(
[str(MAP_ACCESS_SSHD), "-T", "-f", str(config), "-C",
f"user={user},host=localhost,addr={address}"],
capture_output=True, text=True, timeout=10,
)
if result.returncode != 0:
die("Map access SSH effective-policy validation failed")
return dict(line.split(" ", 1) for line in result.stdout.splitlines() if " " in line)
def map_access_validate_candidate(before, candidate):
check = subprocess.run([str(MAP_ACCESS_SSHD), "-t", "-f", str(candidate)],
capture_output=True, timeout=10)
if check.returncode != 0:
die("Map access SSH syntax validation failed")
enabled = candidate.read_bytes().endswith(MAP_ACCESS_APPEND)
with tempfile.NamedTemporaryFile(dir=TMP_DIR) as original:
original.write(before); original.flush()
for address in ("127.0.0.1", "100.114.248.4"):
for user in ("dctouch", "root", "admin", "anonymous"):
old = map_access_effective(original.name, user, address)
new = map_access_effective(candidate, user, address)
if user == "dctouch":
old["allowtcpforwarding"] = "local" if enabled else "no"
old["permitopen"] = "127.0.0.1:18103" if enabled else "any"
if old != new:
die("Map access would change unrelated SSH authority")
def preflight_map_access(root, entries):
desired = read_map_access_descriptor(root, entries)
before = map_access_read_config()
after = map_access_policy(before, desired)
with tempfile.NamedTemporaryFile(dir=TMP_DIR) as candidate:
candidate.write(after); candidate.flush()
map_access_validate_candidate(before, Path(candidate.name))
return before, after
def map_access_replace(raw):
# Same-filesystem atomic replace; host policy is never accepted from an artifact.
original = MAP_ACCESS_CONFIG.stat()
fd, name = tempfile.mkstemp(prefix=".nodedc-map-", dir=MAP_ACCESS_CONFIG.parent)
try:
with os.fdopen(fd, "wb") as stream:
os.fchown(stream.fileno(), 0, original.st_gid)
os.fchmod(stream.fileno(), stat.S_IMODE(original.st_mode))
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
os.replace(name, MAP_ACCESS_CONFIG)
directory_fd = os.open(str(MAP_ACCESS_CONFIG.parent), os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
finally:
if os.path.exists(name):
os.unlink(name)
def map_access_reload():
metadata = MAP_ACCESS_PID.lstat()
if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022:
die("Map access SSH PID metadata rejected")
pid = int(MAP_ACCESS_PID.read_text().strip())
if pid <= 1 or Path(f"/proc/{pid}/exe").resolve() != MAP_ACCESS_SSHD.resolve():
die("Map access SSH master identity mismatch")
os.kill(pid, signal.SIGHUP)
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
try:
with socket.create_connection(("127.0.0.1", 22), timeout=2) as connection:
connection.settimeout(2)
if connection.recv(255).startswith(b"SSH-2.0-"):
return
except OSError:
pass
time.sleep(0.25)
die("Map access SSH listener did not recover")
def backup_map_access(backup_dir):
raw = map_access_read_config()
map_access_policy(raw, "enabled")
path = backup_dir / "sshd-config-before"
with path.open("xb") as output:
os.fchmod(output.fileno(), 0o600)
output.write(raw); output.flush(); os.fsync(output.fileno())
def apply_map_access(root, entries):
before, after = preflight_map_access(root, entries)
if after != before:
map_access_replace(after)
map_access_reload()
def accept_map_access(root, entries):
before, after = preflight_map_access(root, entries)
if before != after:
die("Map access installed policy differs from the requested state")
healthcheck_url({
"url": "http://127.0.0.1:18103/healthz",
"headers": {"x-nodedc-user-id": "mission-core-loopback-operator"},
"expected_json": {"ok": True, "service": "nodedc-map-gateway"},
})
def rollback_map_access(root, backup_dir, entries, current_stamp):
original = backup_dir / "sshd-config-before"
metadata = original.lstat()
if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o077:
die("Map access backup metadata rejected")
raw = original.read_bytes()
map_access_policy(raw, "enabled")
current = map_access_read_config()
map_access_policy(current, "enabled")
map_access_validate_candidate(current, original)
if raw != current:
map_access_replace(raw)
map_access_reload()
restore_overlay_source(root, backup_dir, entries, current_stamp)
if map_access_read_config() != raw:
die("Map access rollback policy verification failed")
def plan_artifact(artifact):
validate_artifact_location(artifact)
ensure_layout()
@@ -31237,6 +31417,8 @@ def plan_artifact(artifact):
validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL)
if is_gitea_incident_salvage_slice(manifest["component"], entries):
validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL)
if manifest["component"] == "mission-core-map-access":
preflight_map_access(payload_dir, entries)
reject_failed_artifact_replay(manifest, sha)
reject_terminal_engine_l2_failed_artifact(manifest, sha)
reject_terminal_device_plane_foundation_artifact(manifest, sha)
@@ -31820,6 +32002,10 @@ def plan_artifact(artifact):
print(f"component={component}")
print(f"type={manifest['type']}")
print(f"payload_root={root}")
if component == "mission-core-map-access":
print("access=local-forward:dctouch:127.0.0.1:18103")
print("runtime=sshd-scoped-reload;docker=untouched;cache=preserved")
print("policy_predecessor=exact;rollback=automatic")
print(f"compose_root={compose_root}")
compose_project = component_compose_project(component)
if compose_project:
@@ -37346,6 +37532,9 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None):
if component == "mission-core-map-access":
accept_map_access(component_root(component), entries)
return
if is_gitea_fresh_install_slice(component, entries):
if tuple(services or ()) != (GITEA_SERVICE,):
die("Gitea fresh-install service set mismatch")
@@ -38486,6 +38675,8 @@ def apply_artifact(artifact):
compose_root = component_compose_root(component)
bootstrap_root = bool(COMPONENTS[component].get("bootstrap_root"))
services = component_services(component, entries)
if component == "mission-core-map-access":
preflight_map_access(payload_dir, entries)
artifact_only = component_artifact_only(component)
defer_bootstrap_root = is_gitea_bootstrap_slice(
component,
@@ -39011,6 +39202,8 @@ def apply_artifact(artifact):
include_nginx_html = component == "engine" and component_publish_dist(component, entries)
create_backup(root, backup_dir, entries, include_nginx_html)
if component == "mission-core-map-access":
backup_map_access(backup_dir)
if component == "device-plane":
if device_plane_runtime_before is None:
die("Device Plane pre-apply runtime inventory is missing")
@@ -39077,6 +39270,9 @@ def apply_artifact(artifact):
for rel in entries:
seal_n8n_private_extension_release(root, rel)
if component == "mission-core-map-access":
apply_map_access(root, entries)
if component_publish_dist(component, entries):
publish_engine_dist(root, current_stamp)
@@ -39194,7 +39390,13 @@ def apply_artifact(artifact):
and backup_dir is not None
and root is not None
):
if is_gitea_fresh_install_slice(component, entries):
if component == "mission-core-map-access":
try:
rollback_map_access(root, backup_dir, entries, current_stamp)
rollback_status = "ok:mission-core-map-access"
except Exception as rollback_exc:
rollback_status = f"failed:{type(rollback_exc).__name__}"
elif is_gitea_fresh_install_slice(component, entries):
try:
restored_action = rollback_gitea_fresh_install(
root,