mandatia 0.1.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.
- amr/__init__.py +1 -0
- amr/attestation.py +369 -0
- amr/config.py +60 -0
- amr/crypto/__init__.py +1 -0
- amr/crypto/chain.py +59 -0
- amr/crypto/principal.py +161 -0
- amr/crypto/signing.py +80 -0
- amr/db/__init__.py +1 -0
- amr/db/engine.py +548 -0
- amr/delegation.py +74 -0
- amr/did_web.py +379 -0
- amr/models/__init__.py +4 -0
- amr/models/attestation.py +17 -0
- amr/models/dossier.py +51 -0
- amr/models/mandate.py +81 -0
- amr/models/organ_decision.py +147 -0
- amr/models/perimeter.py +438 -0
- amr/models/token.py +57 -0
- amr/proof/__init__.py +1 -0
- amr/proof/insurer_dossier.py +321 -0
- amr/public_registry.py +656 -0
- amr/server.py +57 -0
- amr/templates/__init__.py +51 -0
- amr/templates/agent_sante_rgpd.py +112 -0
- amr/templates/base.py +205 -0
- amr/tools/__init__.py +1 -0
- amr/tools/check_action_token.py +228 -0
- amr/tools/contest_action.py +698 -0
- amr/tools/create_mandate.py +567 -0
- amr/tools/export_insurer_dossier.py +312 -0
- amr/tools/get_proof.py +529 -0
- amr/tools/issue_action_token.py +389 -0
- amr/tools/issue_mandate_attestation.py +323 -0
- amr/tools/log_action.py +162 -0
- amr/tools/principal_keys.py +323 -0
- amr/tools/report_issue.py +220 -0
- amr/tools/revoke_mandate.py +422 -0
- amr/tools/verify_mandate.py +117 -0
- amr/verify_attestation.py +73 -0
- mandatia-0.1.0.dist-info/METADATA +1006 -0
- mandatia-0.1.0.dist-info/RECORD +44 -0
- mandatia-0.1.0.dist-info/WHEEL +4 -0
- mandatia-0.1.0.dist-info/entry_points.txt +3 -0
- mandatia-0.1.0.dist-info/licenses/LICENSE +194 -0
amr/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# AMR - Agent Mandate Registry
|
amr/attestation.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Mandate attestations: a signed statement a third party checks offline.
|
|
2
|
+
|
|
3
|
+
An agent asks the registry for an attestation of its mandate (tool
|
|
4
|
+
``issue_mandate_attestation``) and shows it to whoever receives it: a seller, a
|
|
5
|
+
hospital, an insurer. The receiver checks it alone, with the registry's public key
|
|
6
|
+
obtained once (tool ``get_registry_public_key``), without an account and without
|
|
7
|
+
calling the registry: the mandate exists, who granted it, what it allows, until when,
|
|
8
|
+
and that it was active, along its whole delegation chain, when the attestation was
|
|
9
|
+
issued.
|
|
10
|
+
|
|
11
|
+
This module is the receiver's side. It reads no database and makes no network call.
|
|
12
|
+
See docs/mandate-attestation-spec.md.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
from datetime import UTC, datetime, timedelta
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import jwt
|
|
21
|
+
from cryptography.hazmat.primitives import serialization
|
|
22
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
23
|
+
|
|
24
|
+
from amr.crypto.principal import (
|
|
25
|
+
MANDATE_CONTEXT,
|
|
26
|
+
PrincipalSignatureError,
|
|
27
|
+
key_id,
|
|
28
|
+
key_registration_payload,
|
|
29
|
+
parse_public_key,
|
|
30
|
+
parse_signature,
|
|
31
|
+
verify,
|
|
32
|
+
)
|
|
33
|
+
from amr.delegation import MAX_DELEGATION_DEPTH
|
|
34
|
+
from amr.models.perimeter import Perimeter
|
|
35
|
+
|
|
36
|
+
ATTESTATION_TYP = "amr-attestation+jwt"
|
|
37
|
+
ATTESTATION_VERSION = "mandate.v1"
|
|
38
|
+
# EdDSA is the only algorithm accepted, in issuance and in verification.
|
|
39
|
+
ALGORITHM = "EdDSA"
|
|
40
|
+
|
|
41
|
+
_MANDATE_KEYS = (
|
|
42
|
+
"id",
|
|
43
|
+
"principal_id",
|
|
44
|
+
"agent_id",
|
|
45
|
+
"scope",
|
|
46
|
+
"legal_basis",
|
|
47
|
+
"status",
|
|
48
|
+
"created_at",
|
|
49
|
+
"expires_at",
|
|
50
|
+
"parent_mandate_id",
|
|
51
|
+
"perimeter",
|
|
52
|
+
"perimeter_digest",
|
|
53
|
+
"chain_hash",
|
|
54
|
+
"principal_signature",
|
|
55
|
+
)
|
|
56
|
+
_LINK_KEYS = (
|
|
57
|
+
"id",
|
|
58
|
+
"principal_id",
|
|
59
|
+
"agent_id",
|
|
60
|
+
"status",
|
|
61
|
+
"expires_at",
|
|
62
|
+
"parent_mandate_id",
|
|
63
|
+
"perimeter_digest",
|
|
64
|
+
)
|
|
65
|
+
_SIGNATURE_KEYS = ("key_id", "public_key", "signed_at")
|
|
66
|
+
_SIGNED_PAYLOAD_KEYS = ("signature", "payload")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class AttestationError(Exception):
|
|
70
|
+
"""An attestation failed a check. ``code`` is stable and machine-readable."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, code: str, detail: str) -> None:
|
|
73
|
+
super().__init__(f"{code}: {detail}")
|
|
74
|
+
self.code = code
|
|
75
|
+
self.detail = detail
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def registry_key_id(public_key: ed25519.Ed25519PublicKey) -> str:
|
|
79
|
+
"""Key identifier of the registry key: first 16 hex chars of SHA-256 of its raw bytes."""
|
|
80
|
+
raw = public_key.public_bytes(
|
|
81
|
+
encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw
|
|
82
|
+
)
|
|
83
|
+
return hashlib.sha256(raw).hexdigest()[:16]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def claims_digest(claims: dict[str, Any]) -> str:
|
|
87
|
+
"""SHA-256 of the canonical JSON of the claims (kept in the issuance audit)."""
|
|
88
|
+
canonical = json.dumps(claims, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
89
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _timestamp(moment: str) -> float:
|
|
93
|
+
parsed = datetime.fromisoformat(moment)
|
|
94
|
+
if parsed.tzinfo is None:
|
|
95
|
+
parsed = parsed.replace(tzinfo=UTC)
|
|
96
|
+
return parsed.timestamp()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _iso(timestamp: int) -> str:
|
|
100
|
+
return datetime.fromtimestamp(timestamp, UTC).isoformat()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _require_keys(obj: Any, keys: tuple[str, ...], what: str) -> dict[str, Any]:
|
|
104
|
+
if not isinstance(obj, dict):
|
|
105
|
+
raise AttestationError("claims_invalid", f"{what} must be an object")
|
|
106
|
+
missing = [key for key in keys if key not in obj]
|
|
107
|
+
if missing:
|
|
108
|
+
raise AttestationError("claims_invalid", f"{what} lacks {', '.join(missing)}")
|
|
109
|
+
return obj
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _perimeter_digest(perimeter: Any) -> str | None:
|
|
113
|
+
if perimeter is None:
|
|
114
|
+
return None
|
|
115
|
+
try:
|
|
116
|
+
return Perimeter.model_validate(perimeter).digest()
|
|
117
|
+
except ValueError as exc:
|
|
118
|
+
raise AttestationError("claims_invalid", "perimeter is not a valid perimeter") from exc
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _check_principal_signature(mandate: dict[str, Any]) -> bool:
|
|
122
|
+
"""Check the principal signature block; return True if it was re-checked here.
|
|
123
|
+
|
|
124
|
+
The key must always match its key id. When the attestation carries the signed
|
|
125
|
+
payload (issued with include_principal_payload), the receiver re-checks, without
|
|
126
|
+
trusting the registry: the Ed25519 signature over the payload, the key's proof of
|
|
127
|
+
possession when present, and that the payload names this principal, agent, scope,
|
|
128
|
+
legal basis, parent, signed_at and duration (and, for a root mandate, this exact
|
|
129
|
+
perimeter). Without the payload, the signature is vouched for by the registry only.
|
|
130
|
+
"""
|
|
131
|
+
block = _require_keys(mandate["principal_signature"], _SIGNATURE_KEYS, "principal_signature")
|
|
132
|
+
try:
|
|
133
|
+
public_key_raw = parse_public_key(block["public_key"])
|
|
134
|
+
except PrincipalSignatureError as exc:
|
|
135
|
+
raise AttestationError("principal_signature_invalid", exc.code) from exc
|
|
136
|
+
if key_id(public_key_raw) != block["key_id"]:
|
|
137
|
+
raise AttestationError("principal_signature_invalid", "key_id does not match key")
|
|
138
|
+
if not any(key in block for key in _SIGNED_PAYLOAD_KEYS):
|
|
139
|
+
return False
|
|
140
|
+
_require_keys(block, _SIGNED_PAYLOAD_KEYS, "principal_signature")
|
|
141
|
+
try:
|
|
142
|
+
signature_raw = parse_signature(block["signature"])
|
|
143
|
+
except PrincipalSignatureError as exc:
|
|
144
|
+
raise AttestationError("principal_signature_invalid", exc.code) from exc
|
|
145
|
+
payload_text = block["payload"]
|
|
146
|
+
if not isinstance(payload_text, str) or not verify(
|
|
147
|
+
public_key_raw, payload_text.encode("utf-8"), signature_raw
|
|
148
|
+
):
|
|
149
|
+
raise AttestationError("principal_signature_invalid", "signature does not verify")
|
|
150
|
+
proof = block.get("key_proof_signature")
|
|
151
|
+
if proof is not None:
|
|
152
|
+
try:
|
|
153
|
+
proof_raw = parse_signature(proof)
|
|
154
|
+
except PrincipalSignatureError as exc:
|
|
155
|
+
raise AttestationError("principal_signature_invalid", exc.code) from exc
|
|
156
|
+
registration = key_registration_payload(mandate["principal_id"], block["public_key"])
|
|
157
|
+
if not verify(public_key_raw, registration, proof_raw):
|
|
158
|
+
raise AttestationError("principal_signature_invalid", "key proof does not verify")
|
|
159
|
+
try:
|
|
160
|
+
payload = json.loads(payload_text)
|
|
161
|
+
except ValueError as exc:
|
|
162
|
+
raise AttestationError("principal_signature_invalid", "payload is not JSON") from exc
|
|
163
|
+
if not isinstance(payload, dict):
|
|
164
|
+
raise AttestationError("principal_signature_invalid", "payload is not an object")
|
|
165
|
+
expected = {
|
|
166
|
+
"context": MANDATE_CONTEXT,
|
|
167
|
+
"principal_id": mandate["principal_id"],
|
|
168
|
+
"agent_id": mandate["agent_id"],
|
|
169
|
+
"scope": mandate["scope"],
|
|
170
|
+
"legal_basis": mandate["legal_basis"],
|
|
171
|
+
"parent_mandate_id": mandate["parent_mandate_id"],
|
|
172
|
+
"signed_at": block["signed_at"],
|
|
173
|
+
}
|
|
174
|
+
if mandate["parent_mandate_id"] is None:
|
|
175
|
+
expected["perimeter"] = mandate["perimeter"]
|
|
176
|
+
for field, value in expected.items():
|
|
177
|
+
if payload.get(field) != value:
|
|
178
|
+
raise AttestationError(
|
|
179
|
+
"principal_signature_invalid", f"signed {field} differs from the mandate"
|
|
180
|
+
)
|
|
181
|
+
duration = payload.get("duration_hours")
|
|
182
|
+
if isinstance(duration, bool) or not isinstance(duration, int | float):
|
|
183
|
+
raise AttestationError("principal_signature_invalid", "signed duration missing")
|
|
184
|
+
try:
|
|
185
|
+
granted = _timestamp(mandate["expires_at"]) - _timestamp(mandate["created_at"])
|
|
186
|
+
except (TypeError, ValueError) as exc:
|
|
187
|
+
raise AttestationError("claims_invalid", "created_at is not ISO 8601") from exc
|
|
188
|
+
if abs(granted - timedelta(hours=duration).total_seconds()) > 1:
|
|
189
|
+
raise AttestationError(
|
|
190
|
+
"principal_signature_invalid", "signed duration differs from the mandate"
|
|
191
|
+
)
|
|
192
|
+
return True
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def check_claims(claims: dict[str, Any], now: float, leeway: int = 0) -> dict[str, Any]:
|
|
196
|
+
"""Check the content of verified claims; return the receiver's summary or raise.
|
|
197
|
+
|
|
198
|
+
The JWS signature must already have been verified (see verify_attestation).
|
|
199
|
+
"""
|
|
200
|
+
for name in ("iss", "sub", "iat", "nbf", "exp", "jti"):
|
|
201
|
+
if name not in claims:
|
|
202
|
+
raise AttestationError("claims_invalid", f"missing claim {name}")
|
|
203
|
+
if claims.get("amr_attestation") != ATTESTATION_VERSION:
|
|
204
|
+
raise AttestationError("not_an_attestation", "amr_attestation claim missing or unknown")
|
|
205
|
+
for name in ("iat", "nbf", "exp"):
|
|
206
|
+
if isinstance(claims[name], bool) or not isinstance(claims[name], int):
|
|
207
|
+
raise AttestationError("claims_invalid", f"{name} must be an integer")
|
|
208
|
+
if claims["nbf"] > now + leeway:
|
|
209
|
+
raise AttestationError("not_yet_valid", f"valid from {_iso(claims['nbf'])}")
|
|
210
|
+
if claims["exp"] <= now - leeway:
|
|
211
|
+
raise AttestationError("expired", f"expired at {_iso(claims['exp'])}")
|
|
212
|
+
|
|
213
|
+
mandate = _require_keys(claims.get("amr_mandate"), _MANDATE_KEYS, "amr_mandate")
|
|
214
|
+
chain = claims.get("amr_chain")
|
|
215
|
+
if not isinstance(chain, list) or len(chain) > MAX_DELEGATION_DEPTH:
|
|
216
|
+
raise AttestationError("claims_invalid", "amr_chain must be a list of parent mandates")
|
|
217
|
+
links = [_require_keys(link, _LINK_KEYS, "amr_chain entry") for link in chain]
|
|
218
|
+
|
|
219
|
+
if claims["sub"] != mandate["agent_id"]:
|
|
220
|
+
raise AttestationError("claims_invalid", "sub differs from the mandate's agent")
|
|
221
|
+
if _perimeter_digest(mandate["perimeter"]) != mandate["perimeter_digest"]:
|
|
222
|
+
raise AttestationError("claims_invalid", "perimeter_digest does not match perimeter")
|
|
223
|
+
|
|
224
|
+
# The chain must be complete and in order: mandate -> parent -> ... -> root, and
|
|
225
|
+
# each mandate must have been granted by the agent of the mandate above it.
|
|
226
|
+
expected_parent = mandate["parent_mandate_id"]
|
|
227
|
+
delegator = mandate["principal_id"]
|
|
228
|
+
for link in links:
|
|
229
|
+
if link["id"] != expected_parent:
|
|
230
|
+
raise AttestationError("claims_invalid", "amr_chain is incomplete or out of order")
|
|
231
|
+
if link["agent_id"] != delegator:
|
|
232
|
+
raise AttestationError("claims_invalid", "amr_chain link not granted by its agent")
|
|
233
|
+
expected_parent = link["parent_mandate_id"]
|
|
234
|
+
delegator = link["principal_id"]
|
|
235
|
+
if expected_parent is not None:
|
|
236
|
+
raise AttestationError("claims_invalid", "amr_chain does not reach a root mandate")
|
|
237
|
+
|
|
238
|
+
# Active, and not expired before the attestation, at every level.
|
|
239
|
+
for entry in (mandate, *links):
|
|
240
|
+
if entry["status"] != "active":
|
|
241
|
+
raise AttestationError("claims_invalid", f"mandate {entry['id']} is not active")
|
|
242
|
+
try:
|
|
243
|
+
entry_expiry = _timestamp(entry["expires_at"])
|
|
244
|
+
except (TypeError, ValueError) as exc:
|
|
245
|
+
raise AttestationError("claims_invalid", "expires_at is not ISO 8601") from exc
|
|
246
|
+
if claims["exp"] > entry_expiry:
|
|
247
|
+
raise AttestationError(
|
|
248
|
+
"claims_invalid", f"attestation outlives mandate {entry['id']}"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
rechecked = False
|
|
252
|
+
if mandate["principal_signature"] is not None:
|
|
253
|
+
rechecked = _check_principal_signature(mandate)
|
|
254
|
+
|
|
255
|
+
signature = mandate["principal_signature"]
|
|
256
|
+
return {
|
|
257
|
+
"mandate_id": mandate["id"],
|
|
258
|
+
"principal_id": mandate["principal_id"],
|
|
259
|
+
"agent_id": mandate["agent_id"],
|
|
260
|
+
"scope": mandate["scope"],
|
|
261
|
+
"legal_basis": mandate["legal_basis"],
|
|
262
|
+
"perimeter": mandate["perimeter"],
|
|
263
|
+
"mandate_expires_at": mandate["expires_at"],
|
|
264
|
+
"delegated": mandate["parent_mandate_id"] is not None,
|
|
265
|
+
"delegation_chain": [
|
|
266
|
+
{"mandate_id": link["id"], "principal_id": link["principal_id"],
|
|
267
|
+
"agent_id": link["agent_id"]}
|
|
268
|
+
for link in links
|
|
269
|
+
],
|
|
270
|
+
"principal_signed": signature is not None,
|
|
271
|
+
"principal_key_id": signature["key_id"] if signature is not None else None,
|
|
272
|
+
"principal_signature_rechecked": rechecked,
|
|
273
|
+
# did:web keys: where and when the registry saw the domain publish the key.
|
|
274
|
+
# Not rechecked offline: fetch did_document_url again to see it today.
|
|
275
|
+
"principal_key_domain": (
|
|
276
|
+
signature.get("key_domain_proof") if signature is not None else None
|
|
277
|
+
),
|
|
278
|
+
"principal_did_web_unverified": (
|
|
279
|
+
bool(signature.get("did_web_unverified")) if signature is not None else False
|
|
280
|
+
),
|
|
281
|
+
"issuer": claims["iss"],
|
|
282
|
+
"audience": claims.get("aud"),
|
|
283
|
+
"status_checked_at": _iso(claims["iat"]),
|
|
284
|
+
"attestation_expires_at": _iso(claims["exp"]),
|
|
285
|
+
"jti": claims["jti"],
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _load_public_key(public_key_pem: bytes | str) -> ed25519.Ed25519PublicKey:
|
|
290
|
+
pem = public_key_pem.encode("ascii") if isinstance(public_key_pem, str) else public_key_pem
|
|
291
|
+
try:
|
|
292
|
+
key = serialization.load_pem_public_key(pem)
|
|
293
|
+
except ValueError as exc:
|
|
294
|
+
raise AttestationError("public_key_invalid", "not a PEM public key") from exc
|
|
295
|
+
if not isinstance(key, ed25519.Ed25519PublicKey):
|
|
296
|
+
raise AttestationError("public_key_invalid", "the registry key must be Ed25519")
|
|
297
|
+
return key
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def verify_attestation(
|
|
301
|
+
attestation: str,
|
|
302
|
+
public_key_pem: bytes | str,
|
|
303
|
+
*,
|
|
304
|
+
audience: str | None = None,
|
|
305
|
+
issuer: str | None = None,
|
|
306
|
+
now: float | None = None,
|
|
307
|
+
leeway: int = 0,
|
|
308
|
+
) -> dict[str, Any]:
|
|
309
|
+
"""Verify a mandate attestation offline, with the registry's public key only.
|
|
310
|
+
|
|
311
|
+
Checks, in order: the header (EdDSA only, attestation type, key id of this key),
|
|
312
|
+
the Ed25519 signature, the issuer and audience when given (an attestation addressed
|
|
313
|
+
to an audience is accepted only by a receiver that names that audience), the
|
|
314
|
+
validity window, then the content (see check_claims), including the principal's
|
|
315
|
+
own signature when the mandate carries one.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
attestation: The compact JWS returned by issue_mandate_attestation.
|
|
319
|
+
public_key_pem: The registry's public key (PEM), from get_registry_public_key.
|
|
320
|
+
audience: Who you are, if the attestation must be addressed to you.
|
|
321
|
+
issuer: The registry you expect (its token_issuer), if you want it checked.
|
|
322
|
+
now: Unix time to check against (default: the current time).
|
|
323
|
+
leeway: Seconds of clock skew tolerated on nbf and exp.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
{"valid": true, "reason": "ok", "attestation": {...summary}} or
|
|
327
|
+
{"valid": false, "reason": "<code>", "detail": "..."}.
|
|
328
|
+
"""
|
|
329
|
+
moment = datetime.now(UTC).timestamp() if now is None else now
|
|
330
|
+
try:
|
|
331
|
+
public_key = _load_public_key(public_key_pem)
|
|
332
|
+
try:
|
|
333
|
+
header = jwt.get_unverified_header(attestation)
|
|
334
|
+
except jwt.InvalidTokenError as exc:
|
|
335
|
+
raise AttestationError("malformed", "not a compact JWS") from exc
|
|
336
|
+
if header.get("alg") != ALGORITHM:
|
|
337
|
+
raise AttestationError("wrong_algorithm", "only EdDSA is accepted")
|
|
338
|
+
if header.get("typ") != ATTESTATION_TYP:
|
|
339
|
+
raise AttestationError("not_an_attestation", f"typ must be {ATTESTATION_TYP}")
|
|
340
|
+
if header.get("kid") != registry_key_id(public_key):
|
|
341
|
+
raise AttestationError("key_mismatch", "signed with another registry key")
|
|
342
|
+
try:
|
|
343
|
+
claims = jwt.decode(
|
|
344
|
+
attestation,
|
|
345
|
+
public_key,
|
|
346
|
+
algorithms=[ALGORITHM],
|
|
347
|
+
options={
|
|
348
|
+
"verify_exp": False,
|
|
349
|
+
"verify_nbf": False,
|
|
350
|
+
"verify_iat": False,
|
|
351
|
+
"verify_aud": False,
|
|
352
|
+
"verify_iss": False,
|
|
353
|
+
},
|
|
354
|
+
)
|
|
355
|
+
except jwt.InvalidSignatureError as exc:
|
|
356
|
+
raise AttestationError("bad_signature", "signature does not verify") from exc
|
|
357
|
+
except jwt.InvalidTokenError as exc:
|
|
358
|
+
raise AttestationError("malformed", str(exc)) from exc
|
|
359
|
+
if issuer is not None and claims.get("iss") != issuer:
|
|
360
|
+
raise AttestationError("wrong_issuer", "issued by another registry")
|
|
361
|
+
token_audience = claims.get("aud")
|
|
362
|
+
if token_audience is not None and token_audience != audience:
|
|
363
|
+
raise AttestationError("wrong_audience", "addressed to another receiver")
|
|
364
|
+
if audience is not None and token_audience is None:
|
|
365
|
+
raise AttestationError("wrong_audience", "not addressed to any receiver")
|
|
366
|
+
summary = check_claims(claims, moment, leeway)
|
|
367
|
+
except AttestationError as exc:
|
|
368
|
+
return {"valid": False, "reason": exc.code, "detail": exc.detail}
|
|
369
|
+
return {"valid": True, "reason": "ok", "attestation": summary}
|
amr/config.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""AMR configuration - loads from environment variables or .env file."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from pydantic import Field, field_validator
|
|
6
|
+
from pydantic_settings import BaseSettings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Settings(BaseSettings):
|
|
10
|
+
"""Application settings. Override via env vars prefixed AMR_."""
|
|
11
|
+
|
|
12
|
+
db_path: Path = Path("amr_mandates.db")
|
|
13
|
+
hash_algorithm: str = "sha256"
|
|
14
|
+
log_level: str = "INFO"
|
|
15
|
+
server_name: str = "Agent Mandate Registry"
|
|
16
|
+
server_version: str = "0.1.0"
|
|
17
|
+
|
|
18
|
+
# Token issuance
|
|
19
|
+
signing_key_path: Path = Path("amr_signing_key.pem")
|
|
20
|
+
public_key_path: Path = Path("amr_signing_key.pub")
|
|
21
|
+
token_issuer: str = "amr://localhost" # noqa: S105 — not a password, it's an issuer URI
|
|
22
|
+
token_lifetime_seconds: int = 300
|
|
23
|
+
|
|
24
|
+
# Principal signatures on mandates (see docs/principal-signature-spec.md).
|
|
25
|
+
# A principal that registered a key must always sign. When True, every mandate
|
|
26
|
+
# must be signed, so a principal without a registered key cannot grant one.
|
|
27
|
+
require_principal_signature: bool = False
|
|
28
|
+
# How old (or how far in the future) a principal's signed_at may be.
|
|
29
|
+
principal_signature_max_age_seconds: int = 900
|
|
30
|
+
|
|
31
|
+
# Mandate attestations shown by an agent to a third party (see
|
|
32
|
+
# docs/mandate-attestation-spec.md). Longest lifetime an attestation may have:
|
|
33
|
+
# a revocation reaches a receiver that checks offline only when it expires.
|
|
34
|
+
attestation_lifetime_seconds: int = Field(default=900, gt=0)
|
|
35
|
+
|
|
36
|
+
# Public registry (see docs/public-registry-spec.md): the signed snapshot written by
|
|
37
|
+
# `python -m amr.public_registry export` and served read-only by its WSGI app.
|
|
38
|
+
public_export_path: Path = Path("amr_public_registry.jws")
|
|
39
|
+
# Refuse to answer from a snapshot older than this (None: no limit, age shown).
|
|
40
|
+
public_snapshot_max_age_seconds: int | None = Field(default=None, gt=0)
|
|
41
|
+
|
|
42
|
+
# report_issue (see docs/report-issue-spec.md) files issues on this repository.
|
|
43
|
+
# Its token, AMR_ISSUE_TOKEN, is deliberately not a setting: report_issue reads it
|
|
44
|
+
# from the process environment only, never from a .env file.
|
|
45
|
+
issue_repository: str = Field(
|
|
46
|
+
default="JC7333/amr",
|
|
47
|
+
pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
@field_validator("issue_repository")
|
|
51
|
+
@classmethod
|
|
52
|
+
def _no_dot_segments(cls, value: str) -> str:
|
|
53
|
+
if any(part.strip(".") == "" for part in value.split("/")):
|
|
54
|
+
raise ValueError("owner and name cannot be only dots")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
model_config = {"env_prefix": "AMR_", "env_file": ".env", "extra": "ignore"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
settings = Settings()
|
amr/crypto/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# AMR Crypto
|
amr/crypto/chain.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""AMR cryptographic chain module - SHA-256 hash chaining (git-style, not blockchain)."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def compute_hash(data: dict[str, Any], previous_hash: str = "") -> str:
|
|
9
|
+
"""Compute a SHA-256 hash linking data to a previous hash in the chain.
|
|
10
|
+
|
|
11
|
+
Each entry is linked to the previous one via its hash, making the chain
|
|
12
|
+
tamper-evident: modifying any entry invalidates all subsequent hashes.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
data: The data dict to hash (will be JSON-serialized with sorted keys).
|
|
16
|
+
previous_hash: The hash of the previous entry in the chain (or "" for genesis).
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
A 64-character lowercase hex SHA-256 digest.
|
|
20
|
+
"""
|
|
21
|
+
payload = {"previous_hash": previous_hash, "data": data}
|
|
22
|
+
serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
|
|
23
|
+
return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def verify_chain(
|
|
27
|
+
entries: list[dict[str, Any]],
|
|
28
|
+
hash_field: str = "chain_hash",
|
|
29
|
+
initial_hash: str = "",
|
|
30
|
+
) -> bool:
|
|
31
|
+
"""Verify the integrity of a chain of hashed entries.
|
|
32
|
+
|
|
33
|
+
Recomputes the hash for each entry (excluding the stored chain_hash field)
|
|
34
|
+
and compares it with the stored value. Returns False if any entry has been
|
|
35
|
+
tampered with. An empty chain is considered valid (vacuous truth).
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
entries: List of dicts, each containing a hash_field with the stored hash.
|
|
39
|
+
hash_field: The name of the field containing the stored chain hash.
|
|
40
|
+
initial_hash: The hash to use as the genesis previous_hash (default "").
|
|
41
|
+
For action chains, pass the mandate's chain_hash.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
True if the chain is intact, False if any entry fails verification.
|
|
45
|
+
"""
|
|
46
|
+
if not entries:
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
previous_hash = initial_hash
|
|
50
|
+
for entry in entries:
|
|
51
|
+
stored_hash = entry.get(hash_field, "")
|
|
52
|
+
# Rebuild the data without the chain_hash field
|
|
53
|
+
data_without_hash = {k: v for k, v in entry.items() if k != hash_field}
|
|
54
|
+
expected_hash = compute_hash(data_without_hash, previous_hash)
|
|
55
|
+
if expected_hash != stored_hash:
|
|
56
|
+
return False
|
|
57
|
+
previous_hash = stored_hash
|
|
58
|
+
|
|
59
|
+
return True
|
amr/crypto/principal.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Principal signatures: the principal signs the mandate it grants (Ed25519).
|
|
2
|
+
|
|
3
|
+
Separate from the registry's own token key (amr.crypto.signing): this module only
|
|
4
|
+
verifies signatures made by principals with their own keys. It never holds a private key.
|
|
5
|
+
|
|
6
|
+
Encodings: public keys are the 32 raw Ed25519 bytes and signatures the 64 raw bytes,
|
|
7
|
+
both base64url without padding. Signed payloads are canonical JSON (sorted keys, no
|
|
8
|
+
spaces, UTF-8), always built by this module so the signer and the registry agree.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import binascii
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from cryptography.exceptions import InvalidSignature
|
|
19
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
20
|
+
|
|
21
|
+
MANDATE_CONTEXT = "amr.mandate.v1"
|
|
22
|
+
KEY_REGISTRATION_CONTEXT = "amr.principal_key.v1"
|
|
23
|
+
|
|
24
|
+
_PUBLIC_KEY_BYTES = 32
|
|
25
|
+
_SIGNATURE_BYTES = 64
|
|
26
|
+
_B64URL_ALPHABET = frozenset(
|
|
27
|
+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PrincipalSignatureError(Exception):
|
|
32
|
+
"""A principal key or signature problem, with a stable machine-readable code."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, code: str, message: str) -> None:
|
|
35
|
+
super().__init__(f"{code}: {message}")
|
|
36
|
+
self.code = code
|
|
37
|
+
self.message = message
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def b64url_encode(raw: bytes) -> str:
|
|
41
|
+
"""Base64url without padding."""
|
|
42
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def b64url_decode(text: str, expected_len: int, what: str) -> bytes:
|
|
46
|
+
"""Decode base64url (padding optional) and check the decoded length.
|
|
47
|
+
|
|
48
|
+
Raises PrincipalSignatureError(<what>_invalid) on any malformed input.
|
|
49
|
+
"""
|
|
50
|
+
code = f"{what}_invalid"
|
|
51
|
+
if not isinstance(text, str) or not text or len(text) > 200:
|
|
52
|
+
raise PrincipalSignatureError(code, f"{what} must be a base64url string")
|
|
53
|
+
stripped = text.rstrip("=")
|
|
54
|
+
if any(c not in _B64URL_ALPHABET for c in stripped):
|
|
55
|
+
raise PrincipalSignatureError(code, f"{what} must be base64url (A-Z a-z 0-9 - _)")
|
|
56
|
+
try:
|
|
57
|
+
raw = base64.urlsafe_b64decode(stripped + "=" * (-len(stripped) % 4))
|
|
58
|
+
except (binascii.Error, ValueError) as exc:
|
|
59
|
+
raise PrincipalSignatureError(code, f"{what} is not valid base64url") from exc
|
|
60
|
+
if len(raw) != expected_len:
|
|
61
|
+
raise PrincipalSignatureError(code, f"{what} must decode to {expected_len} bytes")
|
|
62
|
+
return raw
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_public_key(public_key: str) -> bytes:
|
|
66
|
+
"""Return the 32 raw bytes of a base64url Ed25519 public key, or raise."""
|
|
67
|
+
raw = b64url_decode(public_key, _PUBLIC_KEY_BYTES, "public_key")
|
|
68
|
+
try:
|
|
69
|
+
ed25519.Ed25519PublicKey.from_public_bytes(raw)
|
|
70
|
+
except ValueError as exc:
|
|
71
|
+
raise PrincipalSignatureError("public_key_invalid", "not an Ed25519 key") from exc
|
|
72
|
+
return raw
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_signature(signature: str) -> bytes:
|
|
76
|
+
"""Return the 64 raw bytes of a base64url Ed25519 signature, or raise."""
|
|
77
|
+
return b64url_decode(signature, _SIGNATURE_BYTES, "principal_signature")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def key_id(public_key_raw: bytes) -> str:
|
|
81
|
+
"""Stable key identifier: first 16 hex chars of SHA-256 of the raw public key."""
|
|
82
|
+
return hashlib.sha256(public_key_raw).hexdigest()[:16]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def verify(public_key_raw: bytes, payload: bytes, signature_raw: bytes) -> bool:
|
|
86
|
+
"""True if ``signature_raw`` is a valid Ed25519 signature of ``payload``."""
|
|
87
|
+
try:
|
|
88
|
+
ed25519.Ed25519PublicKey.from_public_bytes(public_key_raw).verify(
|
|
89
|
+
signature_raw, payload
|
|
90
|
+
)
|
|
91
|
+
except (InvalidSignature, ValueError):
|
|
92
|
+
return False
|
|
93
|
+
return True
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def canonical_json(obj: dict[str, Any]) -> bytes:
|
|
97
|
+
"""Canonical JSON bytes: sorted keys, no whitespace, UTF-8."""
|
|
98
|
+
return json.dumps(
|
|
99
|
+
obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
100
|
+
).encode("utf-8")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_signed_at(signed_at: str) -> datetime:
|
|
104
|
+
"""Parse an ISO 8601 timestamp that must carry a timezone, or raise."""
|
|
105
|
+
if not isinstance(signed_at, str) or not signed_at or len(signed_at) > 64:
|
|
106
|
+
raise PrincipalSignatureError("signed_at_invalid", "signed_at must be an ISO 8601 string")
|
|
107
|
+
try:
|
|
108
|
+
moment = datetime.fromisoformat(signed_at)
|
|
109
|
+
except ValueError as exc:
|
|
110
|
+
raise PrincipalSignatureError(
|
|
111
|
+
"signed_at_invalid", "signed_at must be an ISO 8601 timestamp"
|
|
112
|
+
) from exc
|
|
113
|
+
if moment.tzinfo is None:
|
|
114
|
+
raise PrincipalSignatureError(
|
|
115
|
+
"signed_at_invalid", "signed_at must include a timezone, e.g. +00:00"
|
|
116
|
+
)
|
|
117
|
+
return moment
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def mandate_payload(
|
|
121
|
+
*,
|
|
122
|
+
principal_id: str,
|
|
123
|
+
agent_id: str,
|
|
124
|
+
scope: str,
|
|
125
|
+
legal_basis: dict[str, str],
|
|
126
|
+
duration_hours: float,
|
|
127
|
+
parent_mandate_id: str | None,
|
|
128
|
+
metadata: dict[str, str],
|
|
129
|
+
perimeter: dict[str, Any] | None,
|
|
130
|
+
signed_at: str,
|
|
131
|
+
) -> bytes:
|
|
132
|
+
"""The exact bytes a principal signs to grant a mandate.
|
|
133
|
+
|
|
134
|
+
Covers every field the principal decides; the registry adds only the mandate id
|
|
135
|
+
and the timestamps. ``perimeter`` is the requested perimeter in canonical form.
|
|
136
|
+
"""
|
|
137
|
+
return canonical_json(
|
|
138
|
+
{
|
|
139
|
+
"context": MANDATE_CONTEXT,
|
|
140
|
+
"principal_id": principal_id,
|
|
141
|
+
"agent_id": agent_id,
|
|
142
|
+
"scope": scope,
|
|
143
|
+
"legal_basis": legal_basis,
|
|
144
|
+
"duration_hours": float(duration_hours),
|
|
145
|
+
"parent_mandate_id": parent_mandate_id,
|
|
146
|
+
"metadata": metadata,
|
|
147
|
+
"perimeter": perimeter,
|
|
148
|
+
"signed_at": signed_at,
|
|
149
|
+
}
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def key_registration_payload(principal_id: str, public_key: str) -> bytes:
|
|
154
|
+
"""The exact bytes a principal signs to prove it holds the key it registers."""
|
|
155
|
+
return canonical_json(
|
|
156
|
+
{
|
|
157
|
+
"context": KEY_REGISTRATION_CONTEXT,
|
|
158
|
+
"principal_id": principal_id,
|
|
159
|
+
"public_key": public_key,
|
|
160
|
+
}
|
|
161
|
+
)
|