From 54bcf516491ae8fed4eb249b8afa4ec5465c583d Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:37:30 -0600 Subject: [PATCH 1/3] fabric(sircl): harden marker binary path/integrity, add open-chain planning, and fix route validation --- .../sircl/sparkring_sircl/fabric/cli.py | 3 +- .../sircl/sparkring_sircl/fabric/commands.py | 26 ++++- .../sircl/sparkring_sircl/fabric/diff.py | 22 ++-- .../sircl/sparkring_sircl/fabric/plan.py | 102 ++++++++++++++++-- .../sircl/sparkring_sircl/fabric/state.py | 52 ++++++++- .../sircl/sparkring_sircl/routes.py | 81 +++++++++++--- .../sparkring_sircl/testing/relay_hosts.py | 48 ++++++++- .../sircl/tests/fabric_reference.py | 2 +- .../sircl/tests/test_fabric_ops.py | 59 +++++++++- .../sircl/tests/test_fabric_plan.py | 62 +++++++++++ spark_transport/sircl/tests/test_routes.py | 49 +++++++++ 11 files changed, 458 insertions(+), 48 deletions(-) diff --git a/spark_transport/sircl/sparkring_sircl/fabric/cli.py b/spark_transport/sircl/sparkring_sircl/fabric/cli.py index dd647892..84766859 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/cli.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/cli.py @@ -106,7 +106,8 @@ def _marker_command(site: Site, positions: list[int], executor: ops.Executor, ar marker: commands.MarkerConfig) -> int: states = ops.gather(site, positions, executor, marker) print(report.render_marker_status(states, marker)) - targets = [p for p in positions if states[p].reachable and (args.rebuild or states[p].marker_binary is None)] + targets = [p for p in positions if states[p].reachable and ( + args.rebuild or bool(states[p].marker_problems(marker.path, expected_sha256=marker.expected_sha256)))] if not targets: print("every reachable Spark has the marker executable") return 0 if all(states[p].reachable for p in positions) else 1 diff --git a/spark_transport/sircl/sparkring_sircl/fabric/commands.py b/spark_transport/sircl/sparkring_sircl/fabric/commands.py index ebde5293..7abc900e 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/commands.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/commands.py @@ -42,7 +42,8 @@ STATE_DIR = "/run/sparkring-fabric" RECORD_PATH = f"{STATE_DIR}/relay-state.json" RECORD_SCHEMA = "sparkring-fabric-relay-record/v1" -DEFAULT_MARKER = "/var/tmp/ring8-mesh-marker" +DEFAULT_MARKER_DIR = "/usr/local/libexec/sparkring" +DEFAULT_MARKER = f"{DEFAULT_MARKER_DIR}/ring8-mesh-marker" SECTION = "@@" HEADER = "set -euo pipefail" SETTLE = "sleep 1.5" @@ -61,16 +62,23 @@ class MarkerConfig: path: str = DEFAULT_MARKER log_dir: str = "/tmp" + expected_sha256: str | None = None def __post_init__(self) -> None: for label, value in (("marker path", self.path), ("marker log directory", self.log_dir)): if not _PATH.match(value) or "/../" in f"{value}/": raise FabricError(f"{label} {value!r} must be an absolute path of letters, digits and _./+-") + if self.expected_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", self.expected_sha256.lower()): + raise FabricError(f"expected marker sha256 {self.expected_sha256!r} must be 64 hex characters") @property def name(self) -> str: return posixpath.basename(self.path) + @property + def digest_path(self) -> str: + return f"{self.path}.sha256" + @property def comm(self) -> str: """The process name the kernel keeps for the executable (its first 15 characters).""" @@ -128,6 +136,8 @@ def section(name: str, *commands: str) -> None: section(f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress 2>/dev/null || true") section("markers", f"pgrep -a -x {q(marker.comm)} || true") section("marker-binary", f"sha256sum {q(marker.path)} 2>/dev/null || true") + section("marker-stat", f"stat -c '%u %g %a' {q(marker.path)} 2>/dev/null || true") + section("marker-sha256", f"cat {q(marker.digest_path)} 2>/dev/null || true") for device in RDMA_DEVICES: section(f"marker-log:{device}", f"head -c 4096 {q(marker.log(device))} 2>/dev/null || true") section("record", f"cat {RECORD_PATH} 2>/dev/null || true") @@ -245,18 +255,24 @@ def record_remove() -> str: def marker_build_script(hostname: str, marker: MarkerConfig, source: str) -> str: - """Compile the marker source on a Spark (rdma-core headers needed) and install it at the marker path.""" + """Compile the marker source on a Spark (rdma-core headers needed) and install it root-owned.""" if any(line.strip() == MARKER_SOURCE_END for line in source.splitlines()): raise FabricError("the marker source contains the here-document delimiter") + marker_dir = posixpath.dirname(marker.path) + digest_path = marker.digest_path return "\n".join([ HEADER, guard(hostname), - "work=$(mktemp -d)", + "work=$(mktemp -d /var/tmp/sparkring-marker.XXXXXX)", "trap 'rm -rf \"$work\"' EXIT", f"cat > \"$work/mesh_marker.c\" <<'{MARKER_SOURCE_END}'", source.rstrip("\n"), MARKER_SOURCE_END, "cc -O2 -Wall -Wextra \"$work/mesh_marker.c\" -o \"$work/marker\" -libverbs -lmlx5", - f"install -m 0755 \"$work/marker\" {q(marker.path)}", - f"sha256sum {q(marker.path)}", + f"sudo -n install -d -o root -g root -m 0755 {q(marker_dir)}", + f"sudo -n install -o root -g root -m 0755 \"$work/marker\" {q(marker.path)}", + "rm -f \"$work/marker\"", + f"sha256sum {q(marker.path)} > \"$work/marker.sha256\"", + f"sudo -n install -o root -g root -m 0644 \"$work/marker.sha256\" {q(digest_path)}", + f"cat {q(digest_path)}", ]) + "\n" diff --git a/spark_transport/sircl/sparkring_sircl/fabric/diff.py b/spark_transport/sircl/sparkring_sircl/fabric/diff.py index f523f4e2..67f6fccc 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/diff.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/diff.py @@ -183,16 +183,21 @@ def _marker_changes(diff: SparkDiff, script: _Script, state: HostState, spark: S if process.pid not in handled: script.marker_stop.extend(commands.marker_stop(marker, process.pid)) diff.changes.append(Change("marker", "remove", f"pid {process.pid}", process.text())) - if script.marker_start and state.marker_binary is None: - diff.blockers.append(f"the marker executable {marker.path} is missing; build it with the `marker` command") + if script.marker_start or (spark is not None and spark.markers): + diff.blockers.extend(state.marker_problems(marker.path, expected_sha256=marker.expected_sha256)) def _record(spark: SparkPlan, plan: GroupPlan, layout_name: str, marker: commands.MarkerConfig, - qdiscs: Sequence[str]) -> dict[str, object]: - return {"schema": commands.RECORD_SCHEMA, "spark": spark.name, "position": spark.position, - "layout": layout_name, "group": plan.group.label, "members": list(plan.group.members), - "relay_egress": plan.relay_egress, "plan": plan.digest, "marker": marker.path, - "qdiscs": sorted(qdiscs)} + qdiscs: Sequence[str], *, marker_sha256: str | None = None) -> dict[str, object]: + record: dict[str, object] = { + "schema": commands.RECORD_SCHEMA, "spark": spark.name, "position": spark.position, + "layout": layout_name, "group": plan.group.label, "members": list(plan.group.members), + "relay_egress": plan.relay_egress, "plan": plan.digest, "marker": marker.path, + "qdiscs": sorted(qdiscs), + } + if marker_sha256 is not None: + record["marker_sha256"] = marker_sha256 + return record def compare_up(state: HostState, spark: SparkPlan, plan: GroupPlan, *, layout_name: str, @@ -305,7 +310,8 @@ def compare_up(state: HostState, spark: SparkPlan, plan: GroupPlan, *, layout_na script.qdisc_del.append(commands.qdisc_del(netdev)) kept.discard(netdev) diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the installer")) - wanted_record = _record(spark, plan, layout_name, marker, sorted(kept)) + wanted_record = _record(spark, plan, layout_name, marker, sorted(kept), + marker_sha256=state.marker_binary if spark.markers else None) if state.record != wanted_record: script.record.extend(commands.record_write(wanted_record)) before = (f"group {state.record.get('group')}, plan {state.record.get('plan')}" if state.record diff --git a/spark_transport/sircl/sparkring_sircl/fabric/plan.py b/spark_transport/sircl/sparkring_sircl/fabric/plan.py index b121e984..bb603351 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/plan.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/plan.py @@ -494,7 +494,74 @@ def _digest(label: str, relay_egress: str, sparks: Sequence[SparkPlan]) -> str: return hashlib.sha256(canonical.encode()).hexdigest()[:16] -def build_group_plan(group: Group, facts: Facts, *, relay_egress: str, +@dataclasses.dataclass(frozen=True) +class ChainGroup: + """An open chain/path group backed directly by its fabric cables (no closing ring cable).""" + + members: tuple[int, ...] + fabric: routes.Fabric + + def __post_init__(self) -> None: + members = tuple(int(member) for member in self.members) + object.__setattr__(self, "members", members) + if len(members) < 2 or len(set(members)) != len(members): + raise FabricError(f"chain group {members} needs at least two distinct Sparks") + if self.fabric.kind == "disconnected": + raise FabricError(f"chain group {members} fabric is disconnected") + self.layout() + + def layout(self) -> routes.Layout: + try: + return routes.Layout(self.fabric, self.members) + except routes.RouteError as error: + raise FabricError(str(error)) from None + + @property + def ring_size(self) -> int: + return len(self.fabric.positions) + + @property + def whole_ring(self) -> bool: + return False + + @property + def order(self) -> tuple[int, ...]: + return self.members + + @property + def kind(self) -> str: + return "pair" if len(self.members) == 2 else "path" + + @property + def label(self) -> str: + return f"{self.kind}:{'-'.join(str(position) for position in self.order)}" + + @property + def cables(self) -> tuple[str, ...]: + return tuple(cable.text for cable in self.fabric.cables) + + +def build_chain_plan( + positions: Sequence[int], + facts: Facts, + *, + fabric: routes.Fabric | None = None, + relay_egress: str = "sibling", + max_relays: int = routes.DEFAULT_MAX_RELAYS, +) -> GroupPlan: + """Build the relay plan of an open chain/path of Sparks without assuming a closed ring.""" + members = tuple(int(p) for p in positions) + if fabric is None: + try: + fabric = routes.Fabric.path(members) + except routes.RouteError as error: + raise FabricError(str(error)) from None + if fabric.kind != "path": + raise FabricError(f"open chain plan requires a connected path fabric, got {fabric.kind}") + return build_group_plan(ChainGroup(members, fabric), facts, relay_egress=relay_egress, max_relays=max_relays) + + +def build_group_plan(group: Group | ChainGroup, facts: Facts, *, relay_egress: str, max_relays: int = routes.DEFAULT_MAX_RELAYS) -> GroupPlan: """The relay plan of one group (module docstring), checked by :func:`trace` on every origin route.""" if relay_egress not in RELAY_EGRESS: @@ -545,7 +612,8 @@ def build_group_plan(group: Group, facts: Facts, *, relay_egress: str, by_position = {spark.position: spark for spark in sparks} for spark in sparks: for route in spark.routes: - result = trace(by_position, facts, group.ring_size, spark.position, route.destination) + result = trace(by_position, facts, group.ring_size, spark.position, route.destination, + fabric=layout.fabric) if result.outcome != "delivered" or result.hops[-1] != (route.peer, route.peer_netdev): raise FabricError(f"group {group.label}: the route from {spark.name} to {route.destination} does " f"not deliver through the plan's relays ({result.outcome}: {result.detail})") @@ -591,13 +659,15 @@ class Trace: detail: str = "" -def trace(sparks: Mapping[int, SparkPlan], facts: Facts, ring_size: int, origin: int, destination: str, - *, limit: int = 2 * MAX_TAG) -> Trace: - """Follow a frame from ``origin`` to ``destination`` through the plan's objects on the physical ring. +def trace(sparks: Mapping[int, SparkPlan], facts: Facts, ring_size: int | None, origin: int, destination: str, + *, fabric: routes.Fabric | None = None, limit: int = 2 * MAX_TAG) -> Trace: + """Follow a frame from ``origin`` to ``destination`` through the plan's objects on the physical fabric. - Port 0 of position ``i`` is cabled to port 1 of position ``i + 1``. A frame - is received by the function whose MAC it carries on the far end of the - cable; a tagged frame continues only through a relay filter for its tag. + When ``fabric`` is provided, each hop follows its exact cable + (``fabric.cross``), so open chains/paths drop frames exiting an uncabled + endpoint port and arbitrary port pairings are traced faithfully. Otherwise, + falls back to a closed ring of ``ring_size`` Sparks where port 0 of + position ``i`` is cabled to port 1 of position ``(i + 1) % ring_size``. """ spark = sparks.get(origin) route = spark.route_to(destination) if spark is not None else None @@ -607,11 +677,21 @@ def trace(sparks: Mapping[int, SparkPlan], facts: Facts, ring_size: int, origin: hops: list[tuple[int, str]] = [] for _ in range(limit): port = role_of_netdev(out_netdev).port - there = (here + 1) % ring_size if port == 0 else (here - 1) % ring_size + if fabric is not None: + step = fabric.cross(here, port) + if step is None: + return Trace("dropped", tuple(hops), + f"position {here} port {port} has no cable on this fabric") + there, expected_port = step.dst, step.dst_port + else: + if ring_size is None: + raise FabricError("trace requires either fabric or ring_size") + there = (here + 1) % ring_size if port == 0 else (here - 1) % ring_size + expected_port = 1 - port receiver = facts.find_mac(mac) - if receiver is None or receiver[0] != there or role_of_netdev(receiver[1]).port != 1 - port: + if receiver is None or receiver[0] != there or role_of_netdev(receiver[1]).port != expected_port: return Trace("misdelivered", tuple(hops), f"a frame for {mac} leaves position {here} port {port}; " - f"the cable ends at position {there} port {1 - port}") + f"the cable ends at position {there} port {expected_port}") hops.append(receiver) netdev = receiver[1] k = relays_left(ethertype) diff --git a/spark_transport/sircl/sparkring_sircl/fabric/state.py b/spark_transport/sircl/sparkring_sircl/fabric/state.py index a15a8153..7c938e36 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/state.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/state.py @@ -420,6 +420,10 @@ class HostState: filters: dict[str, list[FilterEntry]] = dataclasses.field(default_factory=dict) markers: list[MarkerProcess] = dataclasses.field(default_factory=list) marker_binary: str | None = None + marker_uid: int | None = None + marker_gid: int | None = None + marker_mode: int | None = None + marker_expected_sha256: str | None = None marker_logs: dict[str, dict | None] = dataclasses.field(default_factory=dict) record: dict | None = None record_problem: str | None = None @@ -502,6 +506,36 @@ def unowned_relay_objects(self) -> tuple[list[RouteEntry], list[NeighbourEntry]] return ([route for route in self.relay_routes() if not route.owned], [neighbour for neighbour in self.relay_neighbours() if not neighbour.owned]) + def marker_problems(self, path: str, *, expected_sha256: str | None = None) -> list[str]: + """Integrity problems that stop running ``path`` as root (empty when safe).""" + if self.marker_binary is None: + return [f"the marker executable {path} is missing; build it with the `marker` command"] + problems: list[str] = [] + if self.marker_uid is None or self.marker_mode is None: + problems.append(f"the marker executable {path} ownership and permissions could not be verified; " + "reinstall it with the `marker --rebuild --apply` command") + else: + if self.marker_uid != 0: + problems.append(f"the marker executable {path} is owned by uid {self.marker_uid}, expected root " + "(uid 0); reinstall it with the `marker --rebuild --apply` command") + if self.marker_mode & 0o022: + problems.append(f"the marker executable {path} has group/world-writable mode {self.marker_mode:04o}; " + "reinstall it with the `marker --rebuild --apply` command") + expected_sources: list[tuple[str, str]] = [] + if expected_sha256 is not None: + expected_sources.append(("configured", expected_sha256.lower())) + if self.marker_expected_sha256 is not None: + expected_sources.append(("recorded digest", self.marker_expected_sha256.lower())) + recorded = (self.record or {}).get("marker_sha256") + if isinstance(recorded, str) and len(recorded) == 64: + expected_sources.append(("state record", recorded.lower())) + actual = self.marker_binary.lower() + for label, expected in expected_sources: + if actual != expected: + problems.append(f"the marker executable {path} sha256 {actual} does not match {label} {expected}; " + "reinstall it with the `marker --rebuild --apply` command") + return problems + def parse_sections(stdout: str) -> dict[str, str]: """``@@`` blocks of a script's output, by name.""" @@ -543,7 +577,23 @@ def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, s state.filters[netdev] = parse_filters(raw.get(f"filters:{netdev}", ""), problems, netdev) state.markers = parse_markers(raw.get("markers", "")) binary = raw.get("marker-binary", "").split() - state.marker_binary = binary[0] if binary and len(binary[0]) == 64 else None + state.marker_binary = (binary[0].lower() + if binary and len(binary[0]) == 64 and all(c in "0123456789abcdef" for c in binary[0].lower()) + else None) + meta = raw.get("marker-stat", "").split() + if len(meta) >= 3 and meta[0].isdigit() and meta[1].isdigit(): + try: + state.marker_uid = int(meta[0]) + state.marker_gid = int(meta[1]) + state.marker_mode = int(meta[2], 8) + except ValueError: + pass + expected = raw.get("marker-sha256", "").split() + state.marker_expected_sha256 = ( + expected[0].lower() + if expected and len(expected[0]) == 64 and all(c in "0123456789abcdef" for c in expected[0].lower()) + else None + ) for device in RDMA_DEVICES: text = raw.get(f"marker-log:{device}", "").strip() first = text.splitlines()[0] if text else "" diff --git a/spark_transport/sircl/sparkring_sircl/routes.py b/spark_transport/sircl/sparkring_sircl/routes.py index b6b3d1e2..2742dcd9 100644 --- a/spark_transport/sircl/sparkring_sircl/routes.py +++ b/spark_transport/sircl/sparkring_sircl/routes.py @@ -252,14 +252,36 @@ def parse(cls, texts: Iterable[str]) -> "Fabric": def positions(self) -> tuple[int, ...]: return tuple(sorted({end[0] for cable in self.cables for end in cable.ends()})) + def connected(self) -> bool: + """Whether every position of the fabric is reachable from every other over its cables.""" + nodes = self.positions + if not nodes: + return False + adjacency: dict[int, list[int]] = {node: [] for node in nodes} + for cable in self.cables: + adjacency[cable.a].append(cable.b) + adjacency[cable.b].append(cable.a) + seen = {nodes[0]} + queue = deque([nodes[0]]) + while queue: + here = queue.popleft() + for nxt in adjacency[here]: + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + return len(seen) == len(nodes) + @property def kind(self) -> str: - """``cycle`` when every Spark has two cables and they close one loop, else ``path``.""" + """``cycle`` when every Spark has two cables closing one connected loop, + ``path`` for one connected open chain, else ``disconnected``.""" degree: dict[int, int] = {} for cable in self.cables: for position, _ in cable.ends(): degree[position] = degree.get(position, 0) + 1 - if degree and all(count == 2 for count in degree.values()) and len(self.cables) == len(degree): + if not degree or not self.connected(): + return "disconnected" + if all(count == 2 for count in degree.values()) and len(self.cables) == len(degree): return "cycle" return "path" @@ -484,12 +506,34 @@ def max_relays(self) -> int: default=0) -def derive_routes(layout: Layout, lanes: int = 2) -> GroupRoutes: - """Route maps of every rank of a session on ``layout``.""" +def _required_ring_peers(rank: int, world: int, layout: Layout | None) -> list[int]: + """The immediate neighbor peer ranks required for a sparse ``--ring-only`` route map.""" + if layout is not None: + rank_of = {pos: idx for idx, pos in enumerate(layout.positions)} + start = layout.positions[rank] + neighbors = sorted({ + rank_of[step.dst] + for port in (0, 1) + if (step := layout.fabric.cross(start, port)) is not None and step.dst in rank_of + } - {rank}) + if neighbors: + return neighbors + return sorted({(rank - 1) % world, (rank + 1) % world} - {rank}) + + +def derive_routes(layout: Layout, lanes: int = 2, *, ring_only: bool = False) -> GroupRoutes: + """Route maps of every rank of a session on ``layout``. + + With ``ring_only=True``, each rank includes only its immediate ring/chain neighbors. + """ ranks = [] + world = layout.world for rank, here in enumerate(layout.positions): - ranks.append({peer: derive_lanes(layout.fabric, here, there, lanes) - for peer, there in enumerate(layout.positions) if peer != rank}) + peers = _required_ring_peers(rank, world, layout) if ring_only else [ + peer for peer in range(world) if peer != rank + ] + ranks.append({peer: derive_lanes(layout.fabric, here, layout.positions[peer], lanes) + for peer in peers}) return GroupRoutes(layout, lanes, tuple(ranks)) @@ -534,22 +578,31 @@ def validate_route_map( max_relays: int = DEFAULT_MAX_RELAYS, available_devices: Iterable[str] | None = None, roles: Mapping[str, Role] | None = None, + ring_only: bool = False, ) -> int: """Check one rank's route map; return its lane count ``L``. - Rules: every other rank named exactly once and the own rank not at all; - every entry with the same lane count, 1 or 2, of distinct non-empty device - names; 1 to 4 devices in all, each available when ``available_devices`` - is given; with a layout, every lane stays inside the fabric and crosses at - most ``max_relays`` relays. Errors name the rank, the entry and the rule. + Rules: every required peer named exactly once (every other rank by default, + or immediate ring/chain neighbors when ``ring_only=True``) and the own rank + not at all; every entry with the same lane count, 1 or 2, of distinct + non-empty device names; 1 to 4 devices in all, each available when + ``available_devices`` is given; with a layout, every lane stays inside the + fabric and crosses at most ``max_relays`` relays. Errors name the rank, the + entry and the rule. """ if not 0 <= rank < world: raise RouteError(f"rank {rank} is outside a session of {world}") if rank in routes: raise RouteError(f"rank {rank}'s route map names its own rank") - missing = [peer for peer in range(world) if peer != rank and peer not in routes] + if layout is not None and layout.world != world: + raise RouteError(f"layout has {layout.world} ranks, the session {world}") + required = (_required_ring_peers(rank, world, layout) if ring_only + else [peer for peer in range(world) if peer != rank]) + missing = [peer for peer in required if peer not in routes] if missing: raise RouteError(f"rank {rank}'s route map has no entry for rank {missing[0]}") + if not routes: + raise RouteError(f"rank {rank}'s route map is empty") extra = sorted(peer for peer in routes if not 0 <= peer < world) if extra: raise RouteError(f"rank {rank}'s route map names rank {extra[0]}, outside the session") @@ -574,8 +627,6 @@ def validate_route_map( raise RouteError(f"rank {rank}'s route map names device {device}, which is not an active " "RDMA device of this host") if layout is not None: - if layout.world != world: - raise RouteError(f"layout has {layout.world} ranks, the session {world}") start = layout.positions[rank] for peer, devices in sorted(routes.items()): for lane, device in enumerate(devices): @@ -820,6 +871,8 @@ def chain_order( (no relay). """ fabric = layout.fabric + if fabric.kind == "disconnected": + return None if sorted(layout.positions) != list(fabric.positions): if not subset_ring: return None diff --git a/spark_transport/sircl/sparkring_sircl/testing/relay_hosts.py b/spark_transport/sircl/sparkring_sircl/testing/relay_hosts.py index e7a4d2ec..c94b2c84 100644 --- a/spark_transport/sircl/sparkring_sircl/testing/relay_hosts.py +++ b/spark_transport/sircl/sparkring_sircl/testing/relay_hosts.py @@ -89,7 +89,8 @@ class SimSpark: """One simulated Spark.""" def __init__(self, name: str, position: int, netdevs: Sequence[Netdev], *, style: str = "iproute2-6", - lan_address: str = "192.0.2.1", marker_path: str | None = "/var/tmp/ring8-mesh-marker") -> None: + lan_address: str = "192.0.2.1", + marker_path: str | None = "/usr/local/libexec/sparkring/ring8-mesh-marker") -> None: if style not in STYLES: raise ValueError(f"style must be one of {STYLES}") self.name = name @@ -108,8 +109,14 @@ def __init__(self, name: str, position: int, netdevs: Sequence[Netdev], *, style self.filters: dict[str, list[Filter]] = {n.name: [] for n in netdevs} self.processes: dict[int, dict] = {} self.files: dict[str, str] = {} + self.file_meta: dict[str, tuple[int, int, int]] = {} if marker_path: - self.files[marker_path] = "\x7fELF ring8-mesh-marker" + content = "\x7fELF ring8-mesh-marker" + self.files[marker_path] = content + self.file_meta[marker_path] = (0, 0, 0o755) + digest = hashlib.sha256(content.encode()).hexdigest() + self.files[f"{marker_path}.sha256"] = f"{digest} {marker_path}\n" + self.file_meta[f"{marker_path}.sha256"] = (0, 0, 0o644) self.next_pid = 4100 self.mutations: list[str] = [] self.reachable = True @@ -320,7 +327,19 @@ def _dispatch(self, line: str, out: list[str], err: list[str]) -> int: self._mutate(line) self.files[record.group(2)] = shlex.split(record.group(1))[0] + "\n" return 0 - if line in ("work=$(mktemp -d)", "trap 'rm -rf \"$work\"' EXIT"): + if line in ("work=$(mktemp -d)", "trap 'rm -rf \"$work\"' EXIT") or re.match( + r"^work=\$\(mktemp -d /\S+\)$", line): + return 0 + if line == 'rm -f "$work/marker"': + self.files.pop("$work/marker", None) + return 0 + sha_redirect = re.match(r'^sha256sum (\S+) > "\$work/marker\.sha256"$', line) + if sha_redirect: + path = shlex.split(sha_redirect.group(1))[0] + if path not in self.files: + return 1 + digest = hashlib.sha256(self.files[path].encode()).hexdigest() + self.files["$work/marker.sha256"] = f"{digest} {path}\n" return 0 compile_line = re.match(r'^cc -O2 -Wall -Wextra "\$work/mesh_marker\.c" -o "\$work/marker" -libverbs -lmlx5$', line) @@ -335,6 +354,23 @@ def _dispatch(self, line: str, out: list[str], err: list[str]) -> int: if install: self._mutate(line) self.files[install.group(1)] = self.files["$work/marker"] + self.file_meta[install.group(1)] = (1000, 1000, 0o755) + return 0 + sudo_install_dir = re.match(r"^sudo -n install -d -o root -g root -m ([0-7]+) (\S+)$", line) + if sudo_install_dir: + self._mutate(line) + return 0 + sudo_install = re.match(r'^sudo -n install -o root -g root -m ([0-7]+) "(\$work/\S+)" (\S+)$', line) + if sudo_install: + self._mutate(line) + mode = int(sudo_install.group(1), 8) + src = sudo_install.group(2) + dst = shlex.split(sudo_install.group(3))[0] + if src not in self.files: + err.append(f"install: cannot stat {src}") + return 1 + self.files[dst] = self.files[src] + self.file_meta[dst] = (0, 0, mode) return 0 words = shlex.split(line) tolerant = False @@ -405,6 +441,12 @@ def _command(self, words: list[str], line: str, out: list[str], err: list[str]) return 1 out.append(f"{hashlib.sha256(self.files[words[1]].encode()).hexdigest()} {words[1]}") return 0 + if words[:2] == ["stat", "-c"] and len(words) == 4 and words[2] == "%u %g %a": + if words[3] not in self.files: + return 1 + uid, gid, mode = self.file_meta.get(words[3], (0, 0, 0o755)) + out.append(f"{uid} {gid} {mode:o}") + return 0 if words[:2] == ["head", "-c"] and len(words) == 4: if words[3] not in self.files: return 1 diff --git a/spark_transport/sircl/tests/fabric_reference.py b/spark_transport/sircl/tests/fabric_reference.py index 6ac24b05..587241c1 100644 --- a/spark_transport/sircl/tests/fabric_reference.py +++ b/spark_transport/sircl/tests/fabric_reference.py @@ -29,7 +29,7 @@ "secondary": {"port0": "enP2p1s0f0np0", "port1": "enP2p1s0f1np1", "dev0": "roceP2p1s0f0", "dev1": "roceP2p1s0f1", "offset": 1}, } -MARKER = "/var/tmp/ring8-mesh-marker" +MARKER = "/usr/local/libexec/sparkring/ring8-mesh-marker" MAX_RELAYS = N // 2 - 1 diff --git a/spark_transport/sircl/tests/test_fabric_ops.py b/spark_transport/sircl/tests/test_fabric_ops.py index 107033b4..e3a9c9b3 100644 --- a/spark_transport/sircl/tests/test_fabric_ops.py +++ b/spark_transport/sircl/tests/test_fabric_ops.py @@ -328,15 +328,17 @@ def test_hostname_mismatch_unreachable_spark_and_missing_marker_block(ring, site ring.sparks[6].reachable = True del ring.sparks[4].files[MARKER.path] assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 3 - assert "marker executable /var/tmp/ring8-mesh-marker is missing" in capsys.readouterr().out + assert "marker executable /usr/local/libexec/sparkring/ring8-mesh-marker is missing" in capsys.readouterr().out assert _cli(ring, site_file, "marker", "--sparks", "4-7") == 0 out = capsys.readouterr().out - assert "spark4: /var/tmp/ring8-mesh-marker missing" in out - assert "dry run: --apply compiles mesh_marker.c and installs /var/tmp/ring8-mesh-marker on spark4" in out + assert "spark4: /usr/local/libexec/sparkring/ring8-mesh-marker missing" in out + assert ("dry run: --apply compiles mesh_marker.c and installs " + "/usr/local/libexec/sparkring/ring8-mesh-marker on spark4") in out assert MARKER.path not in ring.sparks[4].files assert _cli(ring, site_file, "marker", "--sparks", "4-7", "--apply") == 0 assert ring.sparks[4].files[MARKER.path].startswith("\x7fELF built ") - assert not any(line.startswith("install ") for p in (5, 6, 7) for line in ring.sparks[p].mutations) + assert ring.sparks[4].file_meta[MARKER.path] == (0, 0, 0o755) + assert not any("install " in line for p in (5, 6, 7) for line in ring.sparks[p].mutations) assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 0 @@ -512,3 +514,52 @@ def test_spark_diff_counts_and_script_order(ring): order = [k for i, k in enumerate(kinds) if i == 0 or kinds[i - 1] != k] assert order[:4] == [["tc", "qdisc"], ["tc", "filter"], ["ip", "neigh"], ["ip", "route"]] assert lines[-1] == commands.SETTLE + + +def test_marker_path_ownership_mode_and_sha256_verification(ring, site_file, capsys): + assert commands.DEFAULT_MARKER == "/usr/local/libexec/sparkring/ring8-mesh-marker" + build_script = commands.marker_build_script("spark0", MARKER, cli.MARKER_SOURCE.read_text(encoding="utf-8")) + assert "sudo -n install -d -o root -g root -m 0755 /usr/local/libexec/sparkring" in build_script + assert 'sudo -n install -o root -g root -m 0755 "$work/marker" /usr/local/libexec/sparkring/ring8-mesh-marker' in build_script + assert 'rm -f "$work/marker"' in build_script + + # Non-root owner blocks execution as root and `marker --apply` repairs it. + ring.sparks[4].file_meta[MARKER.path] = (1000, 1000, 0o755) + assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 3 + assert "owned by uid 1000, expected root (uid 0)" in capsys.readouterr().out + assert all(not m for m in ring.mutations().values()) + assert _cli(ring, site_file, "marker", "--sparks", "4", "--apply") == 0 + assert ring.sparks[4].file_meta[MARKER.path] == (0, 0, 0o755) + + # Group-writable and world-writable modes both block execution as root. + for bad_mode in (0o775, 0o757): + ring.clear_mutations() + ring.sparks[4].file_meta[MARKER.path] = (0, 0, bad_mode) + assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 3 + assert "group/world-writable mode" in capsys.readouterr().out + assert all(not m for m in ring.mutations().values()) + ring.sparks[4].file_meta[MARKER.path] = (0, 0, 0o755) + + # SHA-256 mismatch against recorded digest blocks execution and `marker --apply` repairs it. + ring.sparks[4].files[MARKER.path] = "\x7fELF tampered-binary" + assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 3 + assert "does not match recorded digest" in capsys.readouterr().out + assert _cli(ring, site_file, "marker", "--sparks", "4", "--apply") == 0 + assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 0 + + # Installed record records marker_sha256; tampering with both binary and sidecar still mismatches record. + record = json.loads(ring.sparks[4].files[commands.RECORD_PATH]) + assert "marker_sha256" in record and len(record["marker_sha256"]) == 64 + ring.sparks[4].files[MARKER.path] = "\x7fELF tampered-again" + del ring.sparks[4].files[MARKER.digest_path] + assert _cli(ring, site_file, "up", "--layout", "2xTP4", "--group", "1", "--apply") == 3 + assert "does not match state record" in capsys.readouterr().out + + # Explicit expected_sha256 on MarkerConfig also catches mismatch in diff.compare_up. + site = ring.site() + layout = layouts.resolve(ring_size=8, layout="2xTP4") + pinned = commands.MarkerConfig(expected_sha256="0" * 64) + states = ops.gather(site, range(4), ring.executor, pinned) + outcome = ops.evaluate(site, layout, layout.groups[:1], states, mode="up", marker=pinned, adopt=False) + assert outcome.blocked + assert any("does not match configured" in blocker for d in outcome.diffs for blocker in d.blockers) diff --git a/spark_transport/sircl/tests/test_fabric_plan.py b/spark_transport/sircl/tests/test_fabric_plan.py index 47b4ac4f..32d9abce 100644 --- a/spark_transport/sircl/tests/test_fabric_plan.py +++ b/spark_transport/sircl/tests/test_fabric_plan.py @@ -217,3 +217,65 @@ def test_tags_and_preferences(): relay_filter = _plan(layout="ring8").groups[0].spark(0).filters[0] assert (relay_filter.pref, relay_filter.handle) == (10 + relay_filter.k, relay_filter.k) assert list(plan.RESERVED_PREFS) == list(range(11, 18)) + + +def _chain_facts(size: int) -> plan.Facts: + """Facts for an open chain of ``size`` Sparks where endpoints only have their single cabled port.""" + sparks = [] + for pos in range(size): + ports = [] + if pos < size - 1: + ports.append(plan.Port("enp1s0f0np0", f"02:5c:{pos:02x}:00:00:01", f"198.18.{2 * pos}.1", 24)) + ports.append(plan.Port("enP2p1s0f0np0", f"02:5c:{pos:02x}:00:01:01", f"198.18.{2 * pos + 1}.1", 24)) + if pos > 0: + ports.append(plan.Port("enp1s0f1np1", f"02:5c:{pos:02x}:01:00:01", f"198.18.{2 * (pos - 1)}.2", 24)) + ports.append(plan.Port("enP2p1s0f1np1", f"02:5c:{pos:02x}:01:01:01", f"198.18.{2 * (pos - 1) + 1}.2", 24)) + sparks.append(plan.SparkFacts(pos, f"chain{pos}", tuple(ports))) + return plan.Facts(sparks) + + +def test_open_chain_relay_planning_for_2_3_and_4_nodes(): + # 2-node open chain: direct pair, no relays or markers. + facts2 = _chain_facts(2) + plan2 = plan.build_chain_plan((0, 1), facts2) + assert plan2.group.label == "pair:0-1" + assert all(not s.routes and not s.filters and not s.markers for s in plan2.sparks) + assert plan2.per_peer_bytes is None + assert plan.isolation_problems([plan2]) == [] + + # 3-node open chain: endpoints 0 and 2 have only 1 neighbor and relay exclusively via 1. + facts3 = _chain_facts(3) + plan3 = plan.build_chain_plan((0, 1, 2), facts3) + assert plan3.group.label == "path:0-1-2" + counts3 = {s.position: (len(s.routes), len(s.filters), len(s.markers)) for s in plan3.sparks} + assert counts3 == {0: (2, 0, 2), 1: (0, 4, 0), 2: (2, 0, 2)} + assert {r.netdev for r in plan3.spark(0).routes} == {"enp1s0f0np0", "enP2p1s0f0np0"} + assert {r.netdev for r in plan3.spark(2).routes} == {"enp1s0f1np1", "enP2p1s0f1np1"} + assert plan.isolation_problems([plan3]) == [] + + # 4-node open chain: endpoints 0 and 3 have 1 neighbor; inner nodes 1 and 2 relay both directions. + facts4 = _chain_facts(4) + plan4 = plan.build_chain_plan((0, 1, 2, 3), facts4) + assert plan4.group.label == "path:0-1-2-3" + counts4 = {s.position: (len(s.routes), len(s.filters), len(s.markers)) for s in plan4.sparks} + assert counts4 == {0: (4, 0, 2), 1: (2, 6, 2), 2: (2, 6, 2), 3: (4, 0, 2)} + assert plan.isolation_problems([plan4]) == [] + sparks4 = {s.position: s for s in plan4.sparks} + for spark in plan4.sparks: + for route in spark.routes: + traced = plan.trace(sparks4, facts4, None, spark.position, route.destination, + fabric=plan4.layout.fabric) + assert traced.outcome == "delivered" and traced.hops[-1] == (route.peer, route.peer_netdev) + + # Trace on an open chain refuses to wrap around an uncabled endpoint port. + bad_route = plan.OriginRoute( + destination=facts4.port(3, "enp1s0f1np1").address, netdev="enp1s0f1np1", device="rocep1s0f1", + source=facts4.port(0, "enp1s0f0np0").address, next_mac=facts4.port(3, "enp1s0f1np1").mac, + tag=plan.tag(0), peer=3, peer_netdev="enp1s0f1np1", hops=1, relays=(), cables=(), owned_cables=()) + bad_sparks = {0: plan.SparkPlan(0, "chain0", "path:0-1-2-3", (bad_route,), ())} + dropped = plan.trace(bad_sparks, facts4, 4, 0, bad_route.destination, fabric=plan4.layout.fabric) + assert dropped.outcome == "dropped" and "has no cable" in dropped.detail + + # Disjoint/closed fabric is rejected by build_chain_plan. + with pytest.raises(FabricError, match="connected path fabric"): + plan.build_chain_plan((0, 1, 2, 3), FACTS, fabric=routes.Fabric.ring(4)) diff --git a/spark_transport/sircl/tests/test_routes.py b/spark_transport/sircl/tests/test_routes.py index deb3d657..3dadf05f 100644 --- a/spark_transport/sircl/tests/test_routes.py +++ b/spark_transport/sircl/tests/test_routes.py @@ -233,3 +233,52 @@ def test_the_ring_over_a_path_closes_through_one_lane_per_relay_queue(): shared[3][0] = (maps[3][0][0], maps[3][0][0]) window, problems = r.ring_window(path, shared, order) assert problems and "carries ring lanes [(3, 0, 0), (3, 0, 1)]" in problems[0] + + +def test_disjoint_cycles_are_not_classified_as_a_single_cycle(): + two_pairs = r.Fabric.parse(["0.port0-1.port1", "1.port0-0.port1", "2.port0-3.port1", "3.port0-2.port1"]) + assert not two_pairs.connected() + assert two_pairs.kind == "disconnected" + two_triangles = r.Fabric.parse([ + "0.port0-1.port1", "1.port0-2.port1", "2.port0-0.port1", + "3.port0-4.port1", "4.port0-5.port1", "5.port0-3.port1", + ]) + assert not two_triangles.connected() + assert two_triangles.kind == "disconnected" + layout = r.Layout(two_pairs, (0, 1, 2, 3)) + assert r.chain_order(layout, [{}, {}, {}, {}]) is None + assert r.Fabric.ring(4).connected() and r.Fabric.ring(4).kind == "cycle" + assert r.Fabric.path((0, 1, 2, 3)).connected() and r.Fabric.path((0, 1, 2, 3)).kind == "path" + + +def test_validate_route_map_accepts_sparse_ring_only_neighbor_maps(): + known = [role.device for role in r.ROLES] + ring8 = r.Layout.parse("ring:8") + sparse_ring = r.derive_routes(ring8, 2, ring_only=True) + maps = [sparse_ring.route_map(rank) for rank in range(8)] + assert set(maps[0]) == {1, 7} + assert set(maps[3]) == {2, 4} + for rank, route_map in enumerate(maps): + assert r.validate_route_map(rank, 8, route_map, layout=ring8, available_devices=known, ring_only=True) == 2 + with pytest.raises(r.RouteError, match="has no entry for rank"): + r.validate_route_map(rank, 8, route_map, layout=ring8, available_devices=known) + assert r.check_complementary(ring8, maps) == [] + assert r.chain_order(ring8, maps) == tuple(range(8)) + + # Missing a ring neighbor is still rejected in ring_only mode. + with pytest.raises(r.RouteError, match="has no entry for rank 7"): + r.validate_route_map(0, 8, {1: maps[0][1]}, layout=ring8, ring_only=True) + + # Without a layout, ring_only requires immediate ring neighbors (rank +/- 1 mod world). + ring4_sparse = r.parse_peer_routes("1=rocep1s0f0/roceP2p1s0f0,3=rocep1s0f1/roceP2p1s0f1") + assert r.validate_route_map(0, 4, ring4_sparse, available_devices=known, ring_only=True) == 2 + + # Open chain (path) in ring_only mode: endpoints only require their single cable neighbor. + chain4 = r.Layout.parse("path:0-3") + sparse_chain = r.derive_routes(chain4, 2, ring_only=True) + chain_maps = [sparse_chain.route_map(rank) for rank in range(4)] + assert [set(m) for m in chain_maps] == [{1}, {0, 2}, {1, 3}, {2}] + for rank, route_map in enumerate(chain_maps): + assert r.validate_route_map(rank, 4, route_map, layout=chain4, available_devices=known, ring_only=True) == 2 + assert r.check_complementary(chain4, chain_maps) == [] + assert r.chain_order(chain4, chain_maps) == (0, 1, 2, 3) From 298af8a8541f3c33b63009364deb4c9f9c89b162 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:37:37 -0600 Subject: [PATCH 2/3] host: harden privilege boundaries, dashboard/helper/sshd, agent yield, and 6/8-Spark hairpin check --- packaging/debian/sparkring-access.service | 10 +- packaging/debian/sparkring-dashboard.service | 9 +- packaging/debian/sparkring-helper.socket | 2 + packaging/debian/sparkring-seed.service | 10 +- runtime/host/control_node.py | 38 +++-- runtime/host/dashboard.py | 60 ++++++-- runtime/host/dashboard_admin.py | 13 +- runtime/host/dashboard_tui.py | 8 +- runtime/host/helper.py | 69 ++++++++- runtime/host/install_workflow.py | 17 ++- runtime/host/node.py | 148 +++++++++++++++++-- runtime/host/privilege.py | 3 + runtime/host/recovery.py | 32 ++-- runtime/host/relays.py | 34 ++++- runtime/host/seed.py | 25 +++- runtime/host/test_control.py | 32 ++++ runtime/host/test_dashboard.py | 67 ++++++++- runtime/host/test_dashboard_admin.py | 3 +- runtime/host/test_dashboard_tui.py | 3 +- runtime/host/test_helper.py | 37 +++++ runtime/host/test_install_workflow.py | 16 ++ runtime/host/test_persistence.py | 5 + runtime/host/test_privilege.py | 38 +++++ runtime/host/test_recovery.py | 47 ++++++ runtime/host/test_relays.py | 82 ++++++++++ 25 files changed, 718 insertions(+), 90 deletions(-) diff --git a/packaging/debian/sparkring-access.service b/packaging/debian/sparkring-access.service index 82de7708..dd390251 100644 --- a/packaging/debian/sparkring-access.service +++ b/packaging/debian/sparkring-access.service @@ -12,9 +12,17 @@ ConditionPathExists=/sys/class/net/sr-control [Service] Type=simple ExecStartPre=/usr/bin/mkdir -p /run/sshd -ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/sshd_config +ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/sshd_config -o AllowTcpForwarding=no -o PermitTunnel=no -o GatewayPorts=no Restart=on-failure RestartSec=5 +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectClock=yes +ProtectHostname=yes +LockPersonality=yes +RestrictRealtime=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +SystemCallArchitectures=native [Install] WantedBy=multi-user.target diff --git a/packaging/debian/sparkring-dashboard.service b/packaging/debian/sparkring-dashboard.service index f4887ef8..78f5711a 100644 --- a/packaging/debian/sparkring-dashboard.service +++ b/packaging/debian/sparkring-dashboard.service @@ -10,15 +10,18 @@ ConditionPathExists=!/etc/sparkring/dashboard.disabled [Service] Type=simple -ExecStart=/usr/bin/sparkring dashboard serve +# Safe default: bind to loopback only unless an operator drop-in supplies +# --password-file /etc/sparkring/dashboard.password (or --allow-unauthenticated-lan). +ExecStart=/usr/bin/sparkring dashboard serve --bind 127.0.0.1 # systemctl reload: re-read the fabric document and the site file at once. sparkring dashboard # export, install, up, down and automatic recovery reload it after they write the site file. ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure RestartSec=30 -# Unprivileged: the fabric document, the site file, the host-agent status and the recovery -# record it reads are mode 0644. It holds no SSH key and starts no process. +# Unprivileged: runs as a dynamic user in the sparkring group to read mode 0640 +# status, recovery, site and node-report files. It holds no SSH key and starts no process. DynamicUser=yes +SupplementaryGroups=sparkring RuntimeDirectory=sparkring-dashboard RuntimeDirectoryMode=0755 CapabilityBoundingSet= diff --git a/packaging/debian/sparkring-helper.socket b/packaging/debian/sparkring-helper.socket index 9a5d650f..d70836ec 100644 --- a/packaging/debian/sparkring-helper.socket +++ b/packaging/debian/sparkring-helper.socket @@ -11,6 +11,8 @@ ListenStream=/run/sparkring/helper.sock SocketGroup=sparkring SocketMode=0660 Accept=yes +MaxConnections=16 +MaxConnectionsPerSource=4 RemoveOnStop=yes [Install] diff --git a/packaging/debian/sparkring-seed.service b/packaging/debian/sparkring-seed.service index 8b63b87d..b310a3d7 100644 --- a/packaging/debian/sparkring-seed.service +++ b/packaging/debian/sparkring-seed.service @@ -7,9 +7,17 @@ ConditionPathExists=/etc/sparkring/seed_sshd_config [Service] Type=simple ExecStartPre=/usr/bin/mkdir -p /run/sshd -ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/seed_sshd_config +ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/seed_sshd_config -o AllowTcpForwarding=no -o PermitTunnel=no -o GatewayPorts=no Restart=on-failure RestartSec=5 +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectClock=yes +ProtectHostname=yes +LockPersonality=yes +RestrictRealtime=yes +RestrictAddressFamilies=AF_INET6 AF_UNIX +SystemCallArchitectures=native [Install] WantedBy=multi-user.target diff --git a/runtime/host/control_node.py b/runtime/host/control_node.py index e68e0104..d4e2e024 100644 --- a/runtime/host/control_node.py +++ b/runtime/host/control_node.py @@ -21,10 +21,8 @@ def write(path, text, *, root="/", mode=0o600): destination = node.location(root, path) destination.parent.mkdir(parents=True, exist_ok=True) - temporary = node.location(root, str(destination.relative_to(root)) + ".writing") - temporary.write_text(text, encoding="utf-8", newline="\n") - temporary.chmod(mode) - temporary.replace(destination) + node.write_text_atomic(destination, text, mode=mode) + return destination def public_key(*, root="/", run=subprocess.run): @@ -327,7 +325,10 @@ def configure(document, *, root="/", run=subprocess.run): AllowUsers root UsePAM yes AllowAgentForwarding no -AllowTcpForwarding yes +AllowTcpForwarding no +AllowStreamLocalForwarding no +GatewayPorts no +PermitTunnel no X11Forwarding no PermitUserRC no Subsystem sftp internal-sftp @@ -354,19 +355,13 @@ def configure(document, *, root="/", run=subprocess.run): def _write_private(name, text, *, root): """Write a root-only file (0600) below a root-only directory (0700); return its path. - The file is created with its final mode, so the private key it carries is - never readable by another user. + The file is created with its final mode before any secret byte is written, + so the private key it carries is never readable by another user. """ destination = node.location(root, name) - destination.parent.mkdir(parents=True, exist_ok=True) + destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) os.chmod(destination.parent, 0o700) - temporary = node.location(root, name + ".writing") - descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: - stream.write(text) - os.chmod(temporary, 0o600) - os.replace(temporary, destination) - return destination + return node.write_text_atomic(destination, text, mode=0o600) def up(*, root="/", run=subprocess.run, now=time.time, contact=probe, say=None): @@ -467,8 +462,7 @@ def ssh_config(configs, keys, identity_file, *, home=None): for path, text in ((include, "\n".join(rows) + "\nHost *\n"), (known, "\n".join(hosts) + "\n")): if path.is_symlink() or path.exists() and path.read_text() != text: raise ValueError("Another controller SSH configuration exists: " + str(path)) - path.write_text(text) - path.chmod(0o600) + node.write_text_atomic(path, text, mode=0o600) settings = directory / "config" if settings.is_symlink(): raise ValueError("SSH config is a symlink; add the SparkRing include explicitly") @@ -477,8 +471,10 @@ def ssh_config(configs, keys, identity_file, *, home=None): if not text.startswith(line): if settings.exists(): backup = directory / ("config.before-sparkring-" + str(os.getpid())) - with backup.open("x") as stream: + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(backup, flags, 0o600) + if hasattr(os, "fchmod"): + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: stream.write(text) - backup.chmod(0o600) - settings.write_text(line + text) - settings.chmod(0o600) + node.write_text_atomic(settings, line + text, mode=0o600) diff --git a/runtime/host/dashboard.py b/runtime/host/dashboard.py index d6890fcd..5bcb3490 100644 --- a/runtime/host/dashboard.py +++ b/runtime/host/dashboard.py @@ -88,6 +88,7 @@ from functools import lru_cache import gzip import hashlib +import hmac from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import ipaddress import json @@ -2014,7 +2015,8 @@ def make_handler(collector: Collector, page: bytes, csp: str, names=frozenset(), manager=None): headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "X-Frame-Options": "DENY"} - expected = None if password is None else "Basic " + base64.b64encode(f"sparkring:{password}".encode()).decode() + expected = (None if password is None + else ("Basic " + base64.b64encode(f"sparkring:{password}".encode("utf-8")).decode("ascii")).encode("utf-8")) class Handler(BaseHTTPRequestHandler): server_version = "sparkring-dashboard" @@ -2023,7 +2025,10 @@ def do_GET(self): if not host_allowed(self.headers.get("Host"), names): return self._send(421, b"This dashboard answers to its IP address or a name given with --name.\n", "text/plain; charset=utf-8") - if (expected is not None and self.headers.get("Authorization") != expected + auth_header = self.headers.get("Authorization") + auth_ok = (auth_header is not None + and hmac.compare_digest(auth_header.encode("utf-8", "replace"), expected)) if expected is not None else True + if (expected is not None and not auth_ok and not (manager and manager.authenticated(self.headers))): self.send_response(401) self.send_header("WWW-Authenticate", 'Basic realm="SparkRing dashboard", charset="UTF-8"') @@ -2110,22 +2115,39 @@ def log_message(self, *args): return Handler -def default_bind(source: Source) -> str: - """On Node A, its LAN address from the fabric document (where its model API serves; else its - management address); on any other host, loopback. ``listen_addresses`` adds loopback to it.""" +def is_loopback_bind(bind: str) -> bool: + """Whether ``bind`` names a loopback interface (``127.0.0.0/8``, ``::1``, or ``localhost``).""" + text = bind.strip() + if text.lower() == "localhost": + return True + try: + return ipaddress.ip_address(text).is_loopback + except ValueError: + return False + + +def default_bind(source: Source, *, authenticated: bool = False, + allow_unauthenticated_lan: bool = False) -> str: + """Default listen address: ``127.0.0.1`` unless authentication (``--password-file``) or + ``--allow-unauthenticated-lan`` is enabled, in which case Node A uses its LAN address + from the fabric document (else its management address).""" + if not authenticated and not allow_unauthenticated_lan: + return "127.0.0.1" rows = (source.fabric or {}).get("positions") or [] if rows and socket.gethostname() == rows[0]["hostname"]: return rows[0].get("lan_address") or rows[0].get("address") or "127.0.0.1" return "127.0.0.1" -def service_url(fabric_path: Path = FABRIC_PATH) -> str: +def service_url(fabric_path: Path = FABRIC_PATH, *, authenticated: bool = False, + allow_unauthenticated_lan: bool = False) -> str: """The address of the dashboard service on this Spark, by the service's default bind rule - (``default_bind``): Node A's LAN address, else loopback. A ``--bind`` given to the service - is not visible here.""" + (``default_bind``): loopback by default, or Node A's LAN address when authenticated or + explicitly opted in.""" source = Source(fabric_path, SITE_PATH) source.refresh() - bind = default_bind(source) + bind = default_bind(source, authenticated=authenticated, + allow_unauthenticated_lan=allow_unauthenticated_lan) literal = f"[{bind}]" if ":" in bind else bind return f"http://{literal}:{DEFAULT_PORT}" @@ -2201,7 +2223,18 @@ def serve(args) -> int: password = Path(args.password_file).read_text(encoding="utf-8").strip() if not password: raise ValueError(f"{args.password_file} is empty") - bind = args.bind or default_bind(sources[0]) + allow_unauthenticated_lan = bool(getattr(args, "allow_unauthenticated_lan", False)) + requested_bind = getattr(args, "bind", None) or getattr(args, "host", None) + if requested_bind: + if not is_loopback_bind(requested_bind) and password is None and not allow_unauthenticated_lan: + raise ValueError( + f"Refusing to bind unauthenticated dashboard to non-loopback address {requested_bind!r}; " + "configure --password-file PATH or opt in explicitly with --allow-unauthenticated-lan" + ) + bind = requested_bind + else: + bind = default_bind(sources[0], authenticated=password is not None, + allow_unauthenticated_lan=allow_unauthenticated_lan) page, csp = page_bytes() names = frozenset(name.lower() for name in args.name or ()) servers = open_servers(listen_addresses(bind), args.port, make_handler(collector, page, csp, names, password, manager)) @@ -2318,13 +2351,16 @@ def main(argv=None) -> int: "no SSH.")) commands = parser.add_subparsers(dest="command", required=True) run = commands.add_parser("serve", help="collect and serve the page") - run.add_argument("--bind", help="listen address (default: Node A's LAN address, else 127.0.0.1); 127.0.0.1 " - "is added unless the address is loopback or a wildcard") + run.add_argument("--bind", "--host", dest="bind", + help="listen address (default: 127.0.0.1; with --password-file or --allow-unauthenticated-lan, " + "Node A's LAN address); 127.0.0.1 is added unless the address is loopback or a wildcard") run.add_argument("--port", type=int, default=DEFAULT_PORT) run.add_argument("--fabric", action="append", type=Path, help="fabric document (repeat with --site per fabric)") run.add_argument("--site", action="append", type=Path, help="site file written by export") run.add_argument("--name", action="append", help="a host name browsers may use for this page") run.add_argument("--password-file", help="require HTTP Basic authentication (user sparkring) with this password") + run.add_argument("--allow-unauthenticated-lan", action="store_true", + help="opt in to binding the dashboard on a non-loopback address without --password-file") run.add_argument("--manage", action="store_true", help="opt in to authenticated actions through the privileged helper") run.add_argument("--manage-token-file", help="file containing the management bearer token (at least 32 characters)") run.add_argument("--cpus", help="CPU list to run on, such as 0-4,10-14 (default: the efficiency cores)") diff --git a/runtime/host/dashboard_admin.py b/runtime/host/dashboard_admin.py index b8913477..e39bcd4e 100644 --- a/runtime/host/dashboard_admin.py +++ b/runtime/host/dashboard_admin.py @@ -4,7 +4,7 @@ The actions here run as root, in the operator's commands: - ``write_site`` turns the controller's deployment records (root only) into the site file - (``sparkring-dashboard-site/v1``, 0644) that the collector reads. + (``sparkring-dashboard-site/v1``, 0640, group ``sparkring``) that the collector reads. - ``refresh_site`` is called by ``sparkring install``, ``up``, ``down``, setup and automatic recovery when they finish, so the page follows every change of deployment records. It writes the site file, then asks the running service to re-read it (``reload_service``). It never @@ -66,7 +66,9 @@ def refresh_nodes(*, state_root=None, output=None, invoke=None, quiet_path=None, with process_lock.hold(output.with_suffix(".lock")): documents = recovery.node_documents(hosts, invoke=invoke) public = cached_node_rows(state_root, output, documents, now()) - node.save(output.parent, output.name, {"schema": "sparkring-dashboard-nodes/v1", "written_at": now(), "nodes": public}) + node.save(output.parent, output.name, {"schema": "sparkring-dashboard-nodes/v1", "written_at": now(), "nodes": public}, mode=0o640) + from runtime.host import privilege + privilege.share(output, 0o640) return documents except (OSError, ValueError, KeyError, TypeError) as error: _stderr(f"Dashboard: agent facts could not be cached ({type(error).__name__})") @@ -288,11 +290,12 @@ def external(args) -> int: def write_site(output: Path | None = None) -> dict: - """Write the site file from this controller's records; returns the document.""" - from runtime.host import controller, node + """Write the site file from this controller's records (mode 0640, group sparkring); returns the document.""" + from runtime.host import controller, node, privilege site = site_from_records(controller.STATE) output = Path(output or SITE_PATH) - node.save(output.parent, output.name, site, mode=0o644) + node.save(output.parent, output.name, site, mode=0o640) + privilege.share(output, 0o640) return site diff --git a/runtime/host/dashboard_tui.py b/runtime/host/dashboard_tui.py index b4c4889d..44193bfc 100644 --- a/runtime/host/dashboard_tui.py +++ b/runtime/host/dashboard_tui.py @@ -628,10 +628,12 @@ def local_url(fabric_path: Path = dashboard.FABRIC_PATH) -> str: def default_urls(fabric_path: Path = dashboard.FABRIC_PATH) -> list: - """Loopback first, then the service's own listen address on this Spark when it differs.""" + """Loopback first, then Node A's LAN listen address if the service was configured to expose it.""" urls = [LOOPBACK_URL] - own = local_url(fabric_path) - return urls + ([own] if own not in urls else []) + for candidate in (local_url(fabric_path), dashboard.service_url(fabric_path, allow_unauthenticated_lan=True)): + if candidate not in urls: + urls.append(candidate) + return urls class Reader: diff --git a/runtime/host/helper.py b/runtime/host/helper.py index 06007335..787258c1 100644 --- a/runtime/host/helper.py +++ b/runtime/host/helper.py @@ -30,6 +30,7 @@ import struct import subprocess import sys +import threading import time SOCKET_PATH = "/run/sparkring/helper.sock" @@ -38,6 +39,10 @@ # One request line; a larger request is refused before anything runs. LINE_LIMIT = 1 << 20 REQUEST_TIMEOUT = 15.0 +EXEC_TIMEOUT = 3600 +# Cap retained output per stream (stdout/stderr) so a runaway child cannot OOM the host. +MAX_STREAM_BYTES = 1 << 20 +TRUNCATION_MARKER = "\n[sparkring-helper: output truncated after byte limit]\n" # A profile or instance name, and an arc such as 0,1 or 2-3, as values. PROFILE = ("re", re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")) @@ -91,7 +96,60 @@ def audit_line(peer_uid, argv, exit_code) -> str: "argv": argv, "exit": exit_code}) -def serve(connection: socket.socket, *, spawn=None, argv0=SPARKRING, out=None): +def _bound_text(text: str | None, max_bytes: int = MAX_STREAM_BYTES) -> str: + if not text: + return "" + raw = text.encode("utf-8", errors="replace") + if len(raw) <= max_bytes: + return text + return raw[:max_bytes].decode("utf-8", errors="ignore") + TRUNCATION_MARKER + + +def _run_bounded(argv, *, argv0=SPARKRING, timeout=EXEC_TIMEOUT, max_bytes=MAX_STREAM_BYTES): + """Run ``[argv0, *argv]`` draining stdout and stderr concurrently with a strict byte cap per stream.""" + command = [argv0, *argv] + proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + captured = {"out": bytearray(), "err": bytearray()} + truncated = {"out": False, "err": False} + + def drain(pipe, key): + try: + while True: + chunk = pipe.read(4096) + if not chunk: + break + remaining = max_bytes - len(captured[key]) + if remaining > 0: + captured[key].extend(chunk[:remaining]) + if len(chunk) > remaining: + truncated[key] = True + else: + truncated[key] = True + finally: + pipe.close() + + threads = [ + threading.Thread(target=drain, args=(proc.stdout, "out"), daemon=True), + threading.Thread(target=drain, args=(proc.stderr, "err"), daemon=True), + ] + for thread in threads: + thread.start() + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + for thread in threads: + thread.join(timeout=5) + raise + for thread in threads: + thread.join() + stdout = captured["out"].decode("utf-8", errors="replace") + (TRUNCATION_MARKER if truncated["out"] else "") + stderr = captured["err"].decode("utf-8", errors="replace") + (TRUNCATION_MARKER if truncated["err"] else "") + return subprocess.CompletedProcess(command, proc.returncode, stdout, stderr) + + +def serve(connection: socket.socket, *, spawn=None, argv0=SPARKRING, out=None, max_bytes=MAX_STREAM_BYTES): """Handle one connection: validate, run, stream, audit; never raises to the socket. Each response is one JSON line: ``{"type": "output", "stream": @@ -100,7 +158,7 @@ def serve(connection: socket.socket, *, spawn=None, argv0=SPARKRING, out=None): refused or the child could not start). """ stream = out or sys.stdout - run = spawn or (lambda argv: subprocess.run([argv0, *argv], capture_output=True, text=True, timeout=3600)) + run = spawn or (lambda argv: _run_bounded(argv, argv0=argv0, timeout=EXEC_TIMEOUT, max_bytes=max_bytes)) peer_uid = None argv = None try: @@ -120,8 +178,9 @@ def serve(connection: socket.socket, *, spawn=None, argv0=SPARKRING, out=None): try: result = run(argv) code, error = result.returncode, None - for name, text in (("out", result.stdout), ("err", result.stderr)): - for start in range(0, len(text or ""), 4096): + for name, raw_text in (("out", result.stdout), ("err", result.stderr)): + text = _bound_text(raw_text, max_bytes=max_bytes) if spawn is not None else (raw_text or "") + for start in range(0, len(text), 4096): _send(connection, {"type": "output", "stream": name, "text": text[start:start + 4096]}) except (OSError, subprocess.SubprocessError) as exc: code, error = 2, str(exc) @@ -135,6 +194,8 @@ def serve(connection: socket.socket, *, spawn=None, argv0=SPARKRING, out=None): def _peer_uid(connection: socket.socket): """The connecting process's uid, from the kernel's peer credentials (Linux).""" + if not hasattr(socket, "SO_PEERCRED"): + return None try: _, uid, _ = struct.unpack("3i", connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) except OSError: diff --git a/runtime/host/install_workflow.py b/runtime/host/install_workflow.py index c0f92a0f..8fa30074 100644 --- a/runtime/host/install_workflow.py +++ b/runtime/host/install_workflow.py @@ -57,6 +57,7 @@ import os import shlex import subprocess +import re import sys import time from pathlib import Path, PurePosixPath @@ -127,6 +128,17 @@ def require_head(cluster=None, *, command="install"): return identity +def sudoers_filename(user: str) -> str: + """Return a valid ``/etc/sudoers.d/`` filename for ``user``. + + ``sudo`` silently ignores files in ``/etc/sudoers.d/`` containing ``.`` or + ending in ``~``, so both characters (and any other unsafe characters) are + replaced with ``_``. + """ + sanitized = re.sub(r"[^A-Za-z0-9_-]", "_", user.replace(".", "_").replace("~", "_")).strip("_") + return f"sparkring-{sanitized or 'user'}" + + def check_access(cluster, *, invoke=None): """Confirm noninteractive SSH and sudo on every enrolled Spark before any change. @@ -140,9 +152,10 @@ def check_access(cluster, *, invoke=None): invoke(row["host"], ["sudo", "-n", "true"]) except (RuntimeError, OSError, subprocess.SubprocessError) as error: user = row["host"].split("@", 1)[0] if "@" in row["host"] else "USER" + filename = sudoers_filename(user) missing.append({"rank": rank, "host": row["host"], "error": str(error).splitlines()[-1][:200], - "fix": f"ssh -t {row['host']} \"echo '{user} ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/{user} " - f"&& sudo chmod 440 /etc/sudoers.d/{user} && sudo visudo -cf /etc/sudoers.d/{user}\""}) + "fix": f"ssh -t {row['host']} \"echo '{user} ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/{filename} " + f"&& sudo chmod 440 /etc/sudoers.d/{filename} && sudo visudo -cf /etc/sudoers.d/{filename}\""}) if missing: raise NeedsInput("Some Sparks need noninteractive SSH and sudo for the installer. Run each listed fix once " "(it asks for that Spark's password), then repeat the install. Nothing has been changed.", diff --git a/runtime/host/node.py b/runtime/host/node.py index e73ebfdb..26d96b56 100644 --- a/runtime/host/node.py +++ b/runtime/host/node.py @@ -45,6 +45,9 @@ FABRIC_UNIT = "sparkring-fabric.service" # The service that runs the relay table's marker processes (runtime/host/relays.py). MARKER_UNIT = relay_table.MARKER_UNIT +# State record written by `sparkring-sircl fabric up --apply` while it owns proto 82 objects. +SIRCL_FABRIC_RECORD = "/run/sparkring-fabric/relay-state.json" +SIRCL_FABRIC_SCHEMA = "sparkring-fabric-relay-record/v1" # Fields of a fabric record that a setup of the same Sparks may replace in place. REFRESHED_FIELDS = ("layout", "relays") # Setup hashes change with observations; the saved ID also owns firewall rules. @@ -76,15 +79,34 @@ def read(root, name): return json.loads(location(root, name).read_text(encoding="utf-8")) -def save(root, name, value, mode=0o644): - path = location(root, name) +def write_text_atomic(path, text, *, mode=0o644): + """Write ``text`` to ``path`` atomically, creating the temporary file with ``mode`` before any byte is written.""" + path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".writing") - location(root, temporary.relative_to(Path(root))) - with temporary.open("w", encoding="utf-8", newline="\n") as stream: - stream.write(json.dumps(value, indent=2) + "\n") - temporary.chmod(mode) - temporary.replace(path) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(temporary, flags, mode) + try: + if hasattr(os, "fchmod"): + os.fchmod(descriptor, mode) + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + descriptor = None + stream.write(text) + except BaseException: + if descriptor is not None: + os.close(descriptor) + temporary.unlink(missing_ok=True) + raise + os.replace(temporary, path) + return path + + +def save(root, name, value, mode=0o640): + path = location(root, name) + path.parent.mkdir(parents=True, exist_ok=True) + temporary_check = path.with_name(path.name + ".writing") + location(root, temporary_check.relative_to(Path(root))) + write_text_atomic(path, json.dumps(value, indent=2) + "\n", mode=mode) def call(argv, *, run=subprocess.run, accepted=(0,)): @@ -395,6 +417,86 @@ def apply_settings(config, *, root="/", run=subprocess.run, log=_log): return rows +def _sircl_marker_pids(marker_path, *, root="/", explicit_pids=()): + """Live PIDs under ``root/proc`` matching a ``sparkring-sircl fabric`` marker or explicit PIDs.""" + proc = Path(root) / "proc" + if not proc.is_dir(): + return [] + found = set() + for pid in explicit_pids: + if type(pid) is int and pid > 0 and (proc / str(pid)).is_dir(): + found.add(pid) + marker_name = PurePosixPath(str(marker_path or "ring8-mesh-marker")).name + marker_comm = marker_name[:15] + try: + entries = list(proc.iterdir()) + except OSError: + return sorted(found) + for entry in entries: + if not entry.name.isdigit(): + continue + pid = int(entry.name) + try: + raw_cmd = (entry / "cmdline").read_bytes() + except OSError: + raw_cmd = b"" + argv = [part.decode(errors="replace") for part in raw_cmd.split(b"\0") if part] + if argv and PurePosixPath(argv[0]).name == marker_name and "--managed" in argv: + found.add(pid) + continue + try: + comm = (entry / "comm").read_text(encoding="utf-8", errors="replace").strip() + except OSError: + comm = "" + if comm and comm == marker_comm: + found.add(pid) + return sorted(found) + + +def sircl_fabric_session(*, root="/"): + """Return active ``sparkring-sircl fabric`` ownership details from ``/run/sparkring-fabric/relay-state.json``, or None. + + A record is considered active when it has schema ``sparkring-fabric-relay-record/v1`` + (and is not explicitly marked ``active: false``) AND either: + - at least one matching marker process (or listed PID) is alive under ``/proc``; or + - the record explicitly declares active ownership (``ownership == "active"`` or ``active is True``). + + A leftover record whose marker processes are all gone is treated as stale + (returns None) so ``sparkring-agent`` resumes normal upkeep instead of staying yielded. + """ + try: + record_path = location(root, SIRCL_FABRIC_RECORD) + if not record_path.exists(): + return None + record = json.loads(record_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(record, dict) or record.get("schema") != SIRCL_FABRIC_SCHEMA: + return None + if record.get("active") is False: + return None + explicit = [] + if type(record.get("pid")) is int: + explicit.append(record["pid"]) + if isinstance(record.get("marker_pids"), list): + explicit.extend(p for p in record["marker_pids"] if type(p) is int) + pids = _sircl_marker_pids(record.get("marker"), root=root, explicit_pids=explicit) + if pids: + reason = "live-marker" + elif record.get("ownership") == "active" or record.get("active") is True: + reason = "active-ownership" + else: + return None + return { + "group": record.get("group"), + "layout": record.get("layout"), + "plan": record.get("plan"), + "marker": record.get("marker"), + "marker_pids": pids, + "reason": reason, + } + + def restore_fabric(config, *, root="/", run=subprocess.run, log=_log): """Add the approved fabric routes of ``config`` that are missing and set its per-interface settings that differ. @@ -426,18 +528,29 @@ def restore_fabric(config, *, root="/", run=subprocess.run, log=_log): - Relay table (``relays.restore``): a function's relay routes leave with its address, and a driver restart removes its ingress queue and filters; the record's objects are added again once the link is up. + - SIRCL fabric ownership: when ``/run/sparkring-fabric/relay-state.json`` + indicates an active ``sparkring-sircl fabric`` session, restoration + yields cleanly instead of overwriting proto 82 objects. Returns None for a record without routes, forwarding and relays (a - pair, or an adopted fabric); ``{"active": False, "routes": [], - "settings": []}`` while the service is not active; else ``{"active": - True, "routes": add_routes(...), "settings": apply_settings(...)}``, - with ``relays`` (``relays.restore`` rows) for a record with a relay table. + pair, or an adopted fabric); ``{"active": False, "yielded_to_sircl_fabric": + True, ...}`` while ``sparkring-sircl fabric`` owns the host; ``{"active": + False, "routes": [], "settings": []}`` while the service is not active; + else ``{"active": True, "routes": add_routes(...), "settings": + apply_settings(...)}``, with ``relays`` (``relays.restore`` rows) for a + record with a relay table. """ validate(config) table = config.get("relays") observed = config.get("ownership") == "observed" if observed and not table or not (config["routes"] or config["forwarding"] or table): return None + sircl = sircl_fabric_session(root=root) + if sircl is not None: + log(f"yielding fabric restoration to active sparkring-sircl fabric session " + f"({sircl.get('group') or sircl.get('layout') or 'active'})") + return {"active": False, "yielded_to_sircl_fabric": True, "sircl_fabric": sircl, + "routes": [], "settings": []} if call(["systemctl", "is-active", FABRIC_UNIT], run=run, accepted=(0, 3)).returncode: return {"active": False, "routes": [], "settings": []} # An adopted fabric (observed) has no routes or settings of its own; only its relay table returns. @@ -1134,6 +1247,10 @@ def snapshot(*, root="/", collect=_collect_local, run=subprocess.run, now=time.t warnings.append("hairpin approval on a Spark that does not relay between its cables: " "sudo sparkring node hairpin revoke") validate(config) + sircl = sircl_fabric_session(root=root) + if sircl is not None: + result["yielded_to_sircl_fabric"] = True + result["sircl_fabric"] = sircl restoration = None if repair: try: @@ -1153,7 +1270,8 @@ def snapshot(*, root="/", collect=_collect_local, run=subprocess.run, now=time.t check_hairpin(config, facts, warnings, root=root, run=run) active = config.get("ownership") == "observed" or not call( ["systemctl", "is-active", FABRIC_UNIT], run=run, accepted=(0, 3)).returncode - verify_persistence(config, facts, run=run, restoration=restoration, active=active, root=root) + if sircl is None: + verify_persistence(config, facts, run=run, restoration=restoration, active=active, root=root) if config.get("ownership") == "observed" and config.get("native_mesh"): from runtime.common import qwen_mesh from runtime.host import native_mesh @@ -1162,7 +1280,7 @@ def snapshot(*, root="/", collect=_collect_local, run=subprocess.run, now=time.t if not parked_mesh(mesh.get("reference"), native_mesh.parked_units(root=root), (result.get("mesh") or {}).get("active") or ()): qwen_mesh.check(mesh["reference"], config["rank"], mesh["hcas"], 3, mesh["host_ip"]) - elif not active: + elif not active and sircl is None: raise ValueError("Fabric service is not active; inspect journalctl -u sparkring-fabric") result.update(state="network-configured", next_action="sparkring models", containers=[{"name": c.get("name"), "state": c.get("state")} for c in (facts["docker"].get("containers") or [])], @@ -1217,7 +1335,9 @@ def agent(*, root="/", once=False, sleep=time.sleep): interval = host_load.agent_interval(document, root=root) if interval != AGENT_INTERVAL: document = {**document, "interval_seconds": interval} - save(root, "/run/sparkring/status.json", document) + save(root, "/run/sparkring/status.json", document, mode=0o640) + from runtime.host import privilege + privilege.share(location(root, "/run/sparkring/status.json"), 0o640) if once: return waited = 0 diff --git a/runtime/host/privilege.py b/runtime/host/privilege.py index 144a7eac..38611121 100644 --- a/runtime/host/privilege.py +++ b/runtime/host/privilege.py @@ -8,6 +8,9 @@ publish for them: - the host agent's observation, ``/run/sparkring/status.json`` (mode 0640); +- the automatic recovery record, ``/var/lib/sparkring/recovery.json`` (mode 0640); +- the dashboard site and cached node files under ``/var/lib/sparkring/dashboard`` + (``site.json`` and ``nodes.json``, mode 0640); - the installation logs under ``/var/log/sparkring`` (mode 0640); - the operator view of the controller's status, ``/var/lib/sparkring/operator-status.json`` (mode 0640), whose site diff --git a/runtime/host/recovery.py b/runtime/host/recovery.py index 5430f021..bce10567 100644 --- a/runtime/host/recovery.py +++ b/runtime/host/recovery.py @@ -166,18 +166,30 @@ def load(*, repair=False): def _write(document): - """Replace the recovery file atomically; its content and the rename reach the disk before this returns.""" + """Replace the recovery file atomically (mode 0640); its content and the rename reach disk before this returns.""" + from runtime.host import privilege file = path() if any(item.is_symlink() for item in (file, *file.parents)): raise ValueError("Recovery state path contains a symlink: " + str(file)) file.parent.mkdir(parents=True, exist_ok=True) - temporary = file.with_name(file.name + ".writing") - with open(temporary, "w", encoding="utf-8", newline="\n") as stream: - stream.write(json.dumps(document, indent=2) + "\n") - stream.flush() - os.fsync(stream.fileno()) - os.chmod(temporary, 0o644) + temporary = file.with_name(f"{file.name}.{os.getpid()}.{time.time_ns()}.writing") + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(temporary, flags, 0o640) + try: + if hasattr(os, "fchmod"): + os.fchmod(descriptor, 0o640) + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + descriptor = None + stream.write(json.dumps(document, indent=2) + "\n") + stream.flush() + os.fsync(stream.fileno()) + except BaseException: + if descriptor is not None: + os.close(descriptor) + temporary.unlink(missing_ok=True) + raise os.replace(temporary, file) + privilege.share(file, 0o640) try: descriptor = os.open(file.parent, os.O_RDONLY) except OSError: @@ -906,9 +918,9 @@ def attempt(directory, lock, state, finding, *, now=time.time, apply=None, invok if finding["action"] is None: update(directory, finding=shown, pending=None) return _outcome("changed", "Observed again before acting: " + finding["summary"], directory, finding=shown) - if len(lock["site"]["ranks"]) == 4: - # retained_source.apply does not check the hairpin setting; up does, for the Sparks that relay - # the group's lanes (every relaying Spark for a model on the whole fabric). + if len(lock["site"]["ranks"]) >= 3: + # retained_source.apply does not check the hairpin setting; up does, for every + # relaying Spark on multi-rank ring/path layouts (3-, 4-, 6-, and 8-Spark clusters). from runtime.host import placement problem = controller._hairpin_problem(placement.from_lock(lock)) if problem: diff --git a/runtime/host/relays.py b/runtime/host/relays.py index 7cc2ad72..5626161e 100644 --- a/runtime/host/relays.py +++ b/runtime/host/relays.py @@ -337,11 +337,14 @@ def _route_present(rows, route): and row.get("prefsrc") == route["src"] and not row.get("gateway") for row in rows) +def _is_proto82(row): + return str(row.get("protocol")) in (str(ROUTE_PROTOCOL), "sparkring") + + def _route_conflict(rows, route): - """Another route to the destination that SparkRing does not own (protocol 82).""" + """Another route to the destination that differs from the planned route, including proto 82 from another owner.""" destination = route["dst"].split("/")[0] - return [row for row in rows if row.get("dst") in (destination, route["dst"]) and not _route_present([row], route) - and str(row.get("protocol")) not in (str(ROUTE_PROTOCOL), "sparkring")] + return [row for row in rows if row.get("dst") in (destination, route["dst"]) and not _route_present([row], route)] def _neighbour_present(rows, neighbour): @@ -398,10 +401,17 @@ def restore(value, *, call, root="/", log=None): rows.append({"kind": "filter", "dev": netdev, "pref": rule["pref"], "state": "restored"}) routes = _route_rows(call) for route in value["routes"]: + conflicts = _route_conflict(routes, route) + extra = {} if _route_present(routes, route): state = "present" - elif _route_conflict(routes, route): + elif conflicts: state = "conflict" + if any(_is_proto82(row) for row in conflicts): + extra["owner"] = "proto-82" + if log: + log(f"leaving conflicting proto {ROUTE_PROTOCOL} route for {route['dst']} untouched " + "(owned by another fabric session)") elif not _link_up(route["dev"], root): state = "no-link" else: @@ -412,7 +422,7 @@ def restore(value, *, call, root="/", log=None): state = "failed" if log: log(f"could not restore relay route {route['dst']} dev {route['dev']}: {error}") - rows.append({"kind": "route", "dst": route["dst"], "dev": route["dev"], "state": state}) + rows.append({"kind": "route", "dst": route["dst"], "dev": route["dev"], "state": state, **extra}) neighbours = _json(call, ["ip", "-j", "-4", "neigh", "show", "nud", "permanent"]) for neighbour in value["neighbours"]: if _neighbour_present(neighbours, neighbour): @@ -464,9 +474,17 @@ def observe(value, *, call, root="/"): rows.append({"kind": "filter", "dev": netdev, "pref": rule["pref"], "state": state}) routes = _route_rows(call) for route in value["routes"]: - state = "present" if _route_present(routes, route) else "conflict" if _route_conflict(routes, route) else ( - "missing" if _link_up(route["dev"], root) else "no-link") - rows.append({"kind": "route", "dst": route["dst"], "dev": route["dev"], "state": state}) + conflicts = _route_conflict(routes, route) + extra = {} + if _route_present(routes, route): + state = "present" + elif conflicts: + state = "conflict" + if any(_is_proto82(row) for row in conflicts): + extra["owner"] = "proto-82" + else: + state = "missing" if _link_up(route["dev"], root) else "no-link" + rows.append({"kind": "route", "dst": route["dst"], "dev": route["dev"], "state": state, **extra}) neighbours = _json(call, ["ip", "-j", "-4", "neigh", "show", "nud", "permanent"]) for neighbour in value["neighbours"]: state = "present" if _neighbour_present(neighbours, neighbour) else ( diff --git a/runtime/host/seed.py b/runtime/host/seed.py index c5194285..dbdc893e 100644 --- a/runtime/host/seed.py +++ b/runtime/host/seed.py @@ -147,11 +147,26 @@ def idle(): "(for example: sudo systemctl disable --now dropbear) and repeat") node.call(["systemctl", "enable", "--now", "ssh.service"], run=run) control_node.write("/etc/sparkring/seed_keys", public_key.strip() + "\n") + # Bind only to the prepared fabric interfaces' link-local IPv6 addresses when present, + # avoiding wildcard exposure on LAN/global addresses. + listen_addresses = [] + for interface in interfaces: + try: + observed6 = json.loads(node.call(["ip", "-j", "-6", "addr", "show", "dev", interface], run=run).stdout) + except (ValueError, RuntimeError, OSError, subprocess.SubprocessError): + continue + for row in observed6: + for addr in row.get("addr_info", []): + if addr.get("scope") == "link" and addr.get("local") and not addr.get("tentative"): + scoped = f"{addr['local']}%{interface}" + if scoped not in listen_addresses: + listen_addresses.append(scoped) + listen_lines = "\n".join(f"ListenAddress {address}" for address in listen_addresses) if listen_addresses else "ListenAddress ::" # This separate SSH service accepts only Node A's public key. Existing SSH # authentication policy and authorized_keys files are preserved. - control_node.write("/etc/sparkring/seed_sshd_config", """Port 2222 + control_node.write("/etc/sparkring/seed_sshd_config", f"""Port 2222 AddressFamily inet6 -ListenAddress :: +{listen_lines} HostKey /etc/ssh/ssh_host_ed25519_key PidFile /run/sparkring-seed.pid AuthorizedKeysFile /etc/sparkring/seed_keys @@ -162,7 +177,11 @@ def idle(): AllowUsers root UsePAM yes AllowAgentForwarding no -AllowTcpForwarding yes +AllowTcpForwarding no +AllowStreamLocalForwarding no +GatewayPorts no +PermitTunnel no +X11Forwarding no PermitUserRC no """) node.call(["/usr/sbin/sshd", "-t", "-f", "/etc/sparkring/seed_sshd_config"], run=run) diff --git a/runtime/host/test_control.py b/runtime/host/test_control.py index 590c2bd1..e7d36653 100644 --- a/runtime/host/test_control.py +++ b/runtime/host/test_control.py @@ -871,3 +871,35 @@ def run(*flags): configured.clear() assert run("--yes") == 0 assert configured == {} and "Every Spark already has these fallback paths." in capsys.readouterr().out + + +def test_secret_files_are_created_atomically_with_target_mode_before_write(tmp_path, monkeypatch): + """Secret writes use O_WRONLY | O_CREAT | O_EXCL with target mode before writing any bytes.""" + opens = [] + real_open = os.open + + def spy_open(path, flags, mode=0o777, *args, **kwargs): + opens.append((str(path), flags, mode)) + return real_open(path, flags, mode, *args, **kwargs) + + monkeypatch.setattr(os, "open", spy_open) + + control_node.write("/etc/sparkring/control.key", CONTROL_PRIVATE + "\n", root=tmp_path) + control_node._write_private("/run/sparkring-control/sr-control.conf", "[Interface]\nPrivateKey = x\n", root=tmp_path) + node.save(tmp_path, "/etc/sparkring/control.json", {"secret": True}, mode=0o600) + + assert len(opens) == 3 + for path, flags, mode in opens: + assert path.endswith(".writing") + assert flags & os.O_WRONLY + assert flags & os.O_CREAT + assert flags & os.O_EXCL + assert mode == 0o600 + + assert (tmp_path / "etc/sparkring/control.key").read_text(encoding="utf-8") == CONTROL_PRIVATE + "\n" + assert (tmp_path / "run/sparkring-control/sr-control.conf").read_text(encoding="utf-8") == "[Interface]\nPrivateKey = x\n" + assert json.loads((tmp_path / "etc/sparkring/control.json").read_text(encoding="utf-8")) == {"secret": True} + if os.name == "posix": + assert (tmp_path / "etc/sparkring/control.key").stat().st_mode & 0o777 == 0o600 + assert (tmp_path / "run/sparkring-control/sr-control.conf").stat().st_mode & 0o777 == 0o600 + assert (tmp_path / "etc/sparkring/control.json").stat().st_mode & 0o777 == 0o600 diff --git a/runtime/host/test_dashboard.py b/runtime/host/test_dashboard.py index 32293ce1..5bd8d19e 100644 --- a/runtime/host/test_dashboard.py +++ b/runtime/host/test_dashboard.py @@ -752,12 +752,77 @@ def test_localhost_is_an_accepted_host_name(): assert dashboard.host_allowed("localhost:8090", frozenset()) assert not dashboard.host_allowed("localhost.attacker.example:8090", frozenset()) -def test_a_password_file_requires_basic_authentication(server): +def test_a_password_file_requires_basic_authentication(server, monkeypatch): port, _ = server(password="correct horse") + calls = [] + real_compare = dashboard.hmac.compare_digest + + def spy_compare(a, b): + calls.append((a, b)) + return real_compare(a, b) + + monkeypatch.setattr(dashboard.hmac, "compare_digest", spy_compare) response, _ = call(port, "GET", "/api/status") assert response.status == 401 and "Basic" in response.getheader("WWW-Authenticate") + wrong = base64.b64encode(b"sparkring:wrong horse").decode() + assert call(port, "GET", "/api/status", headers={"Authorization": "Basic " + wrong})[0].status == 401 token = base64.b64encode(b"sparkring:correct horse").decode() assert call(port, "GET", "/api/status", headers={"Authorization": "Basic " + token})[0].status == 200 + assert len(calls) == 2 + + +def test_dashboard_defaults_to_loopback_and_fails_closed_for_unauthenticated_lan(tmp_path, monkeypatch): + import socket + quiet = tmp_path / "dashboard.quiet" + quiet.write_text("no requests\n") + monkeypatch.setattr(socket, "gethostname", lambda: "spark0") + source = dashboard.Source(fabric_file(tmp_path), site_file(tmp_path)) + source.refresh() + assert dashboard.default_bind(source) == "127.0.0.1" + assert dashboard.default_bind(source, authenticated=True) == NODE_A_LAN + assert dashboard.default_bind(source, allow_unauthenticated_lan=True) == NODE_A_LAN + + # Non-loopback --bind / --host without --password-file or --allow-unauthenticated-lan fails closed. + for bad_bind in ("0.0.0.0", "::", NODE_A_LAN, "dashboard.example"): + args = dashboard.argparse.Namespace( + fabric=[fabric_file(tmp_path)], site=[site_file(tmp_path)], quiet_file=str(quiet), + no_node_status=True, password_file=None, bind=bad_bind, port=0, name=None, cpus=None, + allow_unauthenticated_lan=False) + with pytest.raises(ValueError, match="Refusing to bind unauthenticated dashboard"): + dashboard.serve(args) + + # Non-loopback bind is allowed with --password-file or --allow-unauthenticated-lan. + opened = [] + + class DummyServer: + server_address = ("127.0.0.1", 8090) + + def serve_forever(self): + pass + + monkeypatch.setattr(dashboard, "lower_priority", lambda cpus: []) + monkeypatch.setattr(dashboard, "reload_on_hangup", lambda found: False) + monkeypatch.setattr(dashboard, "open_servers", lambda addrs, port, handler, log=None: opened.append(addrs) or [DummyServer()]) + + pw = tmp_path / "dashboard.pw" + pw.write_text("s3cr3t\n", encoding="utf-8") + args_auth = dashboard.argparse.Namespace( + fabric=[fabric_file(tmp_path)], site=[site_file(tmp_path)], quiet_file=str(quiet), + no_node_status=True, password_file=str(pw), bind=NODE_A_LAN, port=0, name=None, cpus=None, + allow_unauthenticated_lan=False) + assert dashboard.serve(args_auth) == 0 + assert opened[-1] == [NODE_A_LAN, "127.0.0.1"] + + args_opt_in = dashboard.argparse.Namespace( + fabric=[fabric_file(tmp_path)], site=[site_file(tmp_path)], quiet_file=str(quiet), + no_node_status=True, password_file=None, bind=NODE_A_LAN, port=0, name=None, cpus=None, + allow_unauthenticated_lan=True) + assert dashboard.serve(args_opt_in) == 0 + assert opened[-1] == [NODE_A_LAN, "127.0.0.1"] + + unit = (ROOT / "packaging" / "debian" / "sparkring-dashboard.service").read_text(encoding="utf-8") + assert "ExecStart=/usr/bin/sparkring dashboard serve --bind 127.0.0.1" in unit + assert "SupplementaryGroups=sparkring" in unit def test_settings_reads_are_requested_through_a_rate_limited_route(server): diff --git a/runtime/host/test_dashboard_admin.py b/runtime/host/test_dashboard_admin.py index cf6540fb..3f2ac05b 100644 --- a/runtime/host/test_dashboard_admin.py +++ b/runtime/host/test_dashboard_admin.py @@ -317,9 +317,10 @@ def test_the_install_card_names_the_page_only_while_its_service_is_on(tmp_path, monkeypatch.setattr(dashboard_admin, "DISABLED_PATH", tmp_path / "dashboard.disabled") monkeypatch.setattr(socket, "gethostname", lambda: "spark0") path = fabric_file(tmp_path) - page = f"http://{FABRIC_NODE_A_LAN}:8090/" + page = "http://127.0.0.1:8090/" assert REAL_PAGE_URL(run=UnitState("is-enabled"), fabric_path=path) == page assert REAL_PAGE_URL(run=UnitState("is-active"), fabric_path=path) == page # running, though not enabled + assert dashboard.service_url(path, authenticated=True) == f"http://{FABRIC_NODE_A_LAN}:8090" off = UnitState() assert REAL_PAGE_URL(run=off, fabric_path=path) is None assert off.calls == [["is-enabled", "--quiet", dashboard_admin.UNIT], ["is-active", "--quiet", dashboard_admin.UNIT]] diff --git a/runtime/host/test_dashboard_tui.py b/runtime/host/test_dashboard_tui.py index 0d6f3048..cb542a64 100644 --- a/runtime/host/test_dashboard_tui.py +++ b/runtime/host/test_dashboard_tui.py @@ -249,7 +249,8 @@ def test_the_default_address_is_the_services_own_bind(tmp_path, monkeypatch): from runtime.host.test_dashboard import fabric_file path = fabric_file(tmp_path) monkeypatch.setattr(socket, "gethostname", lambda: "spark0") - assert tui.local_url(path) == f"http://{NODE_A_LAN}:{dashboard.DEFAULT_PORT}" + assert tui.local_url(path) == f"http://127.0.0.1:{dashboard.DEFAULT_PORT}" + assert dashboard.service_url(path, authenticated=True) == f"http://{NODE_A_LAN}:{dashboard.DEFAULT_PORT}" monkeypatch.setattr(socket, "gethostname", lambda: "spark3") assert tui.local_url(path) == f"http://127.0.0.1:{dashboard.DEFAULT_PORT}" diff --git a/runtime/host/test_helper.py b/runtime/host/test_helper.py index a6f0812b..d0f27b41 100644 --- a/runtime/host/test_helper.py +++ b/runtime/host/test_helper.py @@ -188,3 +188,40 @@ def test_commands_outside_helper_allowlist_use_the_normal_cli(argv, monkeypatch) monkeypatch.setattr(sparkring, "_main", lambda args: calls.append(args) or 7) assert sparkring.main(argv) == 7 assert calls == [argv] + + +def test_helper_socket_limits_connections(): + from pathlib import Path + unit = (Path(__file__).resolve().parents[2] / "packaging/debian/sparkring-helper.socket").read_text(encoding="utf-8") + assert "MaxConnections=16" in unit + + +def test_run_bounded_caps_runaway_child_output_with_truncation_marker(): + import sys + result = helper._run_bounded( + ["-c", "import sys; sys.stdout.write('A' * 50000); sys.stderr.write('B' * 50000)"], + argv0=sys.executable, + timeout=30, + max_bytes=1024, + ) + assert result.returncode == 0 + assert result.stdout.startswith("A" * 1024) + assert helper.TRUNCATION_MARKER in result.stdout + assert len(result.stdout) < 2048 + assert result.stderr.startswith("B" * 1024) + assert helper.TRUNCATION_MARKER in result.stderr + assert len(result.stderr) < 2048 + + +def test_serve_bounds_oversized_output_and_preserves_truncation_marker(): + connection_a, connection_b = socket.socketpair() + child = Child(code=0, out="X" * 4096, err="Y" * 4096) + connection_b.sendall(b'{"argv": ["up", "glm53-flash", "--execute"]}\n') + audit = io.StringIO() + helper.serve(connection_a, spawn=child, out=audit, max_bytes=256) + lines = [json.loads(line) for line in connection_b.recv(65536).decode().splitlines()] + out_text = "".join(line["text"] for line in lines if line.get("type") == "output" and line.get("stream") == "out") + err_text = "".join(line["text"] for line in lines if line.get("type") == "output" and line.get("stream") == "err") + assert out_text == ("X" * 256) + helper.TRUNCATION_MARKER + assert err_text == ("Y" * 256) + helper.TRUNCATION_MARKER + assert lines[-1] == {"type": "exit", "code": 0} diff --git a/runtime/host/test_install_workflow.py b/runtime/host/test_install_workflow.py index a25a2157..dd2acfb7 100644 --- a/runtime/host/test_install_workflow.py +++ b/runtime/host/test_install_workflow.py @@ -864,6 +864,22 @@ def invoke(host, argv): assert all(argv == ["sudo", "-n", "true"] for _, argv in calls) +def test_check_access_sanitizes_sudoers_filename_for_dots_and_tildes(): + assert flow.sudoers_filename("jane.doe") == "sparkring-jane_doe" + assert flow.sudoers_filename("ops.admin~") == "sparkring-ops_admin" + assert flow.sudoers_filename("user~1.test") == "sparkring-user_1_test" + assert "." not in flow.sudoers_filename("a.b.c~") and "~" not in flow.sudoers_filename("a.b.c~") + cluster = {"plan": {"spec": {"hosts": [{"host": "jane.doe@192.0.2.10"}, {"host": "ops~@192.0.2.11"}]}}} + from runtime.host.install_errors import NeedsInput + with pytest.raises(NeedsInput) as caught: + flow.check_access(cluster, invoke=lambda host, argv: (_ for _ in ()).throw(RuntimeError("sudo: password required"))) + fixes = [row["fix"] for row in caught.value.document()["details"]["hosts"]] + assert "/etc/sudoers.d/sparkring-jane_doe" in fixes[0] + assert "/etc/sudoers.d/jane.doe" not in fixes[0] + assert "/etc/sudoers.d/sparkring-ops" in fixes[1] + assert "/etc/sudoers.d/ops~" not in fixes[1] + + @pytest.mark.parametrize("approved", [False, True]) def test_unrelated_gpu_containers_are_stopped_only_with_approval(monkeypatch, tmp_path, approved): from scripts import installer_runner diff --git a/runtime/host/test_persistence.py b/runtime/host/test_persistence.py index 7a4bda58..4feb09a4 100644 --- a/runtime/host/test_persistence.py +++ b/runtime/host/test_persistence.py @@ -454,6 +454,11 @@ def test_administration_access_starts_whenever_the_administration_interface_exis assert unit[("Unit", "ConditionPathExists")] == ["/etc/sparkring/sshd_config", "/sys/class/net/sr-control"] refresh = unit_settings((PACKAGING / "sparkring-control-refresh.service").read_text()) assert "sparkring-access.service" in refresh[("Service", "ExecStartPost")] + for name in ("sparkring-access.service", "sparkring-seed.service"): + text = (PACKAGING / name).read_text(encoding="utf-8") + assert "-o AllowTcpForwarding=no" in text + assert "ProtectKernelModules=yes" in text + assert "LockPersonality=yes" in text def test_package_enables_the_hairpin_service_only_for_the_next_boot(): diff --git a/runtime/host/test_privilege.py b/runtime/host/test_privilege.py index fa97ba56..f0f210fd 100644 --- a/runtime/host/test_privilege.py +++ b/runtime/host/test_privilege.py @@ -264,3 +264,41 @@ def test_recover_status_refuses_a_user_outside_the_group(monkeypatch, capsys): monkeypatch.setattr(recovery, "describe", _refused) assert recovery.main(["status"]) == 2 assert "sparkring group" in capsys.readouterr().err + + +def test_shared_status_recovery_site_and_nodes_files_use_0640_group_contract(tmp_path, monkeypatch): + from runtime.host import dashboard_admin + shared = [] + monkeypatch.setattr(privilege, "share", lambda p, mode=0o640: shared.append((Path(p).name, mode)) or True) + opens = [] + real_open = os.open + + def spy_open(path, flags, mode=0o777, *args, **kwargs): + opens.append((Path(path).name, mode)) + return real_open(path, flags, mode, *args, **kwargs) + + monkeypatch.setattr(os, "open", spy_open) + + # 1. status.json via node.agent(once=True) + monkeypatch.setattr(node, "snapshot", lambda **kwargs: {"schema": "sparkring-node-status/v1", "observed_at": 1.0}) + node.agent(root=tmp_path, once=True) + + # 2. recovery.json via recovery._write + monkeypatch.setattr(controller, "STATE", tmp_path / "controller") + recovery._write({"schema": recovery.SCHEMA, "deployments": {}}) + + # 3. site.json via dashboard_admin.write_site + monkeypatch.setattr(dashboard_admin, "site_from_records", lambda root: {"schema": "sparkring-dashboard-site/v1", "deployments": []}) + dashboard_admin.write_site(tmp_path / "dashboard" / "site.json") + + # 4. nodes.json via dashboard_admin.refresh_nodes + monkeypatch.setattr(dashboard_admin, "DISABLED_PATH", tmp_path / "dashboard.disabled") + monkeypatch.setattr("runtime.host.host_load.recorded_targets", lambda root: ["root@192.0.2.10"]) + monkeypatch.setattr(recovery, "node_documents", lambda hosts, invoke=None: {}) + monkeypatch.setattr(dashboard_admin, "cached_node_rows", lambda *a, **k: []) + dashboard_admin.refresh_nodes(state_root=tmp_path / "controller", output=tmp_path / "dashboard" / "nodes.json", + quiet_path=tmp_path / "dashboard.quiet") + + assert shared == [("status.json", 0o640), ("recovery.json", 0o640), ("site.json", 0o640), ("nodes.json", 0o640)] + for target_name in ("status.json", "recovery.json", "site.json", "nodes.json"): + assert any(name.startswith(target_name + ".") and mode == 0o640 for name, mode in opens), (target_name, opens) diff --git a/runtime/host/test_recovery.py b/runtime/host/test_recovery.py index db75319e..d4b94768 100644 --- a/runtime/host/test_recovery.py +++ b/runtime/host/test_recovery.py @@ -944,3 +944,50 @@ def test_a_terminal_down_without_execute_refuses_another_operators_hold(pair, mo assert len(answers) == 1 and pair.operations [entry] = [json.loads(line) for line in (controller.STATE / hold.OVERRIDES).read_text().splitlines()] assert entry["operator"] == "bob" and entry["operation"] == "down" + + +@pytest.mark.parametrize("size", [6, 8]) +def test_six_and_eight_spark_clusters_enforce_hairpin_check_during_recovery(tmp_path, monkeypatch, size): + from runtime.host import discovery, placement + from runtime.host.test_fabric_groups import ring_cluster + + monkeypatch.setattr(controller, "STATE", tmp_path / "state") + value = ring_cluster(size) + node.save(controller.STATE, "cluster.json", value) + hosts = [host["host"] for host in value["plan"]["spec"]["hosts"]] + directory = tmp_path / "state" / "deployments" / f"ring{size}" + lock = { + "id": "e" * 64, "backend": "compose", "selection": {"profile": f"test-tp{size}"}, + "site": {"name": f"ring{size}", "ranks": [{"rank": r, "host": h} for r, h in enumerate(hosts)]}, + } + lock["selection"].update(target_variant=None, model_repository="local-inference-lab/Qwen3.8-Flash-Next-NVFP4", + model_revision="0" * 40, release="dev-image") + installer.write(directory / "deployment.lock.json", lock) + installer.write(directory / "state.json", {"generation": 1, "operation": "up", "complete": True}) + placement.record(controller.STATE, None, directory) + sparks = Sparks(hosts) + sparks.directory = directory.resolve() + for rank, host in enumerate(hosts): + sparks.documents[host] = {"state": "network-configured", "hostname": f"spark{rank}", "boot_id": BOOT} + sparks.running.update({rank: True for rank in range(size)}) + sparks.running[1] = False + monkeypatch.setattr(discovery, "ssh", sparks.ssh) + recovery.update(directory, api_url="http://192.0.2.10:8000/v1") + + checked = [] + + def hairpin_problem(slot=None): + checked.append(slot) + return f"rank {size - 1} (spark{size - 1}): the ConnectX hairpin setting is not in effect" + + monkeypatch.setattr(controller, "_hairpin_problem", hairpin_problem) + clock = Clock() + applied = [] + for _ in range(recovery.CONFIRMATIONS): + clock.advance(60) + result = run(clock, apply=applied.append) + assert applied == [] + assert checked == [None] + assert result["state"] == "report" + assert result["finding"]["state"] == "hairpin" + assert result["finding"]["next_action"] == "on Node A: sudo sparkring hairpin" diff --git a/runtime/host/test_relays.py b/runtime/host/test_relays.py index 81bc7fc8..a714f7c1 100644 --- a/runtime/host/test_relays.py +++ b/runtime/host/test_relays.py @@ -627,3 +627,85 @@ def run(argv, **kwargs): assert result["active"] is True and result["routes"] == [] and result["settings"] == [] assert {row["state"] for row in result["relays"] if row["kind"] == "neighbour"} == {"restored"} assert not [argv for argv in kernel.calls if argv[0] in NETWORK_TOOLS or argv[:3] == ["ip", "route", "add"]] + + +def test_agent_yields_to_active_sircl_fabric_and_resumes_when_stale(tmp_path): + config, kernel, facts = adopted_spark(tmp_path) + node.save(tmp_path, "/etc/sparkring/node.json", {"schema": "sparkring-node/v1", "node_id": config["node_id"]}) + node.save(tmp_path, "/etc/sparkring/fabric.json", config) + kernel.neighbours.clear() + kernel.calls.clear() + + # Active sircl fabric session: relay-state.json + live marker process in /proc. + record = { + "schema": node.SIRCL_FABRIC_SCHEMA, + "spark": "spark0", + "position": 0, + "layout": "2xTP4", + "group": "path:0-1-2-3", + "plan": "0123456789abcdef", + "marker": "/usr/local/libexec/sparkring/ring8-mesh-marker", + "qdiscs": ["enp1s0f0np0"], + } + record_path = tmp_path / "run/sparkring-fabric/relay-state.json" + record_path.parent.mkdir(parents=True, exist_ok=True) + record_path.write_text(json.dumps(record), encoding="utf-8") + proc_dir = tmp_path / "proc/4242" + proc_dir.mkdir(parents=True) + (proc_dir / "cmdline").write_bytes( + b"/usr/local/libexec/sparkring/ring8-mesh-marker\x00--device\x00rocep1s0f0\x00--managed\x00" + ) + + def run(argv, **kwargs): + if argv[0] == "systemctl": + return SimpleNamespace(returncode=0, stdout="active\n", stderr="") + return kernel(argv) + + logs = [] + result = node.restore_fabric(config, root=tmp_path, run=run, log=logs.append) + assert result["active"] is False + assert result["yielded_to_sircl_fabric"] is True + assert result["sircl_fabric"]["group"] == "path:0-1-2-3" + assert result["sircl_fabric"]["marker_pids"] == [4242] + assert kernel.calls == [] + assert any("yielding fabric restoration" in line for line in logs) + + # Snapshot reports yielded_to_sircl_fabric cleanly without overwriting or alarming. + snap = node.snapshot(root=tmp_path, collect=lambda req: facts, run=run, repair=True) + assert snap["yielded_to_sircl_fabric"] is True + assert snap["sircl_fabric"]["group"] == "path:0-1-2-3" + assert snap["state"] == "existing-network-verified" + assert kernel.calls == [] + + # Stale relay-state.json (marker exited): agent does NOT yield and restores normally. + (proc_dir / "cmdline").unlink() + proc_dir.rmdir() + assert node.sircl_fabric_session(root=tmp_path) is None + resumed = node.restore_fabric(config, root=tmp_path, run=run, log=lambda line: None) + assert resumed["active"] is True + assert not resumed.get("yielded_to_sircl_fabric") + assert {row["state"] for row in resumed["relays"] if row["kind"] == "neighbour"} == {"restored"} + + +def test_relays_flags_conflicting_proto82_route_instead_of_clobbering(tmp_path): + config, kernel, _ = adopted_spark(tmp_path) + section = config["relays"] + target = section["routes"][0] + other_dev = next(p["netdev"] for p in config["interfaces"] if p["netdev"] != target["dev"]) + kernel.routes = [r for r in kernel.routes if r["dst"] != target["dst"].split("/")[0]] + kernel.routes.append({ + "dst": target["dst"].split("/")[0], "dev": other_dev, "prefsrc": target["src"], + "scope": "link", "protocol": "82", + }) + kernel.calls.clear() + + logs = [] + restored = relays.restore(section, call=kernel, root=tmp_path, log=logs.append) + row = next(r for r in restored if r["kind"] == "route" and r["dst"] == target["dst"]) + assert row["state"] == "conflict" and row.get("owner") == "proto-82" + assert not any(argv[:3] == ["ip", "route", "replace"] and argv[3] == target["dst"] for argv in kernel.calls) + assert any("conflicting proto 82 route" in line for line in logs) + + observed = relays.observe(section, call=kernel, root=tmp_path) + obs_row = next(r for r in observed if r["kind"] == "route" and r["dst"] == target["dst"]) + assert obs_row["state"] == "conflict" and obs_row.get("owner") == "proto-82" From 32b722f504aa70a8bf6aea20b2de14556cdd59b0 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:37:38 -0600 Subject: [PATCH 3/3] install: fix fresh-box apt update, quoted deb glob, /dev/tty prompt, aarch64 check, and CLI shadowing --- bootstrap.sh | 68 ++++++++++++++++++++++++---------- install.sh | 10 ++++- scripts/test_install_script.py | 10 +++-- 3 files changed, 64 insertions(+), 24 deletions(-) diff --git a/bootstrap.sh b/bootstrap.sh index 7acabed9..d133fda0 100644 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -44,6 +44,11 @@ while (($#)); do esac done +if [[ $(uname -m) != aarch64 ]]; then + echo "SparkRing installs on DGX Spark (ARM64) hosts; this host is $(uname -m)." >&2 + exit 1 +fi + for command_name in git python3 ssh ssh-keygen ssh-keyscan ssh-copy-id; do if ! command -v "$command_name" >/dev/null 2>&1; then echo "missing required command: $command_name" >&2 @@ -54,7 +59,12 @@ done if ! python3 -c 'import yaml' >/dev/null 2>&1; then echo "PyYAML is required (Ubuntu package: python3-yaml)." if ((ASSUME_YES == 0)); then - read -r -p "Install python3-yaml with apt? Type yes: " answer + if ! { : /dev/null; then + echo "Cannot prompt for confirmation without a terminal; re-run with --yes or install python3-yaml first." >&2 + exit 1 + fi + answer="" + read -r -p "Install python3-yaml with apt? Type yes: " answer &2 exit 1 @@ -99,34 +109,52 @@ fi mkdir -p "$BIN_DIR" launcher="$BIN_DIR/sparkring" -if [[ -L "$launcher" ]]; then - if [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then - rm "$launcher" - else +if [[ -x /usr/bin/sparkring ]]; then + echo "Warning: /usr/bin/sparkring (installed Debian package) is already present." >&2 + if [[ -L "$launcher" ]] && [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then + rm -f "$launcher" + echo "Removed $launcher so it does not shadow /usr/bin/sparkring." >&2 + elif [[ -f "$launcher" ]] && grep -Fq "$INSTALL_DIR/scripts/sparkring.py" "$launcher" 2>/dev/null; then + rm -f "$launcher" + echo "Removed $launcher so it does not shadow /usr/bin/sparkring." >&2 + elif [[ -e "$launcher" || -L "$launcher" ]]; then + echo "Warning: $launcher exists and may shadow /usr/bin/sparkring when $BIN_DIR precedes /usr/bin in PATH." >&2 + fi + echo "Skipping $launcher creation; use /usr/bin/sparkring (or 'sparkring') for the installed package." >&2 +else + if [[ -L "$launcher" ]]; then + if [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then + rm "$launcher" + else + backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)" + mv "$launcher" "$backup" + echo "backed up existing launcher symlink to $backup" + fi + elif [[ -e "$launcher" ]]; then backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)" mv "$launcher" "$backup" - echo "backed up existing launcher symlink to $backup" + echo "backed up existing launcher to $backup" fi -elif [[ -e "$launcher" ]]; then - backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)" - mv "$launcher" "$backup" - echo "backed up existing launcher to $backup" + # The launcher runs the tracked script through python3, so the checkout keeps + # its committed file modes and stays clean for later --ref updates. + printf '#!/usr/bin/env bash\nexec python3 %q "$@"\n' \ + "$INSTALL_DIR/scripts/sparkring.py" > "$launcher" + chmod 0755 "$launcher" fi -# The launcher runs the tracked script through python3, so the checkout keeps -# its committed file modes and stays clean for later --ref updates. -printf '#!/usr/bin/env bash\nexec python3 %q "$@"\n' \ - "$INSTALL_DIR/scripts/sparkring.py" > "$launcher" -chmod 0755 "$launcher" echo echo "SparkRing installed at $INSTALL_DIR" echo "Checkout revision: $(git -C "$INSTALL_DIR" rev-parse HEAD)" echo "Run repository commands from: cd $INSTALL_DIR" -echo "Command installed at $launcher" -case ":${PATH}:" in - *":${BIN_DIR}:"*) ;; - *) echo "Add this to your shell profile: export PATH=\"${BIN_DIR}:\$PATH\"" ;; -esac +if [[ -x /usr/bin/sparkring ]]; then + echo "Packaged command in use: /usr/bin/sparkring" +else + echo "Command installed at $launcher" + case ":${PATH}:" in + *":${BIN_DIR}:"*) ;; + *) echo "Add this to your shell profile: export PATH=\"${BIN_DIR}:\$PATH\"" ;; + esac +fi echo echo "Check this Spark first:" echo " sparkring host check" diff --git a/install.sh b/install.sh index 76995a78..8ece07c6 100644 --- a/install.sh +++ b/install.sh @@ -226,7 +226,13 @@ say "Source revision: $revision" say "Building the SparkRing package" python3 "$WORK/source/scripts/build_deb.py" --output "$WORK/dist" "${BUILD_ARGS[@]}" >/dev/null \ || stop failed build "Could not build the SparkRing package from $revision." -package=$(echo "$WORK"/dist/sparkring_*_arm64.deb) +shopt -s nullglob +packages=("$WORK"/dist/sparkring_*_arm64.deb) +shopt -u nullglob +if ((${#packages[@]} != 1)); then + stop failed build "Expected one SparkRing Debian package in $WORK/dist, found ${#packages[@]}." +fi +package=${packages[0]} chmod 0644 "$package" version=$(dpkg-deb --field "$package" Version) @@ -280,6 +286,8 @@ else fi fi say "Installing $(basename "$package")" + "${SUDO[@]}" apt-get update >&2 \ + || stop failed package "apt-get update failed before installing $(basename "$package")." "${SUDO[@]}" apt-get install --yes --allow-downgrades "$package" >&2 \ || stop failed package "apt could not install $(basename "$package")." fi diff --git a/scripts/test_install_script.py b/scripts/test_install_script.py index 00519bf2..3d1ab248 100644 --- a/scripts/test_install_script.py +++ b/scripts/test_install_script.py @@ -80,6 +80,8 @@ def test_install_script_parses(): text = SCRIPT.read_text(encoding="utf-8") assert text.startswith("#!/usr/bin/env bash\n") assert "set -euo pipefail" in text + assert '"${SUDO[@]}" apt-get update >&2' in text + assert 'packages=("$WORK"/dist/sparkring_*_arm64.deb)' in text result = subprocess.run([_bash(), "-n"], input=text.encode("utf-8"), capture_output=True, timeout=10) assert result.returncode == 0, result.stderr @@ -200,7 +202,8 @@ def test_json_output_is_one_document_and_progress_goes_to_stderr(tmp_path): assert result.returncode == 0, result.stderr assert only_document(result.stdout)["schema"] == "sparkring-install-result/v1" assert "Reading package lists..." in result.stderr and "Fetching SparkRing" in result.stderr - assert calls == [f"apt-get install --yes --allow-downgrades {calls[0].split()[-1]}", + assert calls == ["apt-get update", + f"apt-get install --yes --allow-downgrades {calls[1].split()[-1]}", "sparkring install --profile qwen38-flash-next-tp2 --yes --json"] @@ -306,7 +309,7 @@ def test_package_only_stops_before_sparkring_install(tmp_path, installed): assert document["state"] == "package-installed" assert (document["version"], document["previous"], document["changed"]) == (BUILT, installed, installed != BUILT) assert document["source_revision"] == "a" * 40 - assert [call.split()[0] for call in calls] == ([] if installed == BUILT else ["apt-get"]) + assert [call.split()[0] for call in calls] == ([] if installed == BUILT else ["apt-get", "apt-get"]) def test_package_only_still_needs_approval(tmp_path): @@ -342,7 +345,8 @@ def test_yes_can_upgrade_an_ancestor_revision(tmp_path): result, calls = run_script(tmp_path, "--yes", "--json", installed="0.1.0~dev.1+gitbbbb", revision="b" * 40, ancestor=True) assert result.returncode == 0, result.stderr - assert calls[0].startswith("apt-get install ") + assert calls[0] == "apt-get update" + assert calls[1].startswith("apt-get install ") assert calls[-1] == "sparkring install --yes --json"