nvs-runtime 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nvs_runtime/__init__.py +29 -0
- nvs_runtime/__version__.py +3 -0
- nvs_runtime/config/__init__.py +3 -0
- nvs_runtime/config/settings.py +26 -0
- nvs_runtime/core/__init__.py +6 -0
- nvs_runtime/core/clock.py +32 -0
- nvs_runtime/core/composition.py +92 -0
- nvs_runtime/core/errors.py +69 -0
- nvs_runtime/core/hext.py +43 -0
- nvs_runtime/core/models.py +151 -0
- nvs_runtime/core/protocols.py +77 -0
- nvs_runtime/core/runtime.py +373 -0
- nvs_runtime/events/__init__.py +4 -0
- nvs_runtime/events/bus.py +50 -0
- nvs_runtime/events/types.py +35 -0
- nvs_runtime/executors/__init__.py +2 -0
- nvs_runtime/governance/__init__.py +4 -0
- nvs_runtime/governance/engine.py +58 -0
- nvs_runtime/governance/quota.py +48 -0
- nvs_runtime/graph/__init__.py +3 -0
- nvs_runtime/graph/capability_graph.py +100 -0
- nvs_runtime/hidden_trajectory/__init__.py +62 -0
- nvs_runtime/hidden_trajectory/_gate_child.py +375 -0
- nvs_runtime/hidden_trajectory/adapter_loader.py +70 -0
- nvs_runtime/hidden_trajectory/canonical.py +22 -0
- nvs_runtime/hidden_trajectory/capture_archive.py +204 -0
- nvs_runtime/hidden_trajectory/capture_chain.py +319 -0
- nvs_runtime/hidden_trajectory/cli.py +765 -0
- nvs_runtime/hidden_trajectory/envelope.py +303 -0
- nvs_runtime/hidden_trajectory/formal_save.py +499 -0
- nvs_runtime/hidden_trajectory/formal_writer.py +590 -0
- nvs_runtime/hidden_trajectory/gate_client.py +460 -0
- nvs_runtime/hidden_trajectory/item_set.py +317 -0
- nvs_runtime/hidden_trajectory/k_measure.py +145 -0
- nvs_runtime/hidden_trajectory/model_catalog.py +56 -0
- nvs_runtime/hidden_trajectory/payload.py +382 -0
- nvs_runtime/hidden_trajectory/phase2/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase2/evaluate.py +319 -0
- nvs_runtime/hidden_trajectory/phase2/geometry.py +80 -0
- nvs_runtime/hidden_trajectory/phase2/labels.py +72 -0
- nvs_runtime/hidden_trajectory/phase4/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4/normalize.py +171 -0
- nvs_runtime/hidden_trajectory/phase4/summary.py +270 -0
- nvs_runtime/hidden_trajectory/phase4b/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4b/load.py +46 -0
- nvs_runtime/hidden_trajectory/phase4b/metrics.py +96 -0
- nvs_runtime/hidden_trajectory/phase4b/scan.py +33 -0
- nvs_runtime/hidden_trajectory/record.py +334 -0
- nvs_runtime/hidden_trajectory/record_schema.py +781 -0
- nvs_runtime/hidden_trajectory/replay/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/replay/risk_control.py +196 -0
- nvs_runtime/hidden_trajectory/rerun.py +302 -0
- nvs_runtime/hidden_trajectory/rsa/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/rsa/analysis.py +248 -0
- nvs_runtime/hidden_trajectory/rsa/calibration.py +659 -0
- nvs_runtime/hidden_trajectory/rsa/compare.py +714 -0
- nvs_runtime/hidden_trajectory/rsa/readout.py +192 -0
- nvs_runtime/hidden_trajectory/run.py +362 -0
- nvs_runtime/hidden_trajectory/token_temporal.py +368 -0
- nvs_runtime/hidden_trajectory/window.py +344 -0
- nvs_runtime/integrations/__init__.py +4 -0
- nvs_runtime/integrations/hekb_formal.py +169 -0
- nvs_runtime/integrations/hekb_vnext.py +302 -0
- nvs_runtime/metrics/__init__.py +3 -0
- nvs_runtime/metrics/collector.py +63 -0
- nvs_runtime/observability/__init__.py +3 -0
- nvs_runtime/observability/store.py +44 -0
- nvs_runtime/planner/__init__.py +3 -0
- nvs_runtime/planner/planner.py +158 -0
- nvs_runtime/providers/__init__.py +19 -0
- nvs_runtime/providers/base.py +43 -0
- nvs_runtime/providers/edge.py +165 -0
- nvs_runtime/providers/grpc.py +58 -0
- nvs_runtime/providers/hekb.py +77 -0
- nvs_runtime/providers/http.py +59 -0
- nvs_runtime/providers/kernel.py +67 -0
- nvs_runtime/providers/local.py +88 -0
- nvs_runtime/providers/mcp.py +84 -0
- nvs_runtime/providers/registry.py +56 -0
- nvs_runtime/providers/replay.py +138 -0
- nvs_runtime/py.typed +0 -0
- nvs_runtime/security/__init__.py +4 -0
- nvs_runtime/security/cbac.py +106 -0
- nvs_runtime/security/signer.py +20 -0
- nvs_runtime/session/__init__.py +4 -0
- nvs_runtime/session/checkpoint.py +108 -0
- nvs_runtime/session/manager.py +149 -0
- nvs_runtime/transport/__init__.py +3 -0
- nvs_runtime/transport/memory.py +36 -0
- nvs_runtime-1.0.0.dist-info/METADATA +234 -0
- nvs_runtime-1.0.0.dist-info/RECORD +94 -0
- nvs_runtime-1.0.0.dist-info/WHEEL +4 -0
- nvs_runtime-1.0.0.dist-info/entry_points.txt +2 -0
- nvs_runtime-1.0.0.dist-info/licenses/LICENSE +190 -0
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
"""``GateClient``: the formal Gate of nvs-runtime, which builds a ``GateVerdict``
|
|
2
|
+
(``gate-verdict/1``; design U6T-1 v0.1 3-7, DC-T1-1..4).
|
|
3
|
+
|
|
4
|
+
The rules are sensos's (by design, no cross-imports): nvs-runtime never
|
|
5
|
+
imports them. ``GateClient`` starts
|
|
6
|
+
``_gate_child.py`` in ``GATE_PY`` (an interpreter with ``jsonschema``) for each call and only
|
|
7
|
+
JSON crosses. What nvs-runtime adds is what the sensos checker does not say:
|
|
8
|
+
|
|
9
|
+
* the layers: L1 (the IC-00 envelope rule), then L2 (the payload), then L3 (the window space, only
|
|
10
|
+
for a ``msr.trajectory-window`` payload). A failed L1 leaves L2 and L3 ``not_run``;
|
|
11
|
+
* the ``result``: ``FAIL`` if any layer has a violation, else ``PASS_UNVERIFIED`` if anything is
|
|
12
|
+
unverifiable, else ``PASS``. ``WAIVED`` is not made (``waived`` is always empty);
|
|
13
|
+
* the check of every ``unverifiable`` row against sensos's catalogue (DC-7, DC-T1-4);
|
|
14
|
+
* the lookup of the parents (DC-T1-3): an envelope with parents is not sent to the Gate without
|
|
15
|
+
one;
|
|
16
|
+
* the checker bundle (``gate-checker-bundle/1``) and its hash, the environment of the child, and
|
|
17
|
+
``verdict_sha256``.
|
|
18
|
+
|
|
19
|
+
Not in a verdict: eligibility or admission to a chain (a verdict does not say it, by design)
|
|
20
|
+
and any time (DC-T1-2): the
|
|
21
|
+
same inputs give the same bytes. The bundle's bytes are given by ``checker_bundle``; keeping them
|
|
22
|
+
is U6T-2's.
|
|
23
|
+
|
|
24
|
+
This module imports the standard library and ``nvs_runtime.__version__`` only.
|
|
25
|
+
``examples/hidden_trajectory/sensos_door.py`` is a thin layer over ``GateProcess`` and
|
|
26
|
+
``GateClient``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import base64
|
|
32
|
+
import hashlib
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import subprocess
|
|
36
|
+
from collections.abc import Mapping
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from typing import Any, Final
|
|
40
|
+
|
|
41
|
+
from nvs_runtime.__version__ import __version__
|
|
42
|
+
|
|
43
|
+
#: The script that runs in ``GATE_PY``. Located, never imported (by design, no cross-imports).
|
|
44
|
+
CHILD_SCRIPT: Final = Path(__file__).with_name("_gate_child.py")
|
|
45
|
+
VERDICT_VERSION: Final = "gate-verdict/1"
|
|
46
|
+
BUNDLE_VERSION: Final = "gate-checker-bundle/1"
|
|
47
|
+
GATE_INTERNAL_ERROR: Final = "gate_internal_error"
|
|
48
|
+
PRODUCER_NAME: Final = "nvs-runtime"
|
|
49
|
+
REPO_NVS_RUNTIME: Final = "nvs-runtime"
|
|
50
|
+
|
|
51
|
+
LAYER_L1: Final = "L1"
|
|
52
|
+
LAYER_L2: Final = "L2"
|
|
53
|
+
LAYER_L3: Final = "L3"
|
|
54
|
+
NOT_RUN: Final = "not_run"
|
|
55
|
+
NOT_APPLICABLE: Final = "not_applicable"
|
|
56
|
+
|
|
57
|
+
#: A ``GateVerdict`` is a plain dictionary of the form ``gate-verdict/1``.
|
|
58
|
+
GateVerdict = dict[str, Any]
|
|
59
|
+
|
|
60
|
+
# The files of nvs-runtime that enter the checker bundle: their package paths.
|
|
61
|
+
_OWN_FILES: Final = (
|
|
62
|
+
"nvs_runtime/hidden_trajectory/_gate_child.py",
|
|
63
|
+
"nvs_runtime/hidden_trajectory/gate_client.py",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class GateError(Exception):
|
|
68
|
+
"""Base of what the Gate raises instead of making a verdict."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class GateUnavailable(GateError):
|
|
72
|
+
"""The child process failed or its output could not be read: no verdict (T-T1-13). Not a
|
|
73
|
+
judgment on the envelope."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class GateInternalError(GateUnavailable):
|
|
77
|
+
"""The Gate could not judge because the caller's input was wrong (a ``contract_facts`` of the
|
|
78
|
+
wrong shape): not a violation of the envelope."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, code: str, message: str) -> None:
|
|
81
|
+
super().__init__(f"{code}: {message}")
|
|
82
|
+
self.code = code
|
|
83
|
+
self.message = message
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class CatalogMismatch(GateError):
|
|
87
|
+
"""The checker returned an ``unverifiable`` row that sensos's catalogue does not have: the
|
|
88
|
+
checker and the catalogue are of different versions, and no verdict is made (DC-T1-4)."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class LookupMissing(GateError):
|
|
92
|
+
"""The envelope has parents (or a calibration) that the lookup does not name: raised before
|
|
93
|
+
the Gate is called (DC-T1-3), so that a mistake of the caller is not recorded as a failure of
|
|
94
|
+
the envelope."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, missing: tuple[str, ...]) -> None:
|
|
97
|
+
super().__init__(f"the lookup lacks: {', '.join(missing)}")
|
|
98
|
+
self.missing = missing
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ParentEnvelopeMissing(GateError):
|
|
102
|
+
"""The envelope has a parent, the caller gave no parent envelope, and did not say the parent is
|
|
103
|
+
absent (``ParentAbsent``): raised before the Gate is called, as ``LookupMissing`` is (DC-T1-3).
|
|
104
|
+
"Not fetched" is the caller's mistake, not a finding about the envelope."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, artifact_id: str) -> None:
|
|
107
|
+
super().__init__(f"the parent envelope of {artifact_id} was not given")
|
|
108
|
+
self.artifact_id = artifact_id
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ParentMismatch(GateError):
|
|
112
|
+
"""The parent envelope the caller gave is not the one ``ParentRef`` names: the data of the
|
|
113
|
+
caller disagree. ``fields`` are the names that differ (``artifact_id``, ``content_id``,
|
|
114
|
+
``seq``, ``observation_id``); ``differences`` has ``(expected, found)`` for each."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, differences: Mapping[str, tuple[Any, Any]]) -> None:
|
|
117
|
+
shown = "; ".join(f"{k}: expected {e!r}, found {f!r}" for k, (e, f) in differences.items())
|
|
118
|
+
super().__init__(f"the parent envelope does not match the parent: {shown}")
|
|
119
|
+
self.differences = dict(differences)
|
|
120
|
+
self.fields = tuple(differences)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True, slots=True)
|
|
124
|
+
class ParentAbsent:
|
|
125
|
+
"""The caller looked the parent up in ``source`` (the store it asked) and it is not there.
|
|
126
|
+
This is a fact the caller states; ``None`` instead means "not fetched" and is never read as
|
|
127
|
+
absence."""
|
|
128
|
+
|
|
129
|
+
artifact_id: str
|
|
130
|
+
source: str
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def required_lookup_ids(envelope: Mapping[str, Any]) -> tuple[str, ...]:
|
|
134
|
+
"""The ``artifact_id`` of every parent and of the calibration of ``envelope`` (the ones the
|
|
135
|
+
IC-00 rule reads from the lookup), once each, in the order of the code points."""
|
|
136
|
+
found: set[str] = set()
|
|
137
|
+
parents = envelope.get("parents")
|
|
138
|
+
if isinstance(parents, list):
|
|
139
|
+
for role in parents:
|
|
140
|
+
ids = role.get("artifact_ids") if isinstance(role, Mapping) else None
|
|
141
|
+
if isinstance(ids, list):
|
|
142
|
+
found.update(i for i in ids if isinstance(i, str))
|
|
143
|
+
calibration = envelope.get("calibration_ref")
|
|
144
|
+
if isinstance(calibration, Mapping) and isinstance(calibration.get("artifact_id"), str):
|
|
145
|
+
found.add(calibration["artifact_id"])
|
|
146
|
+
return tuple(sorted(found))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def missing_lookup(
|
|
150
|
+
envelope: Mapping[str, Any], lookup: Mapping[str, Any] | None
|
|
151
|
+
) -> tuple[str, ...]:
|
|
152
|
+
"""The ids of ``required_lookup_ids`` that ``lookup`` does not have."""
|
|
153
|
+
have = lookup or {}
|
|
154
|
+
return tuple(i for i in required_lookup_ids(envelope) if i not in have)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True)
|
|
158
|
+
class GateProcess:
|
|
159
|
+
"""One call of ``_gate_child.py`` in ``gate_py``, for ``sensos_tools`` (``SENSOS_TOOLS``)."""
|
|
160
|
+
|
|
161
|
+
gate_py: Path
|
|
162
|
+
sensos_tools: Path
|
|
163
|
+
|
|
164
|
+
@classmethod
|
|
165
|
+
def from_environment(cls) -> GateProcess:
|
|
166
|
+
missing = [name for name in ("GATE_PY", "SENSOS_TOOLS") if not os.environ.get(name)]
|
|
167
|
+
if missing:
|
|
168
|
+
raise RuntimeError(f"environment variables not set: {', '.join(missing)}")
|
|
169
|
+
return cls(Path(os.environ["GATE_PY"]), Path(os.environ["SENSOS_TOOLS"]))
|
|
170
|
+
|
|
171
|
+
def call(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
|
172
|
+
try:
|
|
173
|
+
done = subprocess.run(
|
|
174
|
+
[str(self.gate_py), str(CHILD_SCRIPT)],
|
|
175
|
+
input=json.dumps(request),
|
|
176
|
+
capture_output=True,
|
|
177
|
+
text=True,
|
|
178
|
+
env={"PYTHONDONTWRITEBYTECODE": "1", "SENSOS_TOOLS": str(self.sensos_tools)},
|
|
179
|
+
)
|
|
180
|
+
except OSError as error:
|
|
181
|
+
raise GateUnavailable(f"the child process could not be started: {error}") from error
|
|
182
|
+
if done.returncode == 2:
|
|
183
|
+
try:
|
|
184
|
+
answer = json.loads(done.stdout)
|
|
185
|
+
code, message = str(answer["error"]), str(answer["message"])
|
|
186
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
187
|
+
raise GateUnavailable("the child answered 2 with no readable error") from error
|
|
188
|
+
raise GateInternalError(code, message)
|
|
189
|
+
if done.returncode:
|
|
190
|
+
last = done.stderr.strip().splitlines()[-1:] or ["no output"]
|
|
191
|
+
raise GateUnavailable(f"the child exited {done.returncode}: {last[0]}")
|
|
192
|
+
try:
|
|
193
|
+
answer = json.loads(done.stdout)
|
|
194
|
+
except ValueError as error:
|
|
195
|
+
raise GateUnavailable("the child's output is not JSON") from error
|
|
196
|
+
if not isinstance(answer, dict):
|
|
197
|
+
raise GateUnavailable("the child's output is not a JSON object")
|
|
198
|
+
return answer
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def git_head(root: Path) -> str | None:
|
|
202
|
+
"""The commit of the repository whose top is ``root``, or ``None`` (not a checkout, no git)."""
|
|
203
|
+
try:
|
|
204
|
+
top = subprocess.run(
|
|
205
|
+
["git", "-C", str(root), "rev-parse", "--show-toplevel"],
|
|
206
|
+
capture_output=True,
|
|
207
|
+
text=True,
|
|
208
|
+
timeout=20,
|
|
209
|
+
)
|
|
210
|
+
if top.returncode or Path(top.stdout.strip()).resolve() != root.resolve():
|
|
211
|
+
return None
|
|
212
|
+
head = subprocess.run(
|
|
213
|
+
["git", "-C", str(root), "rev-parse", "HEAD"],
|
|
214
|
+
capture_output=True,
|
|
215
|
+
text=True,
|
|
216
|
+
timeout=20,
|
|
217
|
+
)
|
|
218
|
+
except (OSError, subprocess.SubprocessError):
|
|
219
|
+
return None
|
|
220
|
+
value = head.stdout.strip()
|
|
221
|
+
ok = head.returncode == 0 and len(value) == 40 and all(c in "0123456789abcdef" for c in value)
|
|
222
|
+
return value if ok else None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _matches_catalog(
|
|
226
|
+
rows: set[tuple[str, str, str]], schema_id: str, check: str, reason: str
|
|
227
|
+
) -> bool:
|
|
228
|
+
"""A row of the catalogue names ``(payload_schema, check, reason)``; a ``check`` that ends in
|
|
229
|
+
``.<field>`` stands for any field name after its prefix (``contract_binding.<field>``)."""
|
|
230
|
+
if (schema_id, check, reason) in rows:
|
|
231
|
+
return True
|
|
232
|
+
for row_schema, row_check, row_reason in rows:
|
|
233
|
+
if row_schema != schema_id or row_reason != reason or not row_check.endswith(".<field>"):
|
|
234
|
+
continue
|
|
235
|
+
prefix = row_check[: -len("<field>")]
|
|
236
|
+
if check.startswith(prefix) and len(check) > len(prefix):
|
|
237
|
+
return True
|
|
238
|
+
return False
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class GateClient:
|
|
242
|
+
"""``verdict(envelope, ...)`` -> ``GateVerdict``. One client builds its checker bundle once."""
|
|
243
|
+
|
|
244
|
+
def __init__(self, gate_py: Path, sensos_tools: Path) -> None:
|
|
245
|
+
self.process = GateProcess(Path(gate_py), Path(sensos_tools))
|
|
246
|
+
self._prepared: dict[str, Any] | None = None
|
|
247
|
+
|
|
248
|
+
@classmethod
|
|
249
|
+
def from_environment(cls) -> GateClient:
|
|
250
|
+
process = GateProcess.from_environment()
|
|
251
|
+
return cls(process.gate_py, process.sensos_tools)
|
|
252
|
+
|
|
253
|
+
# ---- the bundle and the catalogue: asked once --------------------------------------------
|
|
254
|
+
|
|
255
|
+
def _prepare(self) -> dict[str, Any]:
|
|
256
|
+
if self._prepared is None:
|
|
257
|
+
package_root = CHILD_SCRIPT.parents[2]
|
|
258
|
+
extra = [
|
|
259
|
+
{
|
|
260
|
+
"repo": REPO_NVS_RUNTIME,
|
|
261
|
+
"path": relative,
|
|
262
|
+
"b64": base64.b64encode((package_root / relative).read_bytes()).decode("ascii"),
|
|
263
|
+
}
|
|
264
|
+
for relative in _OWN_FILES
|
|
265
|
+
]
|
|
266
|
+
bundle = self.process.call({"op": "checker_files", "extra_files": extra})
|
|
267
|
+
catalog = self.process.call({"op": "catalog"})
|
|
268
|
+
sensos_commit = git_head(self.process.sensos_tools.resolve().parent)
|
|
269
|
+
runtime_commit = git_head(CHILD_SCRIPT.parents[3])
|
|
270
|
+
self._prepared = {
|
|
271
|
+
"bundle": base64.b64decode(bundle["bundle_b64"]),
|
|
272
|
+
"bundle_sha256": bundle["bundle_sha256"],
|
|
273
|
+
"files": bundle["files"],
|
|
274
|
+
"runtime": bundle["runtime"],
|
|
275
|
+
"rows": {tuple(row) for row in catalog["rows"]},
|
|
276
|
+
"catalog_sha256": catalog["sha256"],
|
|
277
|
+
"sensos_commit": sensos_commit,
|
|
278
|
+
"nvs_runtime_commit": runtime_commit,
|
|
279
|
+
}
|
|
280
|
+
return self._prepared
|
|
281
|
+
|
|
282
|
+
def checker_bundle(self) -> bytes:
|
|
283
|
+
"""The bytes of ``gate-checker-bundle/1`` (the JCS of ``{version, files}``), the same for
|
|
284
|
+
the life of this client. Its SHA-256 is ``bundle_sha256`` of every verdict."""
|
|
285
|
+
bundle = self._prepare()["bundle"]
|
|
286
|
+
assert isinstance(bundle, bytes)
|
|
287
|
+
return bundle
|
|
288
|
+
|
|
289
|
+
def bundle_sha256(self) -> str:
|
|
290
|
+
return str(self._prepare()["bundle_sha256"])
|
|
291
|
+
|
|
292
|
+
# ---- the verdict -------------------------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
def verdict(
|
|
295
|
+
self,
|
|
296
|
+
envelope: Mapping[str, Any],
|
|
297
|
+
*,
|
|
298
|
+
lookup: Mapping[str, Any] | None = None,
|
|
299
|
+
stored: Mapping[str, Any] | None = None,
|
|
300
|
+
blobs: Mapping[str, bytes] | None = None,
|
|
301
|
+
contract_facts: Mapping[str, Any] | None = None,
|
|
302
|
+
) -> GateVerdict:
|
|
303
|
+
"""The ``GateVerdict`` of ``envelope``.
|
|
304
|
+
|
|
305
|
+
``LookupMissing`` before anything is run if a parent is not in ``lookup``;
|
|
306
|
+
``GateUnavailable`` if the child fails or the envelope cannot be identified;
|
|
307
|
+
``CatalogMismatch`` for an ``unverifiable`` row the catalogue does not have. Nothing is
|
|
308
|
+
a verdict then.
|
|
309
|
+
"""
|
|
310
|
+
missing = missing_lookup(envelope, lookup)
|
|
311
|
+
if missing:
|
|
312
|
+
raise LookupMissing(missing)
|
|
313
|
+
subject, rules = self._identify(envelope)
|
|
314
|
+
prepared = self._prepare()
|
|
315
|
+
lookup_given = {k: dict(v) for k, v in (lookup or {}).items()}
|
|
316
|
+
blobs_given = dict(blobs or {})
|
|
317
|
+
answer = self.process.call(
|
|
318
|
+
{
|
|
319
|
+
"op": "gate",
|
|
320
|
+
"envelope": dict(envelope),
|
|
321
|
+
"lookup": lookup_given,
|
|
322
|
+
"stored": dict(stored or {}),
|
|
323
|
+
"blobs": {u: base64.b64encode(d).decode("ascii") for u, d in blobs_given.items()},
|
|
324
|
+
"contract_facts": None if contract_facts is None else dict(contract_facts),
|
|
325
|
+
}
|
|
326
|
+
)
|
|
327
|
+
layers, violations, unverifiable = _layers(answer)
|
|
328
|
+
schema_id = rules["payload_schema"]["id"]
|
|
329
|
+
for row in unverifiable:
|
|
330
|
+
if not _matches_catalog(prepared["rows"], schema_id, row["check"], row["reason"]):
|
|
331
|
+
raise CatalogMismatch(
|
|
332
|
+
f"({schema_id}, {row['check']}, {row['reason']}) is not in the UNVERIFIABLE "
|
|
333
|
+
"catalogue of sensos"
|
|
334
|
+
)
|
|
335
|
+
subject["envelope_sha256"] = answer["envelope_sha256"]
|
|
336
|
+
commit = prepared["sensos_commit"]
|
|
337
|
+
runtime_commit = prepared["nvs_runtime_commit"]
|
|
338
|
+
body: dict[str, Any] = {
|
|
339
|
+
"verdict_version": VERDICT_VERSION,
|
|
340
|
+
"subject": subject,
|
|
341
|
+
"result": _result(violations, unverifiable),
|
|
342
|
+
"layers": layers,
|
|
343
|
+
"codes": sorted({v["code"] for v in violations}),
|
|
344
|
+
"violations": violations,
|
|
345
|
+
"unverifiable": unverifiable,
|
|
346
|
+
"waived": [],
|
|
347
|
+
"rules": rules,
|
|
348
|
+
"inputs": {
|
|
349
|
+
"lookup": lookup_given,
|
|
350
|
+
"lookup_sha256": answer["lookup_sha256"],
|
|
351
|
+
"stored": sorted(stored or {}),
|
|
352
|
+
"blobs_checked": sorted(
|
|
353
|
+
{hashlib.sha256(d).hexdigest() for d in blobs_given.values()}
|
|
354
|
+
),
|
|
355
|
+
"contract_facts_sha256": answer["contract_facts_sha256"],
|
|
356
|
+
},
|
|
357
|
+
"gate": {
|
|
358
|
+
"checker": {
|
|
359
|
+
"bundle_sha256": prepared["bundle_sha256"],
|
|
360
|
+
"sensos_commit": commit,
|
|
361
|
+
"nvs_runtime_commit": runtime_commit,
|
|
362
|
+
"files": prepared["files"],
|
|
363
|
+
},
|
|
364
|
+
"runtime": prepared["runtime"],
|
|
365
|
+
"unverifiable_catalog": {
|
|
366
|
+
"version": commit or "unknown",
|
|
367
|
+
"sha256": prepared["catalog_sha256"],
|
|
368
|
+
},
|
|
369
|
+
},
|
|
370
|
+
"produced_by": {
|
|
371
|
+
"name": PRODUCER_NAME,
|
|
372
|
+
"version": __version__,
|
|
373
|
+
"build": runtime_commit or f"bundle:{prepared['bundle_sha256'][:16]}",
|
|
374
|
+
},
|
|
375
|
+
}
|
|
376
|
+
body["verdict_sha256"] = self.process.call({"op": "jcs_sha256", "value": body})["sha256"]
|
|
377
|
+
return body
|
|
378
|
+
|
|
379
|
+
@staticmethod
|
|
380
|
+
def _identify(envelope: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
381
|
+
"""``(subject, rules)`` from the envelope, or ``GateUnavailable`` if it cannot say what it
|
|
382
|
+
is (then no document of the form ``gate-verdict/1`` can be made about it)."""
|
|
383
|
+
try:
|
|
384
|
+
contract_version = envelope["contract"]["version"]
|
|
385
|
+
schema = envelope["payload_schema"]
|
|
386
|
+
subject = {
|
|
387
|
+
"artifact_id": envelope["artifact_id"],
|
|
388
|
+
"content_id": envelope["content_id"],
|
|
389
|
+
}
|
|
390
|
+
rules = {
|
|
391
|
+
"ic00_contract_version": contract_version,
|
|
392
|
+
"payload_schema": {"id": schema["id"], "version": schema["version"]},
|
|
393
|
+
}
|
|
394
|
+
except (KeyError, TypeError) as error:
|
|
395
|
+
raise GateUnavailable(
|
|
396
|
+
f"the envelope cannot be identified (missing {error}); no verdict is made"
|
|
397
|
+
) from error
|
|
398
|
+
texts = (
|
|
399
|
+
contract_version,
|
|
400
|
+
subject["artifact_id"],
|
|
401
|
+
subject["content_id"],
|
|
402
|
+
rules["payload_schema"]["id"],
|
|
403
|
+
rules["payload_schema"]["version"],
|
|
404
|
+
)
|
|
405
|
+
if not all(isinstance(t, str) and t for t in texts):
|
|
406
|
+
raise GateUnavailable("the envelope cannot be identified (not text); no verdict")
|
|
407
|
+
return subject, rules
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _layers(
|
|
411
|
+
answer: Mapping[str, Any],
|
|
412
|
+
) -> tuple[dict[str, Any], list[dict[str, str]], list[dict[str, str]]]:
|
|
413
|
+
"""``(layers, violations, unverifiable)`` from the child's ``gate`` answer."""
|
|
414
|
+
violations: list[dict[str, str]] = []
|
|
415
|
+
unverifiable: list[dict[str, str]] = []
|
|
416
|
+
|
|
417
|
+
def take(layer: str, found: list[Mapping[str, str]], unknown: list[Mapping[str, str]]) -> None:
|
|
418
|
+
violations.extend(
|
|
419
|
+
{"layer": layer, "code": v["code"], "message": v["message"]} for v in found
|
|
420
|
+
)
|
|
421
|
+
unverifiable.extend(
|
|
422
|
+
{"layer": layer, "check": u["check"], "reason": u["reason"]} for u in unknown
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
l1 = list(answer["l1"])
|
|
426
|
+
take(LAYER_L1, l1, [])
|
|
427
|
+
if l1:
|
|
428
|
+
layers = {
|
|
429
|
+
LAYER_L1: {"status": "FAIL", "codes": sorted({v["code"] for v in l1})},
|
|
430
|
+
LAYER_L2: {"status": NOT_RUN, "kind": None, "codes": []},
|
|
431
|
+
LAYER_L3: {"status": NOT_RUN, "codes": []},
|
|
432
|
+
}
|
|
433
|
+
return layers, violations, unverifiable
|
|
434
|
+
payload = answer["payload"]
|
|
435
|
+
take(LAYER_L2, payload["violations"], payload["unverifiable"])
|
|
436
|
+
window = answer.get("window")
|
|
437
|
+
if window is None:
|
|
438
|
+
l3: dict[str, Any] = {"status": NOT_APPLICABLE, "codes": []}
|
|
439
|
+
else:
|
|
440
|
+
take(LAYER_L3, window["violations"], window["unverifiable"])
|
|
441
|
+
l3 = {
|
|
442
|
+
"status": window["status"],
|
|
443
|
+
"codes": sorted({v["code"] for v in window["violations"]}),
|
|
444
|
+
}
|
|
445
|
+
layers = {
|
|
446
|
+
LAYER_L1: {"status": "PASS", "codes": []},
|
|
447
|
+
LAYER_L2: {
|
|
448
|
+
"status": payload["status"],
|
|
449
|
+
"kind": payload["kind"],
|
|
450
|
+
"codes": sorted({v["code"] for v in payload["violations"]}),
|
|
451
|
+
},
|
|
452
|
+
LAYER_L3: l3,
|
|
453
|
+
}
|
|
454
|
+
return layers, violations, unverifiable
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _result(violations: list[dict[str, str]], unverifiable: list[dict[str, str]]) -> str:
|
|
458
|
+
if violations:
|
|
459
|
+
return "FAIL"
|
|
460
|
+
return "PASS_UNVERIFIED" if unverifiable else "PASS"
|