test(grpc-data): H2 live smoke on the standalone rig - denied-principal modes, pinned-build check, parity; evidence
This commit is contained in:
@@ -83,6 +83,16 @@ prune or prefix-based deletion. Interrupted setup leaves a restricted ownership
|
||||
journal that enables the same cleanup. Run files are retained for evidence;
|
||||
use a new run ID for another run.
|
||||
|
||||
## H2 history profile (opt-in)
|
||||
|
||||
`rig.py up --run-id <id> --history` adds `compose.history.yml`. SOURCE gets a SqlServer historian (schema `hist` in the
|
||||
run's SQL container) and continuous historization. The seeder's history profile historizes Raw `counter`, adds HistoryRead to
|
||||
the consumer's connection and exports, and seeds a second principal `fixture-nohistory`. That principal gets its own key
|
||||
(`credentials.data_key_files.source_nohistory`), exports without HistoryRead and an origin ACL without HistoryRead.
|
||||
`python3 scripts/validation/grpc-data/history_smoke.py --run-id <id>` runs the H2 smoke. It advances the counter, then exercises
|
||||
the probe's `--scenario history` origin RPCs, the CLI `historyread` and the CONSUMER `history` node-probe operation, and checks
|
||||
value parity. Without `--history` the rig, the seed and every D-scenario are unchanged.
|
||||
|
||||
## Scenario authoring and node probes
|
||||
|
||||
The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its
|
||||
|
||||
@@ -23,27 +23,61 @@ def _iso(moment):
|
||||
|
||||
|
||||
def _cli_rows(stdout):
|
||||
"""`historyread` rows → [(source time ISO, value text, status text)]."""
|
||||
"""`historyread` rows (`<source time O> <value> <Good|Bad|Uncertain>`) → [(UTC datetime, value text, quality)]."""
|
||||
rows = []
|
||||
for line in stdout.splitlines():
|
||||
match = re.match(r"^\s*(\d{4}-\d{2}-\d{2}[T ][0-9:.]+Z?)\s*\|?\s*(.*)$", line)
|
||||
if match:
|
||||
rows.append((match[1], match[2].strip()))
|
||||
parts = line.split()
|
||||
if len(parts) == 3 and parts[2] in {"Good", "Bad", "Uncertain"} and re.match(r"^\d{4}-\d{2}-\d{2}T", parts[0]):
|
||||
rows.append((_parse(parts[0]), parts[1], parts[2]))
|
||||
return rows
|
||||
|
||||
|
||||
def _parse(text):
|
||||
"""ISO 8601 with up to 7 fractional digits → aware datetime truncated to microseconds."""
|
||||
match = re.match(r"^(.*?T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$", text)
|
||||
fraction = (match[2] or "")[:6].ljust(6, "0")
|
||||
zone = match[3] or "Z"
|
||||
return datetime.fromisoformat(match[1] + "." + fraction + ("+00:00" if zone == "Z" else zone))
|
||||
|
||||
|
||||
def _wire_rows(samples):
|
||||
rows = []
|
||||
for sample in samples:
|
||||
value = json.loads(sample["value"])
|
||||
scalar = next(v for k, v in value.items() if k != "kind")
|
||||
rows.append((_parse(sample["sourceTimestampUtc"]), str(scalar), "Good" if int(sample["statusCode"], 16) >> 30 == 0 else "Other"))
|
||||
return rows
|
||||
|
||||
|
||||
def compare(cli_stdout, wire_samples):
|
||||
cli, wire = _cli_rows(cli_stdout), _wire_rows(wire_samples)
|
||||
return {"cli_count": len(cli), "wire_count": len(wire), "identical": cli == wire and len(cli) > 0,
|
||||
"first": [str(x) for x in (cli[:1] + wire[:1])], "last": [str(x) for x in (cli[-1:] + wire[-1:])]}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--run-id", required=True)
|
||||
parser.add_argument("--accumulate-seconds", type=int, default=40)
|
||||
parser.add_argument("--denied-expect", choices=("permission-denied", "unsupported"), default="permission-denied",
|
||||
help="the second principal: export lacks HistoryRead (RPC PermissionDenied) or export granted + ACL denies (per-item 0x80720000)")
|
||||
parser.add_argument("--label", default="smoke", help="evidence file suffix")
|
||||
parser.add_argument("--pinned-build", action="store_true",
|
||||
help="the checkout moved after `up`: verify the running Host stamps against the run's RECORDED build hash "
|
||||
"instead of the current checkout (recorded in the report; tools publish from the current checkout)")
|
||||
arguments = parser.parse_args(argv)
|
||||
current_hash = rig.source_tree_hash()
|
||||
if arguments.pinned_build:
|
||||
recorded = scenarios.restricted_json(rig.LocalRig(arguments.run_id).path)["source_tree_hash"]
|
||||
rig.source_tree_hash = lambda: recorded
|
||||
runner = scenarios.ScenarioRunner(arguments.run_id)
|
||||
if runner.manifest["fixture"].get("history") is None:
|
||||
raise SystemExit("run was not brought up with --history")
|
||||
runner.active, runner.deadline = "H2", time.monotonic() + 900
|
||||
runner.publish()
|
||||
report = {"run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"),
|
||||
"source_tree_hash": runner.manifest.get("source_tree_hash"), "items": {}}
|
||||
report = {"denied_expect": arguments.denied_expect, "run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"),
|
||||
"source_tree_hash": runner.manifest.get("source_tree_hash"), "checkout_tree_hash_at_smoke": current_hash,
|
||||
"pinned_build": arguments.pinned_build, "items": {}}
|
||||
|
||||
# 1. Accumulate history: one counter step per second.
|
||||
started = datetime.now(timezone.utc)
|
||||
@@ -58,10 +92,11 @@ def main(argv=None):
|
||||
"window": [_iso(window_start), _iso(window_end)], "device": runner.device()}
|
||||
|
||||
# 2. Origin RPCs on both SOURCE data listeners.
|
||||
output = runner.folder / "H2-history-wire.json"
|
||||
output = runner.folder / ("H2-history-wire-" + arguments.label + ".json")
|
||||
result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "history",
|
||||
"--history-start", _iso(window_start), "--history-end", _iso(window_end), "--output", str(output)],
|
||||
"H2-history-wire", timeout=120)
|
||||
"--history-start", _iso(window_start), "--history-end", _iso(window_end),
|
||||
"--denied-expect", arguments.denied_expect, "--output", str(output)],
|
||||
"H2-history-wire-" + arguments.label, timeout=120)
|
||||
wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]}
|
||||
report["items"]["wire"] = wire
|
||||
|
||||
@@ -99,10 +134,23 @@ def main(argv=None):
|
||||
observed[name] = {"passed": False, "error": type(error).__name__ + ": " + str(error)}
|
||||
consumer[node] = observed
|
||||
report["items"]["consumer"] = consumer
|
||||
runner.save("H2-history-smoke.json", report)
|
||||
print(json.dumps({"saved": str(runner.folder / "H2-history-smoke.json"), "wire_passed": wire.get("passed"),
|
||||
|
||||
# 5. Value parity: OPC UA historyread on the SOURCE node vs the remote origin read vs the runtime consumer, same window.
|
||||
parity = {}
|
||||
for result_row in wire.get("results", []):
|
||||
if result_row["id"].startswith("history-window-"):
|
||||
node = result_row["id"][len("history-window-"):]
|
||||
parity["wire-" + node + "-vs-cli-" + node] = compare(cli[node]["stdout"], result_row["observations"]["samples"])
|
||||
for node, rows in consumer.items():
|
||||
if rows["window"]["passed"]:
|
||||
samples = rows["window"]["observations"]["pages"][0]["samples"]
|
||||
parity["consumer-" + node + "-vs-cli-source-1"] = compare(cli["source-1"]["stdout"], samples)
|
||||
report["items"]["parity"] = parity
|
||||
runner.save("H2-history-" + arguments.label + ".json", report)
|
||||
print(json.dumps({"saved": str(runner.folder / ("H2-history-" + arguments.label + ".json")), "wire_passed": wire.get("passed"),
|
||||
"consumer": {node: {k: v["passed"] for k, v in rows.items()} for node, rows in consumer.items()},
|
||||
"cli": {node: row["returncode"] for node, row in cli.items()}}, indent=2))
|
||||
"cli": {node: row["returncode"] for node, row in cli.items()},
|
||||
"parity": {k: v["identical"] for k, v in parity.items()}}, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -209,17 +209,29 @@ try
|
||||
["serving"] = featured.Serving.ToString(),
|
||||
}));
|
||||
// 3. Unhistorized tag and the no-HistoryRead principal answer the same bytes; no header ⇒ FAILED_PRECONDITION.
|
||||
// --denied-expect: `permission-denied` (the second principal's export lacks HistoryRead ⇒ RPC refused) or
|
||||
// `unsupported` (export granted, origin ACL denies ⇒ per-item, byte-identical to the unhistorized answer).
|
||||
var deniedExpect = arguments.GetValueOrDefault("--denied-expect", "unsupported");
|
||||
var unhist = (await client.HistoryReadAsync(Raw(View(unhistorized), null), With(key, true), deadline())).Items.Single();
|
||||
var denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single();
|
||||
var identical = Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
|
||||
W.HistoryReadResult? denied = null;
|
||||
string? deniedRpc = null;
|
||||
try { denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single(); }
|
||||
catch (RpcException error) { deniedRpc = error.StatusCode.ToString(); }
|
||||
var otherCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(otherKey, true), deadline());
|
||||
var identical = denied is not null && Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
|
||||
var deniedOk = deniedExpect == "permission-denied"
|
||||
? deniedRpc == "PermissionDenied"
|
||||
: denied is not null && denied.StatusCode == 0x80720000u && identical;
|
||||
string? precondition = null;
|
||||
try { await client.HistoryReadAsync(Raw(View(historized), null), With(key, false), deadline()); precondition = "OK"; }
|
||||
catch (RpcException error) { precondition = error.StatusCode.ToString(); }
|
||||
results.Add(new("history-refusals-" + name, "history-refusals",
|
||||
unhist.StatusCode == 0x80720000u && denied.StatusCode == 0x80720000u && identical && precondition == "FailedPrecondition", 4, new()
|
||||
unhist.StatusCode == 0x80720000u && deniedOk && precondition == "FailedPrecondition", 3, new()
|
||||
{
|
||||
["unhistorized"] = new { statusCode = Hex(unhist.StatusCode), unhist.Samples.Count, unhist.HasContinuation, unhist.HasDiagnostic, bytes = Convert.ToHexString(Shape(unhist)) },
|
||||
["deniedPrincipal"] = new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
|
||||
["deniedExpect"] = deniedExpect,
|
||||
["deniedPrincipal"] = denied is null ? new { rpcStatus = deniedRpc } : (object)new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
|
||||
["deniedPrincipalCapabilities"] = new { operations = otherCaps.Operations, historyPresent = otherCaps.History is not null },
|
||||
["byteIdentical"] = identical,
|
||||
["withoutFeatureHeader"] = precondition,
|
||||
}));
|
||||
|
||||
@@ -379,8 +379,10 @@ try
|
||||
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true });
|
||||
}
|
||||
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).
|
||||
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-nohistory", ClusterId = "SOURCE", Principal = "fixture-nohistory",
|
||||
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
|
||||
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly & ~NodePermissions.HistoryRead });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
var seedAdmin = new ApiKeyAdminService(factory, pepper);
|
||||
|
||||
Reference in New Issue
Block a user