aia-verify 0.1.1__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.
- aia/__init__.py +123 -0
- aia/attest/__init__.py +104 -0
- aia/attest/agent_identity.py +166 -0
- aia/attest/agent_policy.py +939 -0
- aia/attest/answer_pdf.py +492 -0
- aia/attest/bundle.py +248 -0
- aia/attest/canonical.py +175 -0
- aia/attest/comparison_verify.py +176 -0
- aia/attest/envelope.py +369 -0
- aia/attest/evidence.py +495 -0
- aia/attest/evidence_verify.py +437 -0
- aia/attest/governed_verify.py +432 -0
- aia/attest/keychain.py +548 -0
- aia/attest/merkle.py +181 -0
- aia/attest/messages/de.json +248 -0
- aia/attest/messages/en.json +248 -0
- aia/attest/record_proof.py +180 -0
- aia/attest/records.py +1132 -0
- aia/attest/render.py +1266 -0
- aia/attest/signing.py +1095 -0
- aia/attest/tee.py +560 -0
- aia/attest/tee_roots/README.md +78 -0
- aia/attest/tree.py +1008 -0
- aia/attest/usage.py +190 -0
- aia/attest/uuid7.py +36 -0
- aia/attest/verify.py +912 -0
- aia/contracts/__init__.py +325 -0
- aia/contracts/agent_step/__init__.py +117 -0
- aia/contracts/agent_step/v1/approval.schema.json +36 -0
- aia/contracts/agent_step/v1/common.schema.json +315 -0
- aia/contracts/agent_step/v1/dkg-read.schema.json +290 -0
- aia/contracts/agent_step/v1/policy-decision.schema.json +408 -0
- aia/contracts/agent_step/v1/record-tree.schema.json +55 -0
- aia/contracts/agent_step/v1/record.schema.json +496 -0
- aia/contracts/agent_step/v1/role.schema.json +300 -0
- aia/contracts/agent_step/v1/step.schema.json +582 -0
- aia/contracts/agent_step/v1/tool-call.schema.json +135 -0
- aia/i18n.py +69 -0
- aia/pqc/__init__.py +34 -0
- aia/pqc/keylen.py +174 -0
- aia/web/static/brand/email.json +266 -0
- aia/web/static/brand/fonts.css +171 -0
- aia/web/static/brand/tokens.json +1289 -0
- aia_verify-0.1.1.dist-info/METADATA +178 -0
- aia_verify-0.1.1.dist-info/RECORD +50 -0
- aia_verify-0.1.1.dist-info/WHEEL +5 -0
- aia_verify-0.1.1.dist-info/entry_points.txt +2 -0
- aia_verify-0.1.1.dist-info/licenses/LICENSE +201 -0
- aia_verify-0.1.1.dist-info/licenses/NOTICE +2 -0
- aia_verify-0.1.1.dist-info/top_level.txt +1 -0
aia/__init__.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""
|
|
3
|
+
AIA - Agentic Intelligence Architecture
|
|
4
|
+
========================================
|
|
5
|
+
|
|
6
|
+
A multi-agent system over a knowledge graph, in which every agent action is
|
|
7
|
+
signed into a record an auditor can verify.
|
|
8
|
+
|
|
9
|
+
Core Components:
|
|
10
|
+
- agents: the roster (``agents/roster.py``) and the runtime its agents share
|
|
11
|
+
- orchestration: the agents service, its task queue and the A2A protocol
|
|
12
|
+
- dkg: the knowledge graph (atoms, their edges and vectors, on PostgreSQL)
|
|
13
|
+
- attest: attestation records, their signing and disclosure bundles
|
|
14
|
+
- crypto: post-quantum cryptography (ML-KEM-1024, ML-DSA-87)
|
|
15
|
+
- llm: model providers, a model on this machine first
|
|
16
|
+
- mcp: Model Context Protocol server
|
|
17
|
+
- api: REST API
|
|
18
|
+
|
|
19
|
+
Version: 2.0.0
|
|
20
|
+
License: proprietary, all rights reserved (see LICENSE), except the offline verifier's
|
|
21
|
+
modules, this file among them (Apache-2.0), and ``blockchain/`` (AGPL-3.0-or-later).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import importlib.abc
|
|
25
|
+
import importlib.machinery
|
|
26
|
+
import logging
|
|
27
|
+
import sys
|
|
28
|
+
from typing import Any, Dict, Optional, Sequence
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _PyEccKeepsTheRecursionLimit(importlib.abc.MetaPathFinder):
|
|
34
|
+
"""Imports ``py_ecc`` without the recursion limit it sets for the whole process.
|
|
35
|
+
|
|
36
|
+
``py_ecc/__init__.py`` runs ``sys.setrecursionlimit(max(100000, ...))``, and every
|
|
37
|
+
process that imports ``eth_account`` (``aia.blockchain``, so ``aia.agents`` and the
|
|
38
|
+
API) imports it. On Python 3.11, which the images run, the C JSON parser counts its
|
|
39
|
+
nesting against that limit, so a request body nested 100,000 deep ran the parser past
|
|
40
|
+
the end of the thread's stack and the worker died of SIGSEGV instead of refusing the
|
|
41
|
+
body as ``max_depth``. Nothing here needs the raised limit: secp256k1 accounts, keyfiles
|
|
42
|
+
and py_ecc's own BLS signatures all work under the default. The limit is put back to
|
|
43
|
+
what it was once py_ecc's ``__init__`` has run; its submodules load lazily after that.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def find_spec(
|
|
47
|
+
self, fullname: str, path: Optional[Sequence[str]], target: Any = None
|
|
48
|
+
) -> Optional[importlib.machinery.ModuleSpec]:
|
|
49
|
+
if fullname != "py_ecc":
|
|
50
|
+
return None
|
|
51
|
+
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
|
|
52
|
+
if spec is None or spec.loader is None:
|
|
53
|
+
return spec
|
|
54
|
+
exec_module = spec.loader.exec_module
|
|
55
|
+
|
|
56
|
+
def exec_keeping_the_limit(module: Any) -> None:
|
|
57
|
+
limit = sys.getrecursionlimit()
|
|
58
|
+
try:
|
|
59
|
+
exec_module(module)
|
|
60
|
+
finally:
|
|
61
|
+
sys.setrecursionlimit(limit)
|
|
62
|
+
|
|
63
|
+
spec.loader.exec_module = exec_keeping_the_limit # type: ignore[method-assign]
|
|
64
|
+
return spec
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if not any(isinstance(f, _PyEccKeepsTheRecursionLimit) for f in sys.meta_path):
|
|
68
|
+
sys.meta_path.insert(0, _PyEccKeepsTheRecursionLimit())
|
|
69
|
+
|
|
70
|
+
__version__ = "2.0.0"
|
|
71
|
+
__author__ = "013a"
|
|
72
|
+
|
|
73
|
+
# Configuration (present in the full install; absent from the connector wheel)
|
|
74
|
+
try:
|
|
75
|
+
from aia.config.settings import Settings, settings
|
|
76
|
+
|
|
77
|
+
CONFIG_AVAILABLE = True
|
|
78
|
+
except ImportError as e:
|
|
79
|
+
# Two different situations, and only one of them is a problem. The connector
|
|
80
|
+
# distribution (OP#646) ships `aia.cli` and `aia.engine` without `aia.config` on
|
|
81
|
+
# purpose, so the module is simply not there -- and a WARNING from a library with
|
|
82
|
+
# no logging configured goes to stderr through Python's last-resort handler,
|
|
83
|
+
# which means `aia version` would print a scary line about missing config every
|
|
84
|
+
# time it ran. A module that IS installed and fails to import is a real fault and
|
|
85
|
+
# still says so.
|
|
86
|
+
if isinstance(e, ModuleNotFoundError) and (e.name or "").startswith("aia.config"):
|
|
87
|
+
logger.debug("aia.config is not part of this distribution")
|
|
88
|
+
else:
|
|
89
|
+
logger.warning(f"Config not available: {e}")
|
|
90
|
+
settings = None
|
|
91
|
+
Settings = None
|
|
92
|
+
CONFIG_AVAILABLE = False
|
|
93
|
+
|
|
94
|
+
# Sub-modules should be imported explicitly to avoid circular dependencies
|
|
95
|
+
# and massive initialization overhead.
|
|
96
|
+
# from aia import agents
|
|
97
|
+
# from aia import orchestration
|
|
98
|
+
# from aia import dkg
|
|
99
|
+
# from aia import crypto
|
|
100
|
+
# from aia import llm
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_aia_status() -> Dict[str, Any]:
|
|
104
|
+
"""Get comprehensive AIA system status"""
|
|
105
|
+
return {
|
|
106
|
+
"version": __version__,
|
|
107
|
+
"author": __author__,
|
|
108
|
+
"modules": {
|
|
109
|
+
"config": CONFIG_AVAILABLE,
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
__all__ = [
|
|
115
|
+
# Version info
|
|
116
|
+
"__version__",
|
|
117
|
+
"__author__",
|
|
118
|
+
# Status function
|
|
119
|
+
"get_aia_status",
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
if CONFIG_AVAILABLE:
|
|
123
|
+
__all__.extend(["settings", "Settings"])
|
aia/attest/__init__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""AIA attestation core (class-A action attestation).
|
|
3
|
+
|
|
4
|
+
This package is the stable contract of AIA's AI-audit layer: every agent
|
|
5
|
+
action becomes a signed, hash-chained, Merkle-batched, optionally anchored
|
|
6
|
+
attestation record that an auditor can verify independently.
|
|
7
|
+
|
|
8
|
+
Design constraints (binding — see ``README.md`` in this directory):
|
|
9
|
+
|
|
10
|
+
- **Dependency-light by contract.** Modules in this package import only the
|
|
11
|
+
standard library, ``pydantic`` (schema), ``rfc8785`` (JCS), ``oqs``
|
|
12
|
+
(ML-DSA-87), ``cryptography`` (Ed25519), and ``pypdf`` (pure Python; an answer
|
|
13
|
+
exported as a PDF, read only where one is given, ``823-answer-records`` D-13).
|
|
14
|
+
The standalone verifier must
|
|
15
|
+
run on an auditor's laptop without the AIA stack — never import FastAPI,
|
|
16
|
+
Redis or Postgres drivers, or ``aia.*`` application modules here.
|
|
17
|
+
- **SHA3-256 everywhere in the class-A evidence layer** (BSI TR-02102-listed;
|
|
18
|
+
Blake3 stays internal to the SP1 rollup circuits).
|
|
19
|
+
- **Signatures are hybrid**: ML-DSA-87 (FIPS 204) primary + Ed25519 classical.
|
|
20
|
+
Verifiers REQUIRE a valid ML-DSA-87 signature and check Ed25519 when present.
|
|
21
|
+
|
|
22
|
+
Each name below is imported on first use (PEP 562), not when the package is. Importing
|
|
23
|
+
any submodule runs this file first, so an eager import here made every reader of a light
|
|
24
|
+
part (``aia.attest.evidence``'s content ids, which the knowledge store computes) load
|
|
25
|
+
liboqs through ``bundle`` and ``keychain``, whose import prints a banner to stdout.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
from importlib import import_module
|
|
30
|
+
from typing import TYPE_CHECKING, Any, Dict
|
|
31
|
+
|
|
32
|
+
# liboqs-python logs one notice when it is imported, through a handler of its own on
|
|
33
|
+
# stdout: "liboqs-python faulthandler is disabled". On the auditor's command line it
|
|
34
|
+
# landed in the verification report, above the record, and it says nothing about the
|
|
35
|
+
# bundle. Dropped here, before any module of this package imports `oqs`; every other
|
|
36
|
+
# message of that logger (its build of a missing liboqs, for one) still shows.
|
|
37
|
+
logging.getLogger("oqs.oqs").addFilter(lambda entry: "faulthandler" not in entry.getMessage())
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from aia.attest.bundle import BUNDLE_VERSION, DisclosureBundle
|
|
41
|
+
from aia.attest.canonical import (
|
|
42
|
+
canonical_bytes,
|
|
43
|
+
hash_bytes,
|
|
44
|
+
hash_json_value,
|
|
45
|
+
idempotency_key,
|
|
46
|
+
record_hash,
|
|
47
|
+
)
|
|
48
|
+
from aia.attest.merkle import InclusionProof, MerkleTree, verify_inclusion
|
|
49
|
+
from aia.attest.records import (
|
|
50
|
+
ActionType,
|
|
51
|
+
AttestationRecord,
|
|
52
|
+
ModelAttestationKind,
|
|
53
|
+
ModelInfo,
|
|
54
|
+
OTelContext,
|
|
55
|
+
)
|
|
56
|
+
from aia.attest.signing import (
|
|
57
|
+
AttestationKeyStore,
|
|
58
|
+
AttestationSigner,
|
|
59
|
+
SignatureEntry,
|
|
60
|
+
SignedAttestation,
|
|
61
|
+
verify_signed_attestation,
|
|
62
|
+
)
|
|
63
|
+
from aia.attest.uuid7 import uuid7
|
|
64
|
+
|
|
65
|
+
#: Each name the package offers, and the module it lives in.
|
|
66
|
+
_LAZY: Dict[str, str] = {
|
|
67
|
+
"BUNDLE_VERSION": ".bundle",
|
|
68
|
+
"DisclosureBundle": ".bundle",
|
|
69
|
+
"canonical_bytes": ".canonical",
|
|
70
|
+
"hash_bytes": ".canonical",
|
|
71
|
+
"hash_json_value": ".canonical",
|
|
72
|
+
"idempotency_key": ".canonical",
|
|
73
|
+
"record_hash": ".canonical",
|
|
74
|
+
"InclusionProof": ".merkle",
|
|
75
|
+
"MerkleTree": ".merkle",
|
|
76
|
+
"verify_inclusion": ".merkle",
|
|
77
|
+
"ActionType": ".records",
|
|
78
|
+
"AttestationRecord": ".records",
|
|
79
|
+
"ModelAttestationKind": ".records",
|
|
80
|
+
"ModelInfo": ".records",
|
|
81
|
+
"OTelContext": ".records",
|
|
82
|
+
"AttestationKeyStore": ".signing",
|
|
83
|
+
"AttestationSigner": ".signing",
|
|
84
|
+
"SignatureEntry": ".signing",
|
|
85
|
+
"SignedAttestation": ".signing",
|
|
86
|
+
"verify_signed_attestation": ".signing",
|
|
87
|
+
"uuid7": ".uuid7",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
__all__ = sorted(_LAZY)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def __getattr__(name: str) -> Any:
|
|
94
|
+
try:
|
|
95
|
+
module = _LAZY[name]
|
|
96
|
+
except KeyError:
|
|
97
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
|
|
98
|
+
value = getattr(import_module(module, __name__), name)
|
|
99
|
+
globals()[name] = value
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def __dir__() -> list:
|
|
104
|
+
return sorted(set(globals()) | set(_LAZY))
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Agent identity per step: the agent's DID under the tenant's key (OP#885 task 885.8, 819-agent-governance D-10).
|
|
3
|
+
|
|
4
|
+
* **The DID** of a role in a tenant is ``did:aia:agent:<tenant>:<role_id>``, for example
|
|
5
|
+
``did:aia:agent:acme:business.research``. It stays the same across the role's versions;
|
|
6
|
+
the version is the step's ``role@version``. A character of the tenant outside the DID
|
|
7
|
+
syntax's set (C0's ``agent_did`` pattern) is percent-encoded.
|
|
8
|
+
* **Its controller** is ``did:aia:tenant:<tenant>``, whose key is the tenant's root key.
|
|
9
|
+
* **It resolves through the tenant's chain:** each version of the role is registered by a
|
|
10
|
+
``role_lifecycle`` record (C0 D-17) whose body is the role document and whose
|
|
11
|
+
``output_hash`` is the document's digest, the ``role_digest`` a step names. The DID
|
|
12
|
+
document lists, for each version, its record, its digest and the window in which it was
|
|
13
|
+
the role's current version: from its record's time until the next version's.
|
|
14
|
+
|
|
15
|
+
Pure, like the rest of :mod:`aia.attest`: the verifier resolves a disclosed step's DID with
|
|
16
|
+
it, from the ``role_lifecycle`` records the export carries.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from typing import Any, Iterable, Mapping, Optional
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"ORCHESTRATOR",
|
|
27
|
+
"agent_did",
|
|
28
|
+
"did_document",
|
|
29
|
+
"parse_agent_did",
|
|
30
|
+
"record_agent_id",
|
|
31
|
+
"tenant_did",
|
|
32
|
+
"version_at",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
#: The record ``agent_id`` of a run, a plan step and their decisions, which have no role (C0 D-15).
|
|
36
|
+
ORCHESTRATOR = "agent-orchestrator"
|
|
37
|
+
|
|
38
|
+
_AGENT_PREFIX = "did:aia:agent:"
|
|
39
|
+
_TENANT_PREFIX = "did:aia:tenant:"
|
|
40
|
+
_ROLE_ID = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+\Z")
|
|
41
|
+
_SAFE = re.compile(r"[A-Za-z0-9._-]")
|
|
42
|
+
_ENCODED_TENANT = re.compile(r"^[A-Za-z0-9._%-]{1,128}\Z")
|
|
43
|
+
_INSTANCE_SUFFIX = re.compile(r"\.[0-9]+\Z")
|
|
44
|
+
_TS = re.compile(r"^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(?:\.([0-9]{1,9}))?Z\Z")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _moment(ts: str) -> datetime:
|
|
48
|
+
"""A record's ``ts`` (RFC 3339, UTC, ``Z``, 0 to 9 fraction digits) as a datetime.
|
|
49
|
+
|
|
50
|
+
Compared as datetimes, never as strings: ``.000Z`` and ``.000000Z`` name one instant.
|
|
51
|
+
"""
|
|
52
|
+
match = _TS.match(ts)
|
|
53
|
+
if match is None:
|
|
54
|
+
raise ValueError(f"{ts!r} is not a record time")
|
|
55
|
+
fraction = (match.group(2) or "").ljust(6, "0")[:6]
|
|
56
|
+
return datetime.strptime(f"{match.group(1)}.{fraction}", "%Y-%m-%dT%H:%M:%S.%f").replace(
|
|
57
|
+
tzinfo=timezone.utc
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _encode(tenant: str) -> str:
|
|
62
|
+
if not tenant:
|
|
63
|
+
raise ValueError("an agent's DID names its tenant")
|
|
64
|
+
encoded = "".join(
|
|
65
|
+
char if _SAFE.match(char) else "".join(f"%{byte:02X}" for byte in char.encode("utf-8"))
|
|
66
|
+
for char in tenant
|
|
67
|
+
)
|
|
68
|
+
if not _ENCODED_TENANT.match(encoded):
|
|
69
|
+
raise ValueError(f"the tenant {tenant!r} is longer than a DID can carry")
|
|
70
|
+
return encoded
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _percent_decode(encoded: str) -> str:
|
|
74
|
+
out = bytearray()
|
|
75
|
+
index = 0
|
|
76
|
+
while index < len(encoded):
|
|
77
|
+
char = encoded[index]
|
|
78
|
+
if char == "%":
|
|
79
|
+
out.append(int(encoded[index + 1 : index + 3], 16))
|
|
80
|
+
index += 3
|
|
81
|
+
else:
|
|
82
|
+
out.extend(char.encode("ascii"))
|
|
83
|
+
index += 1
|
|
84
|
+
return out.decode("utf-8")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def agent_did(tenant: str, role_id: str) -> str:
|
|
88
|
+
"""``did:aia:agent:<tenant>:<role_id>``; a role id with an instance suffix is refused."""
|
|
89
|
+
if not _ROLE_ID.match(role_id) or _INSTANCE_SUFFIX.search(role_id):
|
|
90
|
+
raise ValueError(f"{role_id!r} is not a role id (domain.name, no instance suffix)")
|
|
91
|
+
return f"{_AGENT_PREFIX}{_encode(tenant)}:{role_id}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def tenant_did(tenant: str) -> str:
|
|
95
|
+
"""The controller of every agent DID of ``tenant``: ``did:aia:tenant:<tenant>``."""
|
|
96
|
+
return f"{_TENANT_PREFIX}{_encode(tenant)}"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def parse_agent_did(did: str) -> tuple[str, str]:
|
|
100
|
+
"""``(tenant, role_id)`` of an agent DID, or ``ValueError``."""
|
|
101
|
+
if not did.startswith(_AGENT_PREFIX):
|
|
102
|
+
raise ValueError(f"{did!r} is not an agent DID")
|
|
103
|
+
encoded, separator, role_id = did[len(_AGENT_PREFIX) :].partition(":")
|
|
104
|
+
if not separator or not _ENCODED_TENANT.match(encoded) or not _ROLE_ID.match(role_id):
|
|
105
|
+
raise ValueError(f"{did!r} is not an agent DID")
|
|
106
|
+
return _percent_decode(encoded), role_id
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def record_agent_id(role_id: Optional[str]) -> str:
|
|
110
|
+
"""The ``agent_id`` a step's records carry: the role id without the instance, or
|
|
111
|
+
:data:`ORCHESTRATOR` for a run or a plan step, which has no role (C0 D-15)."""
|
|
112
|
+
if role_id is None:
|
|
113
|
+
return ORCHESTRATOR
|
|
114
|
+
base = _INSTANCE_SUFFIX.sub("", role_id)
|
|
115
|
+
if not _ROLE_ID.match(base):
|
|
116
|
+
raise ValueError(f"{role_id!r} is not a role id")
|
|
117
|
+
return base
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def did_document(tenant: str, role_id: str, records: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
|
|
121
|
+
"""The DID document of ``role_id`` in ``tenant``, built from the tenant's ``role_lifecycle`` records.
|
|
122
|
+
|
|
123
|
+
``records`` are records in their JSON form (``record_id``, ``tenant_id``,
|
|
124
|
+
``action_type``, ``ts``, ``output_hash`` and the ``body`` that is the role document);
|
|
125
|
+
records of another tenant, another action or another role are ignored. Each version is
|
|
126
|
+
valid from its record's ``ts`` until the next version's.
|
|
127
|
+
"""
|
|
128
|
+
registered = sorted(
|
|
129
|
+
(
|
|
130
|
+
record
|
|
131
|
+
for record in records
|
|
132
|
+
if record.get("tenant_id") == tenant
|
|
133
|
+
and record.get("action_type") == "role_lifecycle"
|
|
134
|
+
and isinstance(record.get("body"), Mapping)
|
|
135
|
+
and record["body"].get("id") == role_id
|
|
136
|
+
),
|
|
137
|
+
key=lambda record: (_moment(str(record["ts"])), str(record["record_id"])),
|
|
138
|
+
)
|
|
139
|
+
versions = []
|
|
140
|
+
for index, record in enumerate(registered):
|
|
141
|
+
following = registered[index + 1] if index + 1 < len(registered) else None
|
|
142
|
+
versions.append(
|
|
143
|
+
{
|
|
144
|
+
"version": record["body"]["version"],
|
|
145
|
+
"record_id": record["record_id"],
|
|
146
|
+
"role_digest": record["output_hash"],
|
|
147
|
+
"valid_from": record["ts"],
|
|
148
|
+
"valid_until": following["ts"] if following is not None else None,
|
|
149
|
+
}
|
|
150
|
+
)
|
|
151
|
+
return {
|
|
152
|
+
"id": agent_did(tenant, role_id),
|
|
153
|
+
"controller": tenant_did(tenant),
|
|
154
|
+
"versions": versions,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def version_at(document: Mapping[str, Any], ts: str) -> Optional[Mapping[str, Any]]:
|
|
159
|
+
"""The version of a DID document in force at ``ts`` (an RFC 3339 record time), if any."""
|
|
160
|
+
moment = _moment(ts)
|
|
161
|
+
for version in document["versions"]:
|
|
162
|
+
until = version["valid_until"]
|
|
163
|
+
if _moment(version["valid_from"]) <= moment and (until is None or moment < _moment(until)):
|
|
164
|
+
found: Mapping[str, Any] = version
|
|
165
|
+
return found
|
|
166
|
+
return None
|