From 304e8b1b7d88bec51bd501edc035928da25c66e6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 01:05:53 -0500 Subject: [PATCH] =?UTF-8?q?test(grpc-data):=20A4=20live=20scenarios=20part?= =?UTF-8?q?=201=20harness=20=E2=80=94=20run-owned=20opc-plc=20--alm,=20nat?= =?UTF-8?q?ive=20alarm=20+=202=20referencing=20equipment=20+=203=20conditi?= =?UTF-8?q?on=20mappings,=20UNS-only=20origin=20principal,=20no-grant=20co?= =?UTF-8?q?nsumer=20principal;=20probe=20condition-records;=20node-probe?= =?UTF-8?q?=20alert-transitions;=20conditions=5Fscenarios.py=20(A01/A02/A0?= =?UTF-8?q?4/A05/A08)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../grpc-data/compose.conditions.yml | 22 + .../grpc-data/conditions_scenarios.py | 502 ++++++++++++++++++ .../grpc-data/node-probe/NodeProbeStartup.cs | 44 ++ scripts/validation/grpc-data/probe/Program.cs | 71 ++- scripts/validation/grpc-data/rig.py | 9 +- scripts/validation/grpc-data/seed/Program.cs | 62 ++- 6 files changed, 704 insertions(+), 6 deletions(-) create mode 100644 scripts/validation/grpc-data/conditions_scenarios.py diff --git a/scripts/validation/grpc-data/compose.conditions.yml b/scripts/validation/grpc-data/compose.conditions.yml index 842c432ac..bd49c14b6 100644 --- a/scripts/validation/grpc-data/compose.conditions.yml +++ b/scripts/validation/grpc-data/compose.conditions.yml @@ -2,8 +2,30 @@ # SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets one scripted alarm (`ScalarHigh`, scalar > 100). # The dev DataConnections__ConditionKeySecret is already set on both source services in compose.yml. # Without this file the rig is the unchanged v1 fixture. +# +# A4 live scenarios: a RUN-OWNED opc-plc `--alm` simulator (`opcplc`, same pinned image as the OpcUaClient integration +# fixture, tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/docker-compose.yml) for the SOURCE +# OpcUaClient driver's native alarm. Run-owned rather than the shared 10.100.0.35:50000 fixture because (a) the rig's +# endpoint guard admits only run-owned service DNS (implementation plan: "validate resolved compose/seed has no shared-host +# endpoints") and (b) the scenarios acknowledge/comment upstream conditions, which must not leak into a shared simulator. +# It carries the run labels, so `rig.py down` removes it with everything else. No published port. + +x-labels: &labels + otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID:?run id required} + otopcua.grpc-data.fixture: "v1" services: seeder: environment: GRPC_DATA_CONDITIONS: "1" + opcplc: + image: mcr.microsoft.com/iotedge/opc-plc:2.14.10 + labels: *labels + networks: [rig] + command: ["--pn=50000", "--ut", "--aa", "--alm"] + source-1: + depends_on: + opcplc: {condition: service_started} + source-2: + depends_on: + opcplc: {condition: service_started} diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py new file mode 100644 index 000000000..96d60652e --- /dev/null +++ b/scripts/validation/grpc-data/conditions_scenarios.py @@ -0,0 +1,502 @@ +"""A4 live condition-forwarding scenarios (plan §9 A4, A01–A08) on a `rig.py up --conditions` run. + + python3 scripts/validation/grpc-data/conditions_scenarios.py --run-id [--only A01,A02,A04,A05,A08] + +Part 1 implements A01, A02, A04, A05 and A08. Part 2 (A03 origin failover, A06 consumer Primary change, A07 consumer +restart) adds `scenario_A03`/`scenario_A06`/`scenario_A07` methods to `ConditionScenarios` and their ids to `SCENARIOS`; +everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. + +Rules every scenario follows: +- ids are RESOLVED, never constructed: projected folders by browsing the consumer's address space, imported ConditionIds + and EventIds from the `alarms` notifications the CLI prints (`ConditionNodeId`, `EventId`); +- every absence assertion has a positive control observed in the same window; +- configuration changes go through the seeder's `mutate` (+ deploy) or a rig configuration experiment, and are undone + before the next scenario (`restore` + deploy, or the experiment's own restart). + +Evidence: the run's restricted `evidence/` folder — `A4S--*.txt` CLI logs, `*.process.json`, `*.probe.json`, +`A4S-.json` per scenario and `A4S-results.json` / `A4S-results.md` for the selection. +""" +import argparse +import json +import os +import re +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import rig +import scenarios + +SCENARIOS = ("A01", "A02", "A04", "A05", "A08") # part 2 appends A03, A06, A07 +TIMEOUTS = {"A01": 420, "A02": 360, "A04": 480, "A05": 720, "A08": 720} +NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8) +ADMIN = 4095 +_BROWSE = re.compile(r"^(\s*)\[(\w+)\]\s+(.*?)\s+\(NodeId:\s*(.*)\)\s*$") + + +class Watch: + """One CLI `alarms` subscription (Server object by default, or a notifier folder) writing to a restricted log.""" + + def __init__(self, runner, node, name, *, notifier=None, key=None, refresh=True): + self.log = runner.folder / name + self.started = time.time() + descriptor = os.open(self.log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + argv = ["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(node), "-U", "apikey", "-P", key or runner.key, "-i", "250"] + if notifier: + argv += ["-n", notifier] + if refresh: + argv.append("--refresh") + self.process = subprocess.Popen(argv, stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True, cwd=rig.ROOT) + os.close(descriptor) + + def stop(self): + if self.process.poll() is None: + self.process.send_signal(signal.SIGINT) + try: + self.process.wait(timeout=20) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=10) + + def text(self): + return self.log.read_text(errors="replace") if self.log.exists() else "" + + def blocks(self, condition=None): + found = [] + for block in self.text().split("\n\n"): + header = re.search(r"\[(\S+)\] ALARM\s+(.*)$", block, re.M) + if not header: + continue + fields = {"Time": header.group(1), "Source": header.group(2).strip()} + for line in block.splitlines(): + match = re.match(r"\s*(Condition|State|Severity|Message|Retain|ConditionNodeId|EventId):\s*(.*)$", line) + if match: + fields[match.group(1)] = match.group(2).strip() + if condition is None or fields.get("Condition") == condition: + found.append(fields) + return found + + +def wait_for(predicate, timeout, step=1.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = predicate() + if value: + return value + time.sleep(step) + return predicate() + + +def states(blocks): + return [b.get("State") for b in blocks] + + +class ConditionScenarios: + def __init__(self, run_id): + self.r = scenarios.ScenarioRunner(run_id) + self.fixture = self.r.manifest["fixture"] + if not self.fixture.get("conditions"): + raise scenarios.ScenarioError("the run was not seeded with the conditions profile (rig.py up --conditions)") + files = self.r.manifest["credentials"]["data_key_files"] + self.nogrant_key = Path(files["cli_nogrant"]).read_text().strip() + self.report = None + + # ---- primitives ------------------------------------------------------------------------------------------------- + def check(self, name, condition): + self.report["checks"][name] = bool(condition) + return bool(condition) + + def watch(self, node, tag, **options): + name = f"A4S-{self.r.active}-{tag}.txt" + watcher = Watch(self.r, node, name, **options) + self.watchers.append(watcher) + return watcher + + def cli(self, node, command, *args, tag, key=None, timeout=60): + argv = ["dotnet", str(self.r.cli_dll), command, "-u", self.r.endpoint(node), "-U", "apikey", "-P", key or self.r.key, *args] + result = self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=timeout) + return result.returncode, (result.stdout + result.stderr) + + def browse(self, node, start="i=85", depth=6): + code, text = self.cli(node, "browse", "-n", start, "-r", "-d", str(depth), tag="browse-" + uuid.uuid4().hex[:6], timeout=120) + rows, stack = [], [] + for line in text.splitlines(): + match = _BROWSE.match(line) + if not match: + continue + indent = len(match.group(1)) + while stack and stack[-1][0] >= indent: + stack.pop() + row = {"class": match.group(2), "name": match.group(3), "node_id": match.group(4), + "parent": stack[-1][1]["node_id"] if stack else start, "path": "/".join([s[1]["name"] for s in stack] + [match.group(3)])} + rows.append(row) + stack.append((indent, row)) + return rows + + def read(self, node, node_id, tag): + code, text = self.cli(node, "read", "-n", node_id, tag=tag) + value = re.search(r"^Value:\s*(.*)$", text, re.M) + status = re.search(r"^Status:\s*(\S+)", text, re.M) + return {"value": value.group(1).strip() if value else None, "status": status.group(1) if status else None} + + def condition_child(self, node, condition_id, child, tag): + """Browse the condition node for `child` (e.g. ConfirmedState) and read its `Id` — resolved, never constructed.""" + rows = self.browse(node, condition_id, depth=2) + state = next((r for r in rows if r["name"] == child and r["parent"] == condition_id), None) + identifier = next((r for r in rows if state and r["name"] == "Id" and r["parent"] == state["node_id"]), None) + return self.read(node, identifier["node_id"], tag) if identifier else {"value": None, "status": "unresolved"} + + def projected_folders(self, node): + """Resolve each condition mapping's projected branch folder (and its child folders) by browsing the consumer.""" + rows = self.browse(node) + native = self.fixture["conditions"]["native"] + folders = {} + for alias, branch in [("uns-plc", self.fixture["conditions"]["scripted"]["branch"]), *native["branches"].items()]: + matches = [r for r in rows if r["name"] == branch] + folders[alias] = [{"node_id": r["node_id"], "path": r["path"], + "children": [c for c in rows if c["parent"] == r["node_id"] and c["class"] == "Object"]} for r in matches] + self.report["browse"] = {"folders": folders, "rows": len(rows)} + return folders + + def raise_scripted(self, value=150): + self.r.device("set", address=20, value=value) + + def stop_watchers(self): + for watcher in self.watchers: + watcher.stop() + self.watchers = [] + + def audit(self, node, since): + """The origin's DataConnections audit lines (one per remote condition-method call) logged since `since`.""" + output = self.r.rig.compose("logs", "--no-color", "--since", since, node, timeout=60) + return [line for line in output.splitlines() if "Data-connection condition method" in line] + + def node_probe_async(self, node, operation, timeout_seconds, **fields): + identity = self.r.active + "-" + uuid.uuid4().hex + folder = self.r.rig.folder / "probe" / node + command = {"id": identity, "connectionId": "consumer-source", "operation": operation, "realm": "raw", "originCluster": "SOURCE", + "namespaceUri": "", "path": "", "timeoutSeconds": timeout_seconds, **fields} + rig.atomic_write_secret(folder / (identity + ".request.json"), json.dumps(command)) + def result(): + output = folder / (identity + ".result.json") + if not wait_for(output.exists, timeout_seconds + 20, 0.5): + raise scenarios.ScenarioError("node probe result missing") + raw = scenarios.restricted_json(output) + self.r.save(identity + ".probe.json", raw) + return raw + return result + + def probe_records(self, tag, **arguments): + output = self.r.folder / f"A4S-{self.r.active}-{tag}.json" + argv = ["dotnet", str(self.r.probe_dll), "--manifest", str(self.r.manifest_path), "--scenario", "condition-records", "--output", str(output)] + for key, value in arguments.items(): + argv += ["--" + key.replace("_", "-"), value] + self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=120) + return scenarios.restricted_json(output) if output.exists() else {"passed": False} + + # ---- scenarios -------------------------------------------------------------------------------------------------- + def scenario_A01(self): + """Scripted raise, ack, confirm via the consumer; origin and consumer both show each transition exactly once.""" + source, consumer = self.r.primary("source"), self.r.primary("consumer") + name = self.fixture["conditions"]["scripted"]["condition"] + origin = self.watch(source, "origin") + imported = self.watch(consumer, "consumer") + time.sleep(6) + self.raise_scripted() + active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) + if not self.check("consumer_imports_active_unacked", active): + return + condition = active["ConditionNodeId"] + self.report["condition_id"] = condition + self.check("imported_condition_id_is_opaque", condition.startswith("ns=") and "c1." in condition and "source-scalar-high" not in condition) + code, text = self.cli(consumer, "ack", "-n", condition, "-e", active["EventId"], "-c", "A01 consumer ack", tag="ack") + self.check("ack_good", code == 0 and "Acknowledge successful" in text) + acked = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Acknowledged"), None), 30) + self.check("consumer_sees_ack", acked) + time.sleep(5) + before = {"origin": len(origin.blocks(name)), "consumer": len(imported.blocks(name))} + self.report["ack_counts"] = {"origin": states(origin.blocks(name)).count("Active, Acknowledged"), + "consumer": states(imported.blocks(name)).count("Active, Acknowledged")} + self.check("origin_exactly_one_ack_event", self.report["ack_counts"]["origin"] == 1) + self.check("consumer_exactly_one_ack_event", self.report["ack_counts"]["consumer"] == 1) + latest = imported.blocks(name)[-1] if acked else active + code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A01 consumer confirm", tag="confirm") + self.report["confirm_output"] = text[-300:] + self.check("confirm_good", code == 0 and "Confirm successful" in text) + time.sleep(8) + after = {"origin": origin.blocks(name)[before["origin"]:], "consumer": imported.blocks(name)[before["consumer"]:]} + self.report["confirm_events"] = {k: [(b.get("State"), b.get("Message")) for b in v] for k, v in after.items()} + self.check("origin_exactly_one_confirm_event", len(after["origin"]) == 1) + self.check("consumer_exactly_one_confirm_event", len(after["consumer"]) == 1) + origin_condition = next((b.get("ConditionNodeId") for b in origin.blocks(name) if b.get("ConditionNodeId")), None) + self.report["origin_condition_id"] = origin_condition + confirmed = {"consumer": self.condition_child(consumer, condition, "ConfirmedState", "read-confirmed-consumer"), + "origin": self.condition_child(source, origin_condition, "ConfirmedState", "read-confirmed-origin") if origin_condition else None} + self.report["confirmed_state"] = confirmed + self.check("consumer_confirmed_state_true", (confirmed["consumer"] or {}).get("value") == "True") + self.check("origin_confirmed_state_true", (confirmed["origin"] or {}).get("value") == "True") + self.raise_scripted(0) + self.check("origin_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in origin.blocks(name)), 30)) + self.check("consumer_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 30)) + self.report["states"] = {"origin": states(origin.blocks(name)), "consumer": states(imported.blocks(name))} + + def scenario_A02(self): + """Native condition (OpcUaClient → opc-plc --alm): Ack + AddComment forwarded; Confirm refused BadNotSupported, unsent.""" + source, consumer = self.r.primary("source"), self.r.primary("consumer") + name = self.fixture["conditions"]["native"]["condition"] + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 2)) + origin = self.watch(source, "origin") + imported = self.watch(consumer, "consumer") + event = wait_for(lambda: next((b for b in reversed(imported.blocks(name)) if b.get("EventId") and b.get("ConditionNodeId")), None), 150) + self.report["origin_states"] = states(origin.blocks(name))[:20] + if not self.check("consumer_imports_native_condition", event): + return + condition = event["ConditionNodeId"] + self.report["condition_id"] = condition + self.check("origin_shows_native_condition", origin.blocks(name)) + self.check("imported_condition_id_is_opaque", "c1." in condition and "opcua/opcplc" not in condition) + code, text = self.cli(consumer, "ack", "-n", condition, "-e", "00" * 16, "-c", "A02 bogus", tag="ack-bogus") + self.check("bogus_eventid_refused", "BadEventIdUnknown" in text and "successful" not in text) + latest = imported.blocks(name)[-1] + code, text = self.cli(consumer, "ack", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer ack", tag="ack") + self.report["ack_output"] = text[-300:] + self.check("ack_good", code == 0 and "Acknowledge successful" in text) + latest = imported.blocks(name)[-1] + code, text = self.cli(consumer, "comment", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer comment", tag="comment") + self.report["comment_output"] = text[-300:] + self.check("comment_good", code == 0 and "successful" in text.lower() and "failed" not in text.lower()) + latest = imported.blocks(name)[-1] + code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer confirm", tag="confirm") + self.report["confirm_output"] = text[-300:] + self.check("confirm_refused_bad_not_supported", "BadNotSupported" in text and "Confirm successful" not in text) + time.sleep(6) + audit = self.audit(source, since) + self.report["origin_audit"] = audit[-20:] + joined = "\n".join(audit) + # Positive control: the ack and the comment reached the origin (audited); the confirm never did. + self.check("origin_audited_ack", re.search(r"condition method \W?Acknowledge\b", joined)) + self.check("origin_audited_comment", re.search(r"condition method \W?AddComment\b", joined)) + self.check("confirm_unsent", not re.search(r"condition method \W?Confirm\b", joined)) + self.report["consumer_states"] = states(imported.blocks(name))[-20:] + + def scenario_A04(self): + """One native alarm, three placements (Raw device + two referencing equipment) ⇒ one consumer condition, three + notifiers, one Server-object event per transition; the same ConditionId whichever subscriber came first; a UNS-only + origin principal's records carry no RawPath.""" + consumer, source = self.r.primary("consumer"), self.r.primary("source") + native = self.fixture["conditions"]["native"] + name = native["condition"] + folders = self.projected_folders(consumer) + mapping_aliases = ("raw", "pumpa", "pumpb") + if not self.check("three_branch_folders_resolved", all(len(folders.get(a, [])) == 1 for a in mapping_aliases)): + return + rounds = [] + for number, order in enumerate((("pumpa", "raw", "pumpb"), ("raw", "pumpb", "pumpa")), start=1): + if number == 2: + # Let the demand linger (30 s) expire so round 2 re-imports from scratch with a different first subscriber. + self.stop_watchers() + time.sleep(45) + folder_watches = {} + for alias in order: + candidates = [folders[alias][0]] + folders[alias][0]["children"][:3] + folder_watches[alias] = [(c["node_id"], self.watch(consumer, f"r{number}-{alias}-{i}", notifier=c["node_id"], refresh=False)) + for i, c in enumerate(candidates)] + time.sleep(2) + server = self.watch(consumer, f"r{number}-server") + window_start = time.time() + 8 + wait_for(lambda: len([b for b in server.blocks(name) if b.get("EventId")]) >= 4, 120) + time.sleep(6) + server_events = [b for b in server.blocks(name) if b.get("EventId") and not b.get("Message", "").startswith("Condition refresh")] + ids = {b.get("ConditionNodeId") for b in server_events} + event_ids = [b["EventId"] for b in server_events] + per_folder = {} + for alias, candidates in folder_watches.items(): + hits = [(node_id, [b["EventId"] for b in w.blocks(name) if b.get("EventId")]) for node_id, w in candidates] + notifier = next(((node_id, events) for node_id, events in hits if events), (None, [])) + per_folder[alias] = {"notifier": notifier[0], "events": len(notifier[1]), + "duplicates": len(notifier[1]) - len(set(notifier[1])), + "condition_ids": sorted({b.get("ConditionNodeId") for _, w in candidates for b in w.blocks(name)})} + # Overlap: every Server-object event raised after all subscribers were up reached each notifier exactly once. + late = [b["EventId"] for b in server_events if self._epoch(b.get("Time")) >= window_start] + for alias, candidates in folder_watches.items(): + seen = [e for node_id, w in candidates if node_id == per_folder[alias]["notifier"] for e in + [b["EventId"] for b in w.blocks(name) if b.get("EventId")]] + per_folder[alias]["late_server_events_missing"] = len([e for e in late if e not in seen]) + rounds.append({"order": order, "condition_ids": sorted(ids), "server_events": len(server_events), + "server_duplicate_event_ids": len(event_ids) - len(set(event_ids)), "late_events": len(late), "folders": per_folder}) + self.report["rounds"] = rounds + for index, round_ in enumerate(rounds, start=1): + self.check(f"r{index}_one_consumer_condition", len(round_["condition_ids"]) == 1) + self.check(f"r{index}_server_object_each_event_once", round_["server_events"] >= 1 and round_["server_duplicate_event_ids"] == 0) + self.check(f"r{index}_three_notifiers", all(round_["folders"][a]["notifier"] and round_["folders"][a]["duplicates"] == 0 for a in mapping_aliases)) + self.check(f"r{index}_notifiers_same_condition", all(round_["folders"][a]["condition_ids"] == round_["condition_ids"] for a in mapping_aliases)) + self.check(f"r{index}_late_events_reach_every_notifier", round_["late_events"] >= 1 + and all(round_["folders"][a]["late_server_events_missing"] == 0 for a in mapping_aliases)) + self.check("same_condition_id_both_orders", len(rounds) == 2 and rounds[0]["condition_ids"] == rounds[1]["condition_ids"]) + # UNS-only principal: no RawPath anywhere in its records; positive control = the Raw item under the full principal names it. + unsonly = self.probe_records("records-unsonly", node=source, key_name="source_unsonly", realm="uns", + identifier=native["equipment"]["pumpa"], subject=native["subjects"]["pumpa"], + forbid=native["raw_root"], expect=name) + control = self.probe_records("records-raw-control", node=source, key_name="source", realm="raw", + identifier=native["raw_root"], subject=native["raw_root"], expect=native["raw_root"]) + self.report["records"] = {"unsonly": self._records_summary(unsonly), "raw_control": self._records_summary(control)} + self.check("unsonly_records_carry_no_rawpath", unsonly.get("passed")) + self.check("raw_principal_records_name_rawpath_positive_control", control.get("passed")) + + def scenario_A05(self): + """ACLs off on the consumer: a session WITHOUT the mapping grant at i=2253 receives zero imported events, live or on + refresh, while a granted session sees them in the same window.""" + name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"] + with self.r.rig._configuration_experiment("a4s-acl-off", ("consumer-1", "consumer-2"), {"Security__Acl__Enabled": "false"}): + self.r.manifest = self.r.rig.load() + consumer = self.r.wait_primary("consumer") + self.report["acl_disabled_on"] = consumer + denied = self.watch(consumer, "nogrant", key=self.nogrant_key) + granted = self.watch(consumer, "granted") + time.sleep(5) + self.raise_scripted() + wait_for(lambda: granted.blocks(name) and granted.blocks(native), 150) + time.sleep(15) + # Second refresh pass for the denied session: a fresh subscription's ConditionRefresh replay must also be empty. + denied_refresh = self.watch(consumer, "nogrant-refresh", key=self.nogrant_key) + time.sleep(12) + self.raise_scripted(0) + time.sleep(8) + self.stop_watchers() + imported_denied = [b for w in (denied, denied_refresh) for b in w.blocks() if "c1." in (b.get("ConditionNodeId") or "") + or b.get("Condition") in (name, native)] + markers = [b for b in denied.blocks() if b.get("Message", "").startswith("Condition refresh")] + self.report["granted"] = {"scripted": len(granted.blocks(name)), "native": len(granted.blocks(native))} + self.report["denied"] = {"imported_events": len(imported_denied), "refresh_markers": len(markers), + "all_events": len(denied.blocks()) + len(denied_refresh.blocks())} + self.check("granted_session_sees_scripted_positive_control", granted.blocks(name)) + self.check("granted_session_sees_native_positive_control", granted.blocks(native)) + self.check("denied_session_alive_refresh_markers", markers) + self.check("denied_session_zero_imported_events", not imported_denied) + self.r.manifest = self.r.rig.load() + self.report["restored"] = "consumer pair restarted with Security__Acl__Enabled from compose.yml" + + def scenario_A08(self): + """Origin ACL loses AlarmAcknowledge ⇒ a consumer ack is denied while state keeps streaming; the consumer publishes + no /alerts (alarm-history) transition for imported conditions while the origin does (positive control).""" + name = self.fixture["conditions"]["scripted"]["condition"] + self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NO_ACK}) + self.r.manifest = self.r.rig.load() + source, consumer = self.r.primary("source"), self.r.primary("consumer") + origin_alerts = self.node_probe_async(source, "alert-transitions", 110) + consumer_alerts = self.node_probe_async(consumer, "alert-transitions", 110) + origin = self.watch(source, "origin") + imported = self.watch(consumer, "consumer") + time.sleep(6) + self.raise_scripted() + active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) + if self.check("state_streams_after_revocation", active): + code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 denied ack", tag="ack-denied") + self.report["denied_ack_output"] = text[-300:] + self.check("ack_denied", "Acknowledge successful" not in text and re.search(r"Bad\w*(Denied|Access|Permission)", text)) + time.sleep(5) + self.check("origin_not_acknowledged", "Active, Acknowledged" not in states(origin.blocks(name))) + self.raise_scripted(0) + self.check("consumer_still_streams_clear", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 40)) + origin_result, consumer_result = origin_alerts(), consumer_alerts() + origin_rows = origin_result.get("observations", {}).get("alarmTransitions", []) + consumer_rows = consumer_result.get("observations", {}).get("alarmTransitions", []) + self.report["alerts"] = {"origin": origin_rows, "consumer": consumer_rows, + "origin_probe_passed": origin_result.get("passed"), "consumer_probe_passed": consumer_result.get("passed")} + self.check("origin_alerts_positive_control", origin_result.get("passed") and any(r.get("alarmName") == name for r in origin_rows)) + self.check("consumer_alerts_stream_open", consumer_result.get("passed")) + self.check("consumer_no_alerts_for_imported", not consumer_rows) + # Positive control for the denial: grant restored ⇒ the same consumer ack is applied. + self.stop_watchers() + self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": ADMIN}) + self.r.manifest = self.r.rig.load() + consumer = self.r.primary("consumer") + imported = self.watch(consumer, "consumer-restored") + time.sleep(6) + self.raise_scripted() + active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) + if self.check("restored_raise_imported", active): + code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 restored ack", tag="ack-restored") + self.check("restored_ack_good_positive_control", code == 0 and "Acknowledge successful" in text) + self.raise_scripted(0) + time.sleep(4) + + # ---- helpers ---------------------------------------------------------------------------------------------------- + @staticmethod + def _epoch(stamp): + try: + from datetime import datetime + return datetime.fromisoformat((stamp or "")[:26].rstrip("Z") + "+00:00").timestamp() + except ValueError: + return 0 + + @staticmethod + def _records_summary(result): + rows = result.get("results") if isinstance(result, dict) else None + row = rows[0] if isinstance(rows, list) and rows else result + observations = row.get("observations", row) if isinstance(row, dict) else {} + return {"passed": result.get("passed") if isinstance(result, dict) else None, + "forbiddenFound": observations.get("forbiddenFound"), "expectedFound": observations.get("expectedFound"), + "records": [{"name": (r.get("info") or {}).get("ConditionName"), "placements": (r.get("info") or {}).get("placements")} + for r in observations.get("records", [])]} + + # ---- driver ----------------------------------------------------------------------------------------------------- + def run(self, selection): + self.r.publish() + self.r.rig.seed_helper("snapshot") + rows = [] + for scenario in selection: + self.r.active, self.r.count = "A4S-" + scenario, 0 + self.r.deadline = time.monotonic() + TIMEOUTS.get(scenario, 600) + self.report = {"id": scenario, "checks": {}, "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + self.watchers = [] + error = None + try: + getattr(self, "scenario_" + scenario)() + except Exception as failure: # recorded, never hides restoration + error = type(failure).__name__ + ": " + str(failure)[:400] + finally: + self.stop_watchers() + try: + self.r.device("set", address=20, value=0) + if scenario in ("A08",): + self.r.deadline = time.monotonic() + 600 + self.r.baseline() + self.report["restored"] = self.report.get("restored", True) + except Exception as failure: + self.report["restored"] = False + error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure)[:200] + self.report["error"] = error + self.report["passed"] = error is None and bool(self.report["checks"]) and all(self.report["checks"].values()) + self.r.save(f"A4S-{scenario}.json", self.report) + rows.append({"id": scenario, "passed": self.report["passed"], "error": error, + "failed_checks": [k for k, v in self.report["checks"].items() if not v], "restored": self.report["restored"]}) + print(json.dumps(rows[-1]), flush=True) + summary = {"run_id": self.r.manifest["run_id"], "source_revision": self.r.manifest.get("source_revision"), "rows": rows, + "passed": all(row["passed"] for row in rows)} + self.r.save("A4S-results.json", summary) + lines = ["| Scenario | Result | Failed checks | Restored |", "|---|---|---|---|"] + lines += [f"| {row['id']} | {'PASS' if row['passed'] else 'FAIL'} | {', '.join(row['failed_checks']) or (row['error'] or '—')} | {row['restored']} |" for row in rows] + rig.atomic_write_secret(self.r.folder / "A4S-results.md", "\n".join(lines) + "\n") + return summary + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--run-id", required=True) + parser.add_argument("--only", default=",".join(SCENARIOS), help="comma-separated scenario ids (default: all implemented)") + arguments = parser.parse_args(argv) + selection = [item.strip() for item in arguments.only.split(",") if item.strip()] + unknown = [item for item in selection if item not in SCENARIOS] + if unknown: + parser.error("unknown scenario(s): " + ", ".join(unknown)) + summary = ConditionScenarios(arguments.run_id).run(selection) + print(json.dumps(summary, indent=2)) + return 0 if summary["passed"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs index d6cffebb4..9acde740c 100644 --- a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs +++ b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs @@ -137,6 +137,46 @@ public sealed partial class NodeProbeWorker(IServiceProvider services) : Backgro return new(command.Id, command.Operation, false, assertions, observations, error.GetType().Name); } } + /// + /// A4 (A08/§5.7): listen to THIS node's own authenticated telemetry stream for the command's window and return every + /// alerts transition it carries — the exact feed central's /alerts page and the alarm-history adapter + /// consume. A consumer node must publish none for imported conditions; the SOURCE Primary's list is the positive control. + /// + private static async Task AlertTransitionsAsync(ProbeCommand command, CancellationToken cancellationToken) + { + var observations = new Dictionary(); + var transitions = new List(); + var envelopes = 0; + var host = Environment.GetEnvironmentVariable("HOSTNAME"); + var key = Environment.GetEnvironmentVariable("Telemetry__ApiKey"); + if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(key) || command.TimeoutSeconds is < 3 or > 120) + return new(command.Id, command.Operation, false, 0, observations, "InvalidCommand"); + using var handler = new SocketsHttpHandler { AllowAutoRedirect = false, UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(5) }; + using var channel = GrpcChannel.ForAddress($"http://{host}:4056", new GrpcChannelOptions { HttpHandler = handler, MaxReceiveMessageSize = 1024 * 1024 }); + var client = new T.TelemetryStreamService.TelemetryStreamServiceClient(channel); + var headers = new Metadata { { "authorization", "Bearer " + key } }; + string? failure = null; + try + { + using var call = client.Subscribe(new T.TelemetryStreamRequest { CorrelationId = command.Id }, headers, + deadline: DateTime.UtcNow.AddSeconds(command.TimeoutSeconds - 2), cancellationToken: cancellationToken); + while (await call.ResponseStream.MoveNext(cancellationToken)) + { + envelopes++; + if (call.ResponseStream.Current.AlarmTransition is { } alarm) + transitions.Add(new { alarmId = alarm.AlarmId, alarmName = alarm.AlarmName, kind = alarm.TransitionKind, + equipmentPath = alarm.EquipmentPath, user = alarm.User, comment = alarm.HasComment ? alarm.Comment : null, + at = alarm.TimestampUtc?.ToDateTime().ToString("O") }); + } + } + catch (RpcException error) when (error.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled) { } + catch (Exception error) when (error is not OutOfMemoryException) { failure = error.GetType().Name; } + observations["node"] = host; + observations["envelopes"] = envelopes; + observations["alarmTransitions"] = transitions; + return new(command.Id, command.Operation, failure is null, 1, observations, failure); + } + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var configured = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR"); @@ -217,6 +257,10 @@ public sealed partial class NodeProbeWorker(IServiceProvider services) : Backgro { result = CaptureProjectionDiagnostics(command); } + else if (command.Operation == "alert-transitions") + { + result = await AlertTransitionsAsync(command, timeout.Token); + } else if (command.Operation == "legacy-telemetry") { // Feature-disable validation must bypass DataConnection acquisition. diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs index 9e4664525..dd51120dd 100644 --- a/scripts/validation/grpc-data/probe/Program.cs +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -26,7 +26,7 @@ try using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); var root = manifest.RootElement; var scenario = arguments.GetValueOrDefault("--scenario", "all"); - if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions")) throw new ArgumentException("Unsupported wire scenario."); + if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario."); var nodes = root.GetProperty("nodes"); var endpoints = root.GetProperty("endpoints"); var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; @@ -395,7 +395,74 @@ try if (primary && flipped) await SetScalar(150); // restore for the other node } } - if (scenario is not ("D13" or "history" or "conditions")) + if (scenario == "condition-records") + { + // A4 (A04): one root-scoped condition item, opened on ONE named SOURCE listener under a NAMED principal's data key + // (`--key-name` = a manifest data_key_files alias), returning its complete snapshot records (placements included). + // `--forbid` must occur nowhere in the records (a UNS-only principal: no RawPath); `--expect` must occur (positive control). + failurePhase = ProbeFailurePhase.WireOperation; + var name = arguments["--node"]; + if (name is not ("source-1" or "source-2")) throw new ArgumentException("SOURCE listener required."); + failureTarget = name; + var principalKeyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty(arguments["--key-name"]).GetString()!; + Restricted(principalKeyPath); + var principalKey = (await File.ReadAllTextAsync(principalKeyPath)).Trim(); + var realmName = arguments["--realm"]; + var realm = realmName == "raw" ? DataRealm.Raw : realmName == "uns" ? DataRealm.Uns : throw new ArgumentException("realm"); + var view = new W.View { Address = new() { OriginClusterId = "SOURCE", IdentifierKind = "string", Identifier = arguments["--identifier"], + NamespaceUri = root.GetProperty("fixture").GetProperty("namespace_uris").GetProperty(realmName).GetString()! }, + Realm = (int)realm, Subject = arguments["--subject"] }; + var nodeId = sourceNodes.Single(item => item.Name == name).Value.GetProperty("node_id").GetString()!; + var headers = Headers(principalKey, "Node", nodeId); + headers.Add("x-otopcua-data-features", "conditions"); + using var handler = security.Handler(name); + using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(45)); + using var call = client.Subscribe(headers, cancellationToken: cts.Token); + var open = new W.SubscriptionCommand { SubscriptionId = "records-" + Guid.NewGuid().ToString("N")[..8], StreamEpoch = 1, CommandId = "open-1", + AcknowledgementTimeoutTicks = TimeSpan.FromSeconds(10).Ticks, Open = new() { SessionLifetimeTicks = TimeSpan.FromMinutes(5).Ticks, + SnapshotBudget = new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 64, MaxBytes = 4 * 1024 * 1024 } } }; + open.Open.Items.Add(new W.SubscriptionItem { ClientItemId = "records", View = view, Settings = new() { Trigger = 2 }, ConditionScope = new() { IncludeInfo = true } }); + await call.RequestStream.WriteAsync(open); + int? ackStatus = null, total = null; + var snapshot = new List(); + var complete = false; + string? ended = null; + try + { + while (await call.ResponseStream.MoveNext(cts.Token)) + { + var frame = call.ResponseStream.Current; + if (frame.Ack is { } ack) { ackStatus = ack.Items.Single().Status; if (ackStatus != 1) break; continue; } + if (frame.ConditionStates is not { IsSnapshot: true } states) continue; + if (states.HasTotal) { total = states.Total; snapshot.Clear(); } + snapshot.AddRange(states.Items); + if (states.SnapshotComplete) { complete = true; break; } + } + } + catch (RpcException error) { ended = error.StatusCode.ToString(); } + await cts.CancelAsync(); + var records = snapshot.Select(r => (object)new + { + key = r.ConditionKey, r.StateKnown, r.Active, r.Acknowledged, r.Severity, r.Message, + info = r.Info is null ? null : new { r.Info.ConditionType, r.Info.ConditionName, r.Info.SourceKind, + placements = r.Info.Placements.Select(p => new { realm = p.Realm, ns = p.Address.NamespaceUri, id = p.Address.Identifier, subject = p.Subject }).ToArray() }, + raw = r.ToString(), + }).ToArray(); + var text = JsonSerializer.Serialize(records); + var forbid = arguments.GetValueOrDefault("--forbid"); + var expect = arguments.GetValueOrDefault("--expect"); + var forbidden = forbid is not null && text.Contains(forbid, StringComparison.Ordinal); + var expected = expect is null || text.Contains(expect, StringComparison.Ordinal); + results.Add(new("condition-records-" + name, "condition-records", ackStatus == 1 && complete && snapshot.Count >= 1 && !forbidden && expected, 4, new() + { + ["principal"] = arguments["--key-name"], ["realm"] = realmName, ["subject"] = view.Subject, ["ackStatus"] = ackStatus, ["total"] = total, + ["snapshotComplete"] = complete, ["ended"] = ended, ["records"] = records, ["forbid"] = forbid, ["forbiddenFound"] = forbidden, + ["expect"] = expect, ["expectedFound"] = expected, + })); + } + if (scenario is not ("D13" or "history" or "conditions" or "condition-records")) { var fixture = root.GetProperty("fixture"); var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index ffbbdd02f..69f6247fa 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -473,8 +473,9 @@ def require_production_prerequisites(action, available): ROOT = Path(__file__).resolve().parents[3] HERE = Path(__file__).resolve().parent NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2)) -# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml); listing it is the DNS allowlist. -SERVICES = ("sql", "migrator", "device", "seeder", "questdb", *NODES) +# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml), `opcplc` only on a `--conditions` +# run (compose.conditions.yml); listing them is the DNS allowlist. +SERVICES = ("sql", "migrator", "device", "seeder", "questdb", "opcplc", *NODES) HISTORY_BACKENDS = ("sqlserver", "questdb") @@ -948,6 +949,10 @@ class LocalRig: "data_key_files": {"source": str(self.folder / "seed" / "source.key")}} if self.environment.get("GRPC_DATA_HISTORY") == "1": manifest["credentials"]["data_key_files"]["source_nohistory"] = str(self.folder / "seed" / "source-nohistory.key") + if self.environment.get("GRPC_DATA_CONDITIONS") == "1": + # A4: the UNS-only origin principal (A04) and the CONSUMER CLI principal without a mapping grant (A05). + manifest["credentials"]["data_key_files"]["source_unsonly"] = str(self.folder / "seed" / "source-unsonly.key") + manifest["credentials"]["data_key_files"]["cli_nogrant"] = str(self.folder / "seed" / "cli-nogrant.key") manifest["state"] = "seeded" self.capture(manifest) return manifest diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 8b30abfb5..2e901efd2 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -327,6 +327,7 @@ try return 0; } if (args[0] != "seed") return 2; + var pumpEquipment = new Dictionary(StringComparer.Ordinal); // A4: pump equipment name → EquipmentId await using (var db = await factory.CreateDbContextAsync()) { if (await db.ServerClusters.AnyAsync()) throw new InvalidOperationException("fixture seed requires empty owned database"); @@ -382,6 +383,27 @@ try SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(predicate))) }); db.ScriptedAlarms.Add(new() { ScriptedAlarmRowId = Guid.NewGuid(), ScriptedAlarmId = "source-scalar-high", EquipmentId = equipment, Name = "ScalarHigh", AlarmType = "AlarmCondition", MessageTemplate = "scalar high", PredicateScriptId = "source-scalar-high" }); + // A4 live scenarios (A02/A04): an OpcUaClient driver against the run-owned opc-plc `--alm` container (compose.conditions.yml), + // one native alarm tag bound 1:1 to the upstream CONDITION node EastTank?Red (several conditions share the EastTank source, + // so the source node would fold them; docs/drivers/OpcUaClient.md "Native alarms"), and a value control tag. The alarm tag is + // referenced by two NEW equipment (pumpa, pumpb) so the A2a/A3 smokes' `plc` equipment view is unchanged. + db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-opcua", ClusterId = "SOURCE", Name = "opcua", DriverType = "OpcUaClient", + DriverConfig = """{"SecurityPolicy":"None","SecurityMode":"None","AuthType":"Anonymous","AutoAcceptCertificates":true}""" }); + db.Devices.Add(new() { DeviceRowId = Guid.NewGuid(), DeviceId = "source-opcplc", DriverInstanceId = "source-opcua", Name = "opcplc", + DeviceConfig = """{"EndpointUrl":"opc.tcp://opcplc:50000"}""" }); + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-fast", DeviceId = "source-opcplc", Name = "FastUInt1", DataType = "UInt32", + AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, TagConfig = """{"nodeId":"ns=3;s=FastUInt1"}""" }); + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-red", DeviceId = "source-opcplc", Name = "EastTankRed", DataType = "Boolean", + AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, + TagConfig = """{"nodeId":"ns=6;s=1:Colours/EastTank?Red","alarm":{"alarmType":"AlarmCondition","severity":500}}""" }); + foreach (var pump in new[] { "pumpa", "pumpb" }) + { + var pumpUuid = Guid.NewGuid(); + var pumpId = DraftValidator.DeriveEquipmentId(pumpUuid); + pumpEquipment[pump] = pumpId; + db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = pumpId, EquipmentUuid = pumpUuid, UnsLineId = "source-line", Name = pump, MachineCode = "fixture-" + pump }); + db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + pump + "-red", EquipmentId = pumpId, TagId = "source-opcua-red" }); + } } db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); @@ -415,6 +437,31 @@ try db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead }); } + if (conditions) + { + // A4: exports + CONSUMER mappings for the native alarm's three placements — the Raw opc-plc device and the two + // UNS equipment that reference it (A04: one consumer condition, three notifiers). Distinct branch names. + var conditionOps = operations | DataOperationSets.ConditionGrants; + foreach (var (id, realm, rootKind, entity, identifier) in new[] { + ("opc", DataRealm.Raw, "RawDevice", "source-opcplc", "opcua/opcplc"), + ("pumpa", DataRealm.Uns, "Equipment", pumpEquipment["pumpa"], pumpEquipment["pumpa"]), + ("pumpb", DataRealm.Uns, "Equipment", pumpEquipment["pumpb"], pumpEquipment["pumpb"]) }) + { + db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + id, ClusterId = "SOURCE", Enabled = true, + Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = conditionOps }); + db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-" + id, + ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], + Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-" + id, + RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, + RemoteIdentifierKind = "string", RemoteIdentifier = identifier, AllowedOperations = conditionOps, WriteThrough = false }); + } + // A04: a UNS-ONLY origin principal (one UNS export, no Raw export) — its condition records must carry no RawPath. + db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-pumpa-unsonly", ClusterId = "SOURCE", Enabled = true, + Realm = DataRealm.Uns, RootKind = "Equipment", RootEntityId = pumpEquipment["pumpa"], PrincipalId = "fixture-unsonly", AllowedOperations = conditionOps }); + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-unsonly", ClusterId = "SOURCE", Principal = "fixture-unsonly", + ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); + // A05: the CONSUMER-local principal `fixture-cli-nogrant` deliberately has NO NodeAcl row (no mapping grant). + } if (history) // The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused // (PermissionDenied, like v1 Read); granting the export bit then leaves the per-node ACL denial (BadHistoryOperationUnsupported). @@ -425,6 +472,11 @@ try var seedAdmin = new ApiKeyAdminService(factory, pepper); await SaveText("cli.key", await seedAdmin.CreateAsync("fixture-cli", "fixture-cli", null, "owned local fixture", default)); await SaveText("source.key", await seedAdmin.CreateAsync("source-issued-consumer", "fixture-consumer", null, "SOURCE grants for CONSUMER", default)); + if (conditions) + { + await SaveText("source-unsonly.key", await seedAdmin.CreateAsync("source-issued-unsonly", "fixture-unsonly", null, "SOURCE UNS-only export (A04)", default)); + await SaveText("cli-nogrant.key", await seedAdmin.CreateAsync("fixture-cli-nogrant", "fixture-cli-nogrant", null, "CONSUMER principal without a mapping grant (A05)", default)); + } if (history) await SaveText("source-nohistory.key", await seedAdmin.CreateAsync("source-issued-nohistory", "fixture-nohistory", null, "SOURCE export without HistoryRead", default)); string unsBrowseRoot; @@ -433,7 +485,7 @@ try var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db); var errors = DraftValidator.Validate(snapshot).Concat(snapshot.ServerClusters.SelectMany(cluster => DraftValidator.ValidateClusterTopology(cluster, snapshot.ClusterNodes.Where(node => node.ClusterId == cluster.ClusterId).ToList()))).ToList(); if (errors.Count != 0) throw new InvalidOperationException("production validator rejected fixture"); - unsBrowseRoot = await db.Equipment.Select(item => item.EquipmentId).SingleAsync(); + unsBrowseRoot = await db.Equipment.Where(item => item.Name == "plc").Select(item => item.EquipmentId).SingleAsync(); } await Save("fixture.json", new { connection_id = "consumer-source", mapping_ids = new[] { "map-raw", "map-uns" }, namespace_uris = new { raw = V3NodeIds.RawNamespaceUri, uns = V3NodeIds.UnsNamespaceUri, mapped_raw = ProjectedDataIds.RawNamespaceUri, mapped_uns = ProjectedDataIds.UnsNamespaceUri }, @@ -441,7 +493,13 @@ try browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" }, origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" }, history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" }, - historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null }); + historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null, + // A4 live scenarios: where the native alarm lives (origin RawPath + equipment) and which consumer mappings place it. + conditions = conditions ? new { scripted = new { condition = "ScalarHigh", origin_id = "source-scalar-high", mapping = "map-uns", branch = "remote-source" }, + native = new { condition = "EastTankRed", raw_path = "opcua/opcplc/EastTankRed", upstream = "ns=6;s=1:Colours/EastTank?Red", + equipment = pumpEquipment, subjects = new { pumpa = "area/line/pumpa", pumpb = "area/line/pumpb" }, raw_root = "opcua/opcplc", + mappings = new { raw = "map-opc", pumpa = "map-pumpa", pumpb = "map-pumpb" }, + branches = new { raw = "remote-opc", pumpa = "remote-pumpa", pumpb = "remote-pumpb" } } } : null }); return 0; } catch (Exception error)