umf-access 0.1.0.dev8__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.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
|
@@ -0,0 +1,1491 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Closed generation ROOT registry and original setup records.
|
|
3
|
+
|
|
4
|
+
This module contains native-free codecs and the configured ROOT verifier.
|
|
5
|
+
Native observations and process/session authority are supplied only by the
|
|
6
|
+
fixed supervisor facade above this module.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import fcntl
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import stat
|
|
17
|
+
import threading
|
|
18
|
+
import uuid
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..canonical import canonical_json
|
|
24
|
+
from .generation_enrollment_ledger import (
|
|
25
|
+
_MAX_CONFIG,
|
|
26
|
+
_MAX_RECORDS,
|
|
27
|
+
_MAX_REQUEST,
|
|
28
|
+
GenerationEnrollmentAuthorityError,
|
|
29
|
+
_config,
|
|
30
|
+
_json_copy,
|
|
31
|
+
_Ledger,
|
|
32
|
+
_parse_canonical,
|
|
33
|
+
_text,
|
|
34
|
+
_uint,
|
|
35
|
+
)
|
|
36
|
+
from .generation_enrollment_ledger import (
|
|
37
|
+
_fail as _logical_fail,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
ROOT_REGISTRY_PROFILE = 'umf.generation-authority-registry/0.1'
|
|
41
|
+
ROOT_POLICY_PROFILE = 'umf.generation-authority-root-policy/0.1'
|
|
42
|
+
ROOT_APPROVAL_PROFILE = 'umf.generation-authority-trust-approval/0.1'
|
|
43
|
+
ROOT_INTENT_PROFILE = 'umf.generation-authority-trust-intent/0.1'
|
|
44
|
+
ROOT_ENROLLMENT_PROFILE = 'umf.original-generation-authority-enrollment/0.1'
|
|
45
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
46
|
+
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
|
|
47
|
+
_MAX_SAFE = 9_007_199_254_740_991
|
|
48
|
+
_MAX_SAFE_INT = _MAX_SAFE
|
|
49
|
+
_MAX_REGISTRY = 8 * 1024 * 1024
|
|
50
|
+
_MAX_REQUESTS = 4096
|
|
51
|
+
_MAX_ENROLLMENTS = 256
|
|
52
|
+
|
|
53
|
+
TRUST_PROFILE = 'umf.generation-authority-trust-enrollment/0.1'
|
|
54
|
+
CONTEXT_PROFILE = 'umf.generation-authority-context/0.1'
|
|
55
|
+
PURPOSES = ('production', 'native-acceptance')
|
|
56
|
+
_CONTEXT_REGISTRY_PROFILE = 'umf.generation-authority-context-registry/0.2'
|
|
57
|
+
_CONTEXT_EVENT_KINDS = {'context-birth-intent', 'context-birth-confirmed'}
|
|
58
|
+
_TRUST_SEAL = object()
|
|
59
|
+
_TRUST_ISSUER_ORIGINS: dict[int, tuple[object, str, object, object]] = {}
|
|
60
|
+
_CONTEXT_SEAL = object()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _ImmutableOpaque:
|
|
64
|
+
__slots__ = ()
|
|
65
|
+
|
|
66
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
67
|
+
if hasattr(self, name):
|
|
68
|
+
raise AttributeError('opaque authority values are immutable')
|
|
69
|
+
object.__setattr__(self, name, value)
|
|
70
|
+
|
|
71
|
+
def __delattr__(self, name: str) -> None:
|
|
72
|
+
raise AttributeError('opaque authority values are immutable')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class GenerationAuthorityBootstrapError(RuntimeError):
|
|
76
|
+
"""Sanitized failure from the original generation ROOT registry."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, code: str):
|
|
79
|
+
super().__init__(code)
|
|
80
|
+
self.code = code
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _fail(code: str) -> None:
|
|
84
|
+
raise GenerationAuthorityBootstrapError(code)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _closed(value: object, keys: set[str], code: str = 'generation-root-record-invalid') -> dict[str, Any]:
|
|
88
|
+
if type(value) is not dict or set(value) != keys:
|
|
89
|
+
_fail(code)
|
|
90
|
+
return value
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _uuid(value: object) -> str:
|
|
94
|
+
if type(value) is not str or not _UUID.fullmatch(value):
|
|
95
|
+
_fail('generation-root-record-invalid')
|
|
96
|
+
try:
|
|
97
|
+
if str(uuid.UUID(value)) != value:
|
|
98
|
+
_fail('generation-root-record-invalid')
|
|
99
|
+
except ValueError:
|
|
100
|
+
_fail('generation-root-record-invalid')
|
|
101
|
+
return value
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _digest(value: object) -> str:
|
|
105
|
+
if type(value) is not str or not _HEX.fullmatch(value):
|
|
106
|
+
_fail('generation-root-record-invalid')
|
|
107
|
+
return value
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _canonical(value: object) -> bytes:
|
|
111
|
+
try:
|
|
112
|
+
return canonical_json(value).encode('utf-8')
|
|
113
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
114
|
+
_fail('generation-root-record-invalid')
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _parse(raw: object) -> dict[str, Any]:
|
|
118
|
+
if type(raw) is not bytes or not 1 <= len(raw) <= _MAX_REGISTRY:
|
|
119
|
+
_fail('generation-root-registry-invalid')
|
|
120
|
+
def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
121
|
+
result: dict[str, Any] = {}
|
|
122
|
+
for key, value in items:
|
|
123
|
+
if key in result:
|
|
124
|
+
_fail('generation-root-registry-invalid')
|
|
125
|
+
result[key] = value
|
|
126
|
+
return result
|
|
127
|
+
try:
|
|
128
|
+
value = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs,
|
|
129
|
+
parse_float=lambda _item: _fail('generation-root-registry-invalid'),
|
|
130
|
+
parse_constant=lambda _item: _fail('generation-root-registry-invalid'))
|
|
131
|
+
except GenerationAuthorityBootstrapError:
|
|
132
|
+
raise
|
|
133
|
+
except (UnicodeError, ValueError, RecursionError):
|
|
134
|
+
_fail('generation-root-registry-invalid')
|
|
135
|
+
if type(value) is not dict or _canonical(value) != raw:
|
|
136
|
+
_fail('generation-root-registry-noncanonical')
|
|
137
|
+
return value
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _sha(raw: bytes) -> str:
|
|
141
|
+
return hashlib.sha256(raw).hexdigest()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def initial_registry(registry_id: str, anchor_digest: str) -> dict[str, Any]:
|
|
145
|
+
return {'profile': ROOT_REGISTRY_PROFILE, 'registryId': _uuid(registry_id),
|
|
146
|
+
'anchorDigest': _digest(anchor_digest), 'sequence': 0,
|
|
147
|
+
'requests': [], 'enrollments': []}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def initial_registry_bytes(registry_id: str, anchor_digest: str) -> bytes:
|
|
151
|
+
"""Return the canonical zero-state registry (no terminal LF)."""
|
|
152
|
+
return _canonical(initial_registry(registry_id, anchor_digest))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _root_text(value: object, maximum: int) -> str:
|
|
156
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
157
|
+
_fail('generation-root-registry-invalid')
|
|
158
|
+
try:
|
|
159
|
+
if len(value.encode('utf-8')) > maximum:
|
|
160
|
+
_fail('generation-root-registry-invalid')
|
|
161
|
+
except UnicodeEncodeError:
|
|
162
|
+
_fail('generation-root-registry-invalid')
|
|
163
|
+
return value
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _root_canonical(value: object, *, maximum: int = _MAX_REGISTRY) -> bytes:
|
|
167
|
+
try:
|
|
168
|
+
copied = _json_copy(value)
|
|
169
|
+
encoded = canonical_json(copied).encode('utf-8')
|
|
170
|
+
except (GenerationEnrollmentAuthorityError, TypeError, ValueError,
|
|
171
|
+
UnicodeError, RecursionError):
|
|
172
|
+
_fail('generation-root-registry-invalid')
|
|
173
|
+
if len(encoded) > maximum:
|
|
174
|
+
_fail('generation-root-registry-capacity')
|
|
175
|
+
return encoded
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _root_same_json(left: object, right: object) -> bool:
|
|
179
|
+
"""Compare JSON values without Python's bool/int/float equality aliases."""
|
|
180
|
+
try:
|
|
181
|
+
return _root_canonical(left) == _root_canonical(right)
|
|
182
|
+
except GenerationAuthorityBootstrapError:
|
|
183
|
+
return False
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _root_config(value: object) -> dict[str, Any]:
|
|
187
|
+
try:
|
|
188
|
+
config, _keys = _config(value)
|
|
189
|
+
if _root_canonical(config, maximum=_MAX_CONFIG) != _root_canonical(
|
|
190
|
+
value, maximum=_MAX_CONFIG):
|
|
191
|
+
_fail('generation-root-registry-invalid')
|
|
192
|
+
return config
|
|
193
|
+
except (GenerationEnrollmentAuthorityError, TypeError, ValueError, KeyError,
|
|
194
|
+
AttributeError, RecursionError, UnicodeError):
|
|
195
|
+
_fail('generation-root-registry-invalid')
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _root_policy(value: object) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
199
|
+
policy = _closed(value, {'profile', 'authorityId', 'policyRevision', 'keys'})
|
|
200
|
+
if policy['profile'] != ROOT_POLICY_PROFILE:
|
|
201
|
+
_fail('generation-root-policy-invalid')
|
|
202
|
+
authority_id = _uuid(policy['authorityId'])
|
|
203
|
+
revision = _root_text(policy['policyRevision'], 128)
|
|
204
|
+
keys = policy['keys']
|
|
205
|
+
if type(keys) is not list or not 1 <= len(keys) <= 32:
|
|
206
|
+
_fail('generation-root-policy-invalid')
|
|
207
|
+
seen: set[str] = set()
|
|
208
|
+
for raw_key in keys:
|
|
209
|
+
key = _closed(raw_key, {'keyId', 'publicKey', 'principalId',
|
|
210
|
+
'logicalAuthorityIds', 'configurationProfiles'})
|
|
211
|
+
key_id = _root_text(key['keyId'], 128)
|
|
212
|
+
_root_text(key['principalId'], 128)
|
|
213
|
+
if key_id in seen:
|
|
214
|
+
_fail('generation-root-policy-invalid')
|
|
215
|
+
seen.add(key_id)
|
|
216
|
+
public = key['publicKey']
|
|
217
|
+
if type(public) is not str or re.fullmatch(r'[A-Za-z0-9_-]{43}', public) is None:
|
|
218
|
+
_fail('generation-root-policy-invalid')
|
|
219
|
+
try:
|
|
220
|
+
public_bytes = base64.urlsafe_b64decode(public + '=')
|
|
221
|
+
except (ValueError, TypeError):
|
|
222
|
+
_fail('generation-root-policy-invalid')
|
|
223
|
+
if (len(public_bytes) != 32
|
|
224
|
+
or base64.urlsafe_b64encode(public_bytes).decode('ascii').rstrip('=') != public):
|
|
225
|
+
_fail('generation-root-policy-invalid')
|
|
226
|
+
logical_ids = key['logicalAuthorityIds']
|
|
227
|
+
if type(logical_ids) is not list or not 1 <= len(logical_ids) <= 256:
|
|
228
|
+
_fail('generation-root-policy-invalid')
|
|
229
|
+
normalized_ids = [_uuid(item) for item in logical_ids]
|
|
230
|
+
if len(set(normalized_ids)) != len(normalized_ids):
|
|
231
|
+
_fail('generation-root-policy-invalid')
|
|
232
|
+
profiles = key['configurationProfiles']
|
|
233
|
+
if (type(profiles) is not list or not profiles
|
|
234
|
+
or any(type(item) is not str for item in profiles)
|
|
235
|
+
or len(set(profiles)) != len(profiles)
|
|
236
|
+
or any(item != _config_profile() for item in profiles)):
|
|
237
|
+
_fail('generation-root-policy-invalid')
|
|
238
|
+
# The policy is separately bound by the original owner-bootstrap record;
|
|
239
|
+
# payload validation selects the matching configured key below.
|
|
240
|
+
try:
|
|
241
|
+
policy_bytes = _root_canonical(policy, maximum=_MAX_CONFIG)
|
|
242
|
+
except GenerationEnrollmentAuthorityError:
|
|
243
|
+
_fail('generation-root-policy-invalid')
|
|
244
|
+
return policy, {'authorityId': authority_id, 'policyRevision': revision,
|
|
245
|
+
'digest': _sha(policy_bytes)}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _config_profile() -> str:
|
|
249
|
+
return 'umf.configured-generation-enrollment-authority/0.1'
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_ROOT_PAYLOAD_FIELDS = {
|
|
253
|
+
'profile', 'scope', 'rootAuthorityId', 'rootPolicyRevision', 'keyId',
|
|
254
|
+
'principalId', 'approvalId', 'purpose', 'bootstrapEnrollmentId',
|
|
255
|
+
'rootPolicyDigest', 'supervisorId', 'custodianId', 'providerId',
|
|
256
|
+
'installationId', 'intentDigest',
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _validate_root_intent(intent_value: object, *, request: dict[str, Any]
|
|
261
|
+
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
262
|
+
intent = _closed(intent_value, {'profile', 'contextId', 'trust', 'configuration',
|
|
263
|
+
'configurationDigest', 'nativeEvidenceDigest'})
|
|
264
|
+
if intent['profile'] != ROOT_INTENT_PROFILE:
|
|
265
|
+
_fail('generation-root-registry-invalid')
|
|
266
|
+
context_id = _uuid(intent['contextId'])
|
|
267
|
+
trust = _closed(intent['trust'], {
|
|
268
|
+
'profile', 'enrollmentId', 'ownerBootstrapContextDigest', 'configurationDigest',
|
|
269
|
+
'supervisorId', 'custodianId', 'providerId', 'installationId',
|
|
270
|
+
'targetCustodyDigest', 'storeCreationReceiptDigest', 'custodySequence',
|
|
271
|
+
})
|
|
272
|
+
configuration = _root_config(intent['configuration'])
|
|
273
|
+
configuration_digest = _digest(intent['configurationDigest'])
|
|
274
|
+
_digest(intent['nativeEvidenceDigest'])
|
|
275
|
+
if (trust['profile'] != TRUST_PROFILE
|
|
276
|
+
or _uuid(trust['enrollmentId']) != request['enrollmentId']
|
|
277
|
+
or trust['configurationDigest'] != configuration_digest
|
|
278
|
+
or configuration_digest != _sha(_root_canonical(configuration, maximum=_MAX_CONFIG))
|
|
279
|
+
or _uuid(trust['supervisorId']) != configuration['supervisorId']
|
|
280
|
+
or _uuid(trust['custodianId']) != configuration['custodianId']
|
|
281
|
+
or _uuid(trust['providerId']) != configuration['providerId']
|
|
282
|
+
or _root_text(trust['installationId'], 256) != configuration['installationId']
|
|
283
|
+
or _digest(trust['targetCustodyDigest'])
|
|
284
|
+
!= _sha(_root_canonical(configuration['targetCustody']))
|
|
285
|
+
or _uint_root(trust['custodySequence']) != request['reservedSequence']):
|
|
286
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
287
|
+
_digest(trust['ownerBootstrapContextDigest'])
|
|
288
|
+
_digest(trust['storeCreationReceiptDigest'])
|
|
289
|
+
if context_id != request['contextId']:
|
|
290
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
291
|
+
return intent, trust, configuration
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _uint_root(value: object) -> int:
|
|
295
|
+
if type(value) is not int or not 0 <= value <= _MAX_SAFE:
|
|
296
|
+
_fail('generation-root-registry-invalid')
|
|
297
|
+
return value
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _validate_root_payload(payload_value: object, *, intent: dict[str, Any],
|
|
301
|
+
trust: dict[str, Any], configuration: dict[str, Any],
|
|
302
|
+
effect: list[str], root_policy: object, purpose: str,
|
|
303
|
+
bootstrap_enrollment_id: str) -> dict[str, Any]:
|
|
304
|
+
payload = _closed(payload_value, _ROOT_PAYLOAD_FIELDS)
|
|
305
|
+
if (payload['profile'] != ROOT_APPROVAL_PROFILE
|
|
306
|
+
or payload['scope'] != 'enroll-generation-authority'):
|
|
307
|
+
_fail('generation-root-approval-invalid')
|
|
308
|
+
root_authority_id = _uuid(payload['rootAuthorityId'])
|
|
309
|
+
root_revision = _root_text(payload['rootPolicyRevision'], 128)
|
|
310
|
+
key_id = _root_text(payload['keyId'], 128)
|
|
311
|
+
principal_id = _root_text(payload['principalId'], 128)
|
|
312
|
+
_uuid(payload['approvalId'])
|
|
313
|
+
payload_purpose = payload['purpose']
|
|
314
|
+
if payload_purpose not in PURPOSES:
|
|
315
|
+
_fail('generation-root-approval-invalid')
|
|
316
|
+
bootstrap_id = _uuid(payload['bootstrapEnrollmentId'])
|
|
317
|
+
policy_digest = _digest(payload['rootPolicyDigest'])
|
|
318
|
+
supervisor_id = _uuid(payload['supervisorId'])
|
|
319
|
+
custodian_id = _uuid(payload['custodianId'])
|
|
320
|
+
provider_id = _uuid(payload['providerId'])
|
|
321
|
+
installation_id = _root_text(payload['installationId'], 256)
|
|
322
|
+
intent_digest = _digest(payload['intentDigest'])
|
|
323
|
+
if (payload_purpose != purpose or payload_purpose != configuration['purpose']
|
|
324
|
+
or bootstrap_id != bootstrap_enrollment_id
|
|
325
|
+
or intent_digest != _sha(_root_canonical(intent, maximum=2 * _MAX_CONFIG))
|
|
326
|
+
or supervisor_id != trust['supervisorId']
|
|
327
|
+
or custodian_id != trust['custodianId']
|
|
328
|
+
or provider_id != trust['providerId']
|
|
329
|
+
or installation_id != trust['installationId']
|
|
330
|
+
or effect != ['enroll-generation-authority', bootstrap_id, provider_id,
|
|
331
|
+
installation_id, configuration['authorityId'],
|
|
332
|
+
configuration['policyRevision']]):
|
|
333
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
334
|
+
policy, policy_meta = _root_policy(root_policy)
|
|
335
|
+
if (root_authority_id != policy_meta['authorityId']
|
|
336
|
+
or root_revision != policy_meta['policyRevision']
|
|
337
|
+
or policy_digest != policy_meta['digest']):
|
|
338
|
+
_fail('generation-root-approval-invalid')
|
|
339
|
+
matching = [key for key in policy['keys']
|
|
340
|
+
if key['keyId'] == key_id and key['principalId'] == principal_id]
|
|
341
|
+
if len(matching) != 1:
|
|
342
|
+
_fail('generation-root-key-unavailable')
|
|
343
|
+
selected = matching[0]
|
|
344
|
+
if (configuration['authorityId'] not in selected['logicalAuthorityIds']
|
|
345
|
+
or configuration['profile'] not in selected['configurationProfiles']):
|
|
346
|
+
_fail('generation-root-profile-denied')
|
|
347
|
+
return payload
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _validate_root_envelope(envelope_value: object, *, payload: dict[str, Any]) -> str:
|
|
351
|
+
envelope = _closed(envelope_value, {'payload', 'signature'})
|
|
352
|
+
envelope_payload = _closed(envelope['payload'], _ROOT_PAYLOAD_FIELDS)
|
|
353
|
+
if not _root_same_json(envelope_payload, payload):
|
|
354
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
355
|
+
_root_canonical(payload, maximum=16_384)
|
|
356
|
+
signature = envelope['signature']
|
|
357
|
+
if type(signature) is not str or re.fullmatch(r'[A-Za-z0-9_-]{86}', signature) is None:
|
|
358
|
+
_fail('generation-root-signature-invalid')
|
|
359
|
+
try:
|
|
360
|
+
raw = base64.urlsafe_b64decode(signature + '==')
|
|
361
|
+
except (ValueError, TypeError):
|
|
362
|
+
_fail('generation-root-signature-invalid')
|
|
363
|
+
if (len(raw) != 64
|
|
364
|
+
or base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=') != signature):
|
|
365
|
+
_fail('generation-root-signature-invalid')
|
|
366
|
+
return _sha(_root_canonical(envelope, maximum=16_384))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def validate_registry(raw: bytes, *, registry_id: str,
|
|
370
|
+
anchor_digest: str, root_policy: object, purpose: str,
|
|
371
|
+
bootstrap_enrollment_id: str) -> dict[str, Any]:
|
|
372
|
+
"""Validate the closed registry against its original configured root.
|
|
373
|
+
|
|
374
|
+
This checks structural/cross-record integrity and verifies every confirmed
|
|
375
|
+
root signature. It does not establish native deployment custody or nonrewind
|
|
376
|
+
provenance; those remain obligations of the fixed original host resolver.
|
|
377
|
+
"""
|
|
378
|
+
value = _parse(raw)
|
|
379
|
+
_closed(value, {'profile', 'registryId', 'anchorDigest', 'sequence',
|
|
380
|
+
'requests', 'enrollments'}, 'generation-root-registry-invalid')
|
|
381
|
+
if (value['profile'] != ROOT_REGISTRY_PROFILE
|
|
382
|
+
or value['registryId'] != _uuid(registry_id)
|
|
383
|
+
or value['anchorDigest'] != _digest(anchor_digest)):
|
|
384
|
+
_fail('generation-root-registry-binding-mismatch')
|
|
385
|
+
bootstrap_id = _uuid(bootstrap_enrollment_id)
|
|
386
|
+
if type(purpose) is not str or purpose not in PURPOSES:
|
|
387
|
+
_fail('generation-root-approval-invalid')
|
|
388
|
+
try:
|
|
389
|
+
trusted_policy = _closed(_json_copy(root_policy), {
|
|
390
|
+
'profile', 'authorityId', 'policyRevision', 'keys'})
|
|
391
|
+
except GenerationEnrollmentAuthorityError:
|
|
392
|
+
_fail('generation-root-policy-invalid')
|
|
393
|
+
_root_policy(trusted_policy)
|
|
394
|
+
sequence = value['sequence']
|
|
395
|
+
requests = value['requests']
|
|
396
|
+
enrollments = value['enrollments']
|
|
397
|
+
if (type(sequence) is not int or not 0 <= sequence <= _MAX_SAFE
|
|
398
|
+
or type(requests) is not list or len(requests) > _MAX_REQUESTS
|
|
399
|
+
or type(enrollments) is not list or len(enrollments) > _MAX_ENROLLMENTS):
|
|
400
|
+
_fail('generation-root-registry-capacity')
|
|
401
|
+
reserved: list[int] = []
|
|
402
|
+
confirmed: list[int] = []
|
|
403
|
+
request_ids: set[str] = set()
|
|
404
|
+
approval_ids: set[str] = set()
|
|
405
|
+
enrollment_ids: set[str] = set()
|
|
406
|
+
effect_keys: set[tuple[str, ...]] = set()
|
|
407
|
+
by_id: dict[str, dict[str, Any]] = {}
|
|
408
|
+
context_ids: set[str] = set()
|
|
409
|
+
validated: dict[str, dict[str, Any]] = {}
|
|
410
|
+
for request in requests:
|
|
411
|
+
_closed(request, {'requestId', 'enrollmentId', 'contextId', 'effectKey',
|
|
412
|
+
'intent', 'payload', 'state', 'reservedSequence',
|
|
413
|
+
'confirmedSequence', 'approvalEnvelope'},
|
|
414
|
+
'generation-root-registry-invalid')
|
|
415
|
+
request_id = _uuid(request['requestId'])
|
|
416
|
+
enrollment_id = _uuid(request['enrollmentId'])
|
|
417
|
+
context_id = _uuid(request['contextId'])
|
|
418
|
+
if (request_id in request_ids or enrollment_id in enrollment_ids
|
|
419
|
+
or context_id in context_ids):
|
|
420
|
+
_fail('generation-root-registry-duplicate-identity')
|
|
421
|
+
request_ids.add(request_id); enrollment_ids.add(enrollment_id)
|
|
422
|
+
context_ids.add(context_id)
|
|
423
|
+
key = request['effectKey']
|
|
424
|
+
if (type(key) is not list or len(key) != 6
|
|
425
|
+
or any(type(part) is not str or not part for part in key)):
|
|
426
|
+
_fail('generation-root-registry-invalid')
|
|
427
|
+
for part in key:
|
|
428
|
+
_root_text(part, 256)
|
|
429
|
+
effect = tuple(key)
|
|
430
|
+
if effect in effect_keys:
|
|
431
|
+
_fail('generation-root-registry-duplicate-effect')
|
|
432
|
+
effect_keys.add(effect)
|
|
433
|
+
reserve_seq = request['reservedSequence']
|
|
434
|
+
confirm_seq = request['confirmedSequence']
|
|
435
|
+
if (type(reserve_seq) is not int or not 1 <= reserve_seq <= sequence):
|
|
436
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
437
|
+
reserved.append(reserve_seq)
|
|
438
|
+
intent, trust, configuration = _validate_root_intent(request['intent'], request=request)
|
|
439
|
+
payload = _validate_root_payload(
|
|
440
|
+
request['payload'], intent=intent, trust=trust, configuration=configuration,
|
|
441
|
+
effect=key, root_policy=trusted_policy, purpose=purpose,
|
|
442
|
+
bootstrap_enrollment_id=bootstrap_id)
|
|
443
|
+
approval_id = _uuid(payload['approvalId'])
|
|
444
|
+
if approval_id in approval_ids:
|
|
445
|
+
_fail('generation-root-registry-duplicate-approval')
|
|
446
|
+
approval_ids.add(approval_id)
|
|
447
|
+
envelope_digest: str | None = None
|
|
448
|
+
if request['state'] == 'prepared':
|
|
449
|
+
if confirm_seq is not None or request['approvalEnvelope'] is not None:
|
|
450
|
+
_fail('generation-root-registry-invalid')
|
|
451
|
+
elif request['state'] == 'confirmed':
|
|
452
|
+
if (type(confirm_seq) is not int or not reserve_seq < confirm_seq <= sequence
|
|
453
|
+
or type(request['approvalEnvelope']) is not dict):
|
|
454
|
+
_fail('generation-root-registry-invalid')
|
|
455
|
+
confirmed.append(confirm_seq)
|
|
456
|
+
verifier = ConfiguredGenerationAuthorityRootVerifier(trusted_policy, purpose=purpose)
|
|
457
|
+
envelope_digest = _validate_root_envelope(
|
|
458
|
+
request['approvalEnvelope'], payload=payload)
|
|
459
|
+
try:
|
|
460
|
+
verified_approval_id = verifier.verify_approval(
|
|
461
|
+
request['approvalEnvelope']['payload'],
|
|
462
|
+
request['approvalEnvelope']['signature'])
|
|
463
|
+
except GenerationAuthorityBootstrapError:
|
|
464
|
+
raise
|
|
465
|
+
except (ImportError, ValueError, TypeError, KeyError, AttributeError,
|
|
466
|
+
IndexError, OverflowError):
|
|
467
|
+
_fail('generation-root-signature-invalid')
|
|
468
|
+
if verified_approval_id != approval_id:
|
|
469
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
470
|
+
else:
|
|
471
|
+
_fail('generation-root-registry-invalid')
|
|
472
|
+
by_id[request_id] = request
|
|
473
|
+
validated[request_id] = {'intent': intent, 'trust': trust,
|
|
474
|
+
'configuration': configuration, 'payload': payload,
|
|
475
|
+
'envelopeDigest': envelope_digest}
|
|
476
|
+
if reserved != sorted(reserved) or len(set(reserved)) != len(reserved):
|
|
477
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
478
|
+
if len(set(confirmed)) != len(confirmed):
|
|
479
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
480
|
+
if sequence != len(requests) + len(enrollments):
|
|
481
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
482
|
+
if sorted(reserved + confirmed) != list(range(1, sequence + 1)):
|
|
483
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
484
|
+
enrollment_sequences: list[int] = []
|
|
485
|
+
seen_requests: set[str] = set()
|
|
486
|
+
for item in enrollments:
|
|
487
|
+
_closed(item, {'profile', 'enrollmentId', 'requestId', 'contextId',
|
|
488
|
+
'bootstrapEnrollmentId', 'rootPolicyDigest', 'rootApprovalDigest',
|
|
489
|
+
'trust', 'configuration', 'configurationDigest',
|
|
490
|
+
'nativeEvidenceDigest', 'state', 'registrySequence'},
|
|
491
|
+
'generation-root-registry-invalid')
|
|
492
|
+
if item['profile'] != ROOT_ENROLLMENT_PROFILE or item['state'] != 'confirmed':
|
|
493
|
+
_fail('generation-root-registry-invalid')
|
|
494
|
+
request_id = _uuid(item['requestId'])
|
|
495
|
+
if request_id in seen_requests or request_id not in by_id:
|
|
496
|
+
_fail('generation-root-registry-invalid')
|
|
497
|
+
seen_requests.add(request_id)
|
|
498
|
+
request = by_id[request_id]
|
|
499
|
+
info = validated[request_id]
|
|
500
|
+
if (request['state'] != 'confirmed'
|
|
501
|
+
or item['enrollmentId'] != request['enrollmentId']
|
|
502
|
+
or item['contextId'] != request['contextId']
|
|
503
|
+
or item['bootstrapEnrollmentId'] != bootstrap_id
|
|
504
|
+
or item['bootstrapEnrollmentId'] != request['effectKey'][1]
|
|
505
|
+
or item['rootPolicyDigest'] != info['payload']['rootPolicyDigest']
|
|
506
|
+
or item['rootApprovalDigest'] != info['envelopeDigest']
|
|
507
|
+
or not _root_same_json(item['trust'], info['trust'])
|
|
508
|
+
or not _root_same_json(item['configuration'], info['configuration'])
|
|
509
|
+
or item['configurationDigest'] != info['intent']['configurationDigest']
|
|
510
|
+
or item['nativeEvidenceDigest'] != info['intent']['nativeEvidenceDigest']):
|
|
511
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
512
|
+
seq = item['registrySequence']
|
|
513
|
+
if type(seq) is not int or seq != request['confirmedSequence']:
|
|
514
|
+
_fail('generation-root-registry-sequence-invalid')
|
|
515
|
+
enrollment_sequences.append(seq)
|
|
516
|
+
for field in ('rootPolicyDigest', 'rootApprovalDigest', 'configurationDigest',
|
|
517
|
+
'nativeEvidenceDigest'):
|
|
518
|
+
_digest(item[field])
|
|
519
|
+
if (enrollment_sequences != sorted(enrollment_sequences)
|
|
520
|
+
or len(seen_requests) != len(enrollments)
|
|
521
|
+
or {r['requestId'] for r in requests if r['state'] == 'confirmed'} != seen_requests):
|
|
522
|
+
_fail('generation-root-registry-crosslink-invalid')
|
|
523
|
+
return value
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _verify_trust_observation(entry: OriginalGenerationTrustEnrollment,
|
|
527
|
+
current: object) -> None:
|
|
528
|
+
statement = _parse_canonical(entry._statement_bytes)
|
|
529
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
530
|
+
fields = {'profile', 'statementDigest', 'configurationDigest',
|
|
531
|
+
'ownerBootstrapContextDigest', 'targetCustodyDigest',
|
|
532
|
+
'storeCreationReceiptDigest', 'custodySequence', 'supervisorId',
|
|
533
|
+
'custodianId', 'providerId', 'installationId', 'targetCustody'}
|
|
534
|
+
if type(current) is not dict or set(current) != fields:
|
|
535
|
+
_logical_fail('generation-authority-original-trust-unverified')
|
|
536
|
+
expected = {
|
|
537
|
+
'profile': 'umf.generation-authority-native-trust-observation/0.1',
|
|
538
|
+
'statementDigest': _sha(entry._statement_bytes),
|
|
539
|
+
'configurationDigest': _sha(entry._configuration_bytes),
|
|
540
|
+
'ownerBootstrapContextDigest': statement['ownerBootstrapContextDigest'],
|
|
541
|
+
'targetCustodyDigest': _sha(_canonical(config['targetCustody'])),
|
|
542
|
+
'storeCreationReceiptDigest': statement['storeCreationReceiptDigest'],
|
|
543
|
+
'custodySequence': statement['custodySequence'],
|
|
544
|
+
'supervisorId': config['supervisorId'], 'custodianId': config['custodianId'],
|
|
545
|
+
'providerId': config['providerId'], 'installationId': config['installationId'],
|
|
546
|
+
'targetCustody': config['targetCustody'],
|
|
547
|
+
}
|
|
548
|
+
if _canonical(current) != _canonical(expected):
|
|
549
|
+
_logical_fail('generation-authority-original-trust-unverified')
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _validate_context_projection(projection: object) -> dict[str, Any]:
|
|
553
|
+
if type(projection) is not dict:
|
|
554
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
555
|
+
base = {'profile','contextId','trustEnrollmentDigest','configurationDigest',
|
|
556
|
+
'supervisorId','custodianId','providerId','installationId',
|
|
557
|
+
'targetCustodyDigest','storeCreationReceiptDigest','purpose'}
|
|
558
|
+
if set(projection) == base | {'sourceTestOnly'}:
|
|
559
|
+
if projection['sourceTestOnly'] is not True:
|
|
560
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
561
|
+
elif set(projection) != base:
|
|
562
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
563
|
+
if projection['profile'] != CONTEXT_PROFILE:
|
|
564
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
565
|
+
_uuid(projection['contextId'])
|
|
566
|
+
for field in ('trustEnrollmentDigest','configurationDigest',
|
|
567
|
+
'targetCustodyDigest','storeCreationReceiptDigest'):
|
|
568
|
+
_digest(projection[field])
|
|
569
|
+
for field in ('supervisorId','custodianId','providerId'):
|
|
570
|
+
_uuid(projection[field])
|
|
571
|
+
_text(projection['installationId'], 256)
|
|
572
|
+
if projection['purpose'] not in PURPOSES:
|
|
573
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
574
|
+
return projection
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _context_replay(events: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
|
578
|
+
contexts: dict[str, dict[str, Any]] = {}
|
|
579
|
+
for event in events:
|
|
580
|
+
payload = event['payload']
|
|
581
|
+
if event['kind'] == 'context-birth-intent':
|
|
582
|
+
projection = payload['projection']
|
|
583
|
+
context_id = projection['contextId']
|
|
584
|
+
contexts[context_id] = {
|
|
585
|
+
**payload, 'contextId': context_id, 'intentDigest': event['digest'],
|
|
586
|
+
'confirmed': False, 'ledgerBirthDigest': None,
|
|
587
|
+
}
|
|
588
|
+
else:
|
|
589
|
+
state = contexts.get(payload['contextId'])
|
|
590
|
+
if (state is None or state['confirmed']
|
|
591
|
+
or state['intentDigest'] != payload['intentDigest']):
|
|
592
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
593
|
+
state['confirmed'] = True
|
|
594
|
+
state['ledgerBirthDigest'] = payload['ledgerBirthDigest']
|
|
595
|
+
return contexts
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _context_identity(journal: _ContextJournal, context_id: str) -> tuple[str, str]:
|
|
599
|
+
state = journal.context_for(context_id)
|
|
600
|
+
if state is None or not state['confirmed']:
|
|
601
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
602
|
+
return state['logicalEnrollmentId'], state['initialEpoch']
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _verify_durable_context(journal: _ContextJournal,
|
|
606
|
+
entry: OriginalGenerationTrustEnrollment,
|
|
607
|
+
projection: dict[str, Any]) -> dict[str, Any]:
|
|
608
|
+
state = journal.context_for(projection['contextId'])
|
|
609
|
+
if (state is None or not state['confirmed'] or state['projection'] != projection
|
|
610
|
+
or state['trustEntryDigest'] != _sha(entry._statement_bytes)
|
|
611
|
+
or state['configurationDigest'] != _sha(entry._configuration_bytes)):
|
|
612
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
613
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
614
|
+
ledger = _Ledger(entry._ledger_path, config['authorityId'],
|
|
615
|
+
_sha(entry._configuration_bytes), _sha(_canonical(projection)),
|
|
616
|
+
config['purpose'])
|
|
617
|
+
records = ledger.events(create=False)
|
|
618
|
+
identities = [record for record in records if record['kind'] == 'identity-allocated']
|
|
619
|
+
if (len(identities) != 1 or identities[0]['payload'] != {
|
|
620
|
+
'enrollmentId': state['logicalEnrollmentId'],
|
|
621
|
+
'initialEpoch': state['initialEpoch']}
|
|
622
|
+
or identities[0]['digest'] != state['ledgerBirthDigest']):
|
|
623
|
+
_logical_fail('generation-authority-original-history-missing')
|
|
624
|
+
return state
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
class OriginalGenerationTrustEnrollment(_ImmutableOpaque):
|
|
628
|
+
"""Opaque original host-registry entry; never construct from a projection."""
|
|
629
|
+
|
|
630
|
+
__slots__ = (
|
|
631
|
+
'_configuration_bytes',
|
|
632
|
+
'_custodian',
|
|
633
|
+
'_entry_id',
|
|
634
|
+
'_ingress_store',
|
|
635
|
+
'_issuer',
|
|
636
|
+
'_ledger_path',
|
|
637
|
+
'_statement_bytes',
|
|
638
|
+
'_supervisor',
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
def __init__(self, seal: object, issuer: object, *, statement_bytes: bytes,
|
|
642
|
+
configuration_bytes: bytes, supervisor: object, custodian: object,
|
|
643
|
+
ingress_store: object, ledger_path: Path, entry_id: str):
|
|
644
|
+
if seal is not _TRUST_SEAL:
|
|
645
|
+
raise TypeError('original generation trust enrollment is issuer-created')
|
|
646
|
+
self._issuer = issuer
|
|
647
|
+
self._statement_bytes = bytes(statement_bytes)
|
|
648
|
+
self._configuration_bytes = bytes(configuration_bytes)
|
|
649
|
+
self._supervisor = supervisor
|
|
650
|
+
self._custodian = custodian
|
|
651
|
+
self._ingress_store = ingress_store
|
|
652
|
+
self._ledger_path = ledger_path
|
|
653
|
+
self._entry_id = entry_id
|
|
654
|
+
|
|
655
|
+
def __reduce_ex__(self, _protocol: int):
|
|
656
|
+
raise TypeError('original generation trust enrollment is not serializable')
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
class GenerationEnrollmentAuthorityContext(_ImmutableOpaque):
|
|
660
|
+
"""Opaque logical-authority context bound to original physical handles."""
|
|
661
|
+
|
|
662
|
+
__slots__ = (
|
|
663
|
+
'_configuration_bytes',
|
|
664
|
+
'_custodian',
|
|
665
|
+
'_ingress_store',
|
|
666
|
+
'_initial_epoch',
|
|
667
|
+
'_issuer',
|
|
668
|
+
'_ledger_path',
|
|
669
|
+
'_logical_enrollment_id',
|
|
670
|
+
'_projection_bytes',
|
|
671
|
+
'_supervisor',
|
|
672
|
+
'_trust',
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
def __init__(self, seal: object, issuer: object, trust: OriginalGenerationTrustEnrollment,
|
|
676
|
+
projection_bytes: bytes, logical_enrollment_id: str,
|
|
677
|
+
initial_epoch: str):
|
|
678
|
+
if seal is not _CONTEXT_SEAL:
|
|
679
|
+
raise TypeError('generation authority context is issuer-created')
|
|
680
|
+
self._issuer = issuer
|
|
681
|
+
self._trust = trust
|
|
682
|
+
self._projection_bytes = bytes(projection_bytes)
|
|
683
|
+
self._configuration_bytes = bytes(trust._configuration_bytes)
|
|
684
|
+
self._supervisor = trust._supervisor
|
|
685
|
+
self._custodian = trust._custodian
|
|
686
|
+
self._ingress_store = trust._ingress_store
|
|
687
|
+
self._ledger_path = trust._ledger_path
|
|
688
|
+
self._logical_enrollment_id = _uuid(logical_enrollment_id)
|
|
689
|
+
self._initial_epoch = _uuid(initial_epoch)
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def public_reference(self) -> dict[str, Any]:
|
|
693
|
+
return _parse_canonical(self._projection_bytes)
|
|
694
|
+
|
|
695
|
+
def __reduce_ex__(self, _protocol: int):
|
|
696
|
+
raise TypeError('generation authority context is not serializable')
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
class _GenerationTrustIssuer:
|
|
700
|
+
"""Native-free issuer state; the fixed session layer performs native checks."""
|
|
701
|
+
|
|
702
|
+
__slots__ = (
|
|
703
|
+
'_contexts',
|
|
704
|
+
'_custodian',
|
|
705
|
+
'_entries',
|
|
706
|
+
'_ingress_store',
|
|
707
|
+
'_lock',
|
|
708
|
+
'_registry',
|
|
709
|
+
'_registry_id',
|
|
710
|
+
'_registry_path',
|
|
711
|
+
'_supervisor',
|
|
712
|
+
)
|
|
713
|
+
|
|
714
|
+
def __init__(self, seal: object, *, registry_id: str, registry: object,
|
|
715
|
+
supervisor: object, custodian: object, ingress_store: object,
|
|
716
|
+
registry_path: Path):
|
|
717
|
+
if seal is not _TRUST_SEAL:
|
|
718
|
+
raise TypeError('generation trust issuer is original-bootstrap-only')
|
|
719
|
+
self._registry_id = _uuid(registry_id)
|
|
720
|
+
self._registry = registry
|
|
721
|
+
self._supervisor = supervisor
|
|
722
|
+
self._custodian = custodian
|
|
723
|
+
self._ingress_store = ingress_store
|
|
724
|
+
self._registry_path = registry_path
|
|
725
|
+
self._entries: dict[str, OriginalGenerationTrustEnrollment] = {}
|
|
726
|
+
self._contexts: dict[str, GenerationEnrollmentAuthorityContext] = {}
|
|
727
|
+
self._lock = threading.RLock()
|
|
728
|
+
|
|
729
|
+
def _issue_original_trust_entry(self, *_args: object, **_kwargs: object
|
|
730
|
+
) -> OriginalGenerationTrustEnrollment:
|
|
731
|
+
"""Production trust entries must be resolved from the real host registry."""
|
|
732
|
+
_logical_fail('generation-authority-native-bootstrap-unavailable')
|
|
733
|
+
|
|
734
|
+
def _enroll_registered_context(
|
|
735
|
+
self, entry: OriginalGenerationTrustEnrollment
|
|
736
|
+
) -> GenerationEnrollmentAuthorityContext:
|
|
737
|
+
"""Persist logical birth for the exact native-registered original entry.
|
|
738
|
+
|
|
739
|
+
The caller is the fixed session layer. This method accepts the original
|
|
740
|
+
opaque entry, never an observation mapping or caller-supplied resolver.
|
|
741
|
+
"""
|
|
742
|
+
_require_registered_issuer(self, 'production')
|
|
743
|
+
if (type(entry) is not OriginalGenerationTrustEnrollment
|
|
744
|
+
or entry._issuer is not self or self._entries.get(entry._entry_id) is not entry
|
|
745
|
+
or entry._supervisor is not self._supervisor
|
|
746
|
+
or entry._custodian is not self._custodian
|
|
747
|
+
or entry._ingress_store is not self._ingress_store):
|
|
748
|
+
_logical_fail('generation-authority-original-trust-required')
|
|
749
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
750
|
+
statement = _parse_canonical(entry._statement_bytes)
|
|
751
|
+
config, _keys = _config(config)
|
|
752
|
+
context_id = statement['enrollmentId']
|
|
753
|
+
projection = {
|
|
754
|
+
'profile': CONTEXT_PROFILE, 'contextId': context_id,
|
|
755
|
+
'trustEnrollmentDigest': _sha(entry._statement_bytes),
|
|
756
|
+
'configurationDigest': _sha(entry._configuration_bytes),
|
|
757
|
+
'supervisorId': config['supervisorId'], 'custodianId': config['custodianId'],
|
|
758
|
+
'providerId': config['providerId'], 'installationId': config['installationId'],
|
|
759
|
+
'targetCustodyDigest': _sha(_canonical(config['targetCustody'])),
|
|
760
|
+
'storeCreationReceiptDigest': statement['storeCreationReceiptDigest'],
|
|
761
|
+
'purpose': config['purpose'],
|
|
762
|
+
}
|
|
763
|
+
projection_bytes = _canonical(projection)
|
|
764
|
+
existing = self._contexts.get(context_id)
|
|
765
|
+
if existing is not None:
|
|
766
|
+
if existing._projection_bytes != projection_bytes or existing._trust is not entry:
|
|
767
|
+
_logical_fail('generation-authority-context-rebound')
|
|
768
|
+
_verify_durable_context(
|
|
769
|
+
_ContextJournal(self._registry_path, self._registry_id), entry, projection)
|
|
770
|
+
return existing
|
|
771
|
+
registry = _ContextJournal(self._registry_path, self._registry_id)
|
|
772
|
+
ledger = _Ledger(entry._ledger_path, config['authorityId'],
|
|
773
|
+
_sha(entry._configuration_bytes), _sha(projection_bytes),
|
|
774
|
+
config['purpose'])
|
|
775
|
+
logical_enrollment_id, initial_epoch = registry.reserve_context(projection, entry, ledger)
|
|
776
|
+
context = GenerationEnrollmentAuthorityContext(
|
|
777
|
+
_CONTEXT_SEAL, self, entry, projection_bytes,
|
|
778
|
+
logical_enrollment_id, initial_epoch)
|
|
779
|
+
self._contexts[context_id] = context
|
|
780
|
+
return context
|
|
781
|
+
|
|
782
|
+
def resolve_generation_authority_context(
|
|
783
|
+
self, handle: object) -> GenerationEnrollmentAuthorityContext:
|
|
784
|
+
_require_registered_issuer(self, 'production')
|
|
785
|
+
if (type(handle) is not GenerationEnrollmentAuthorityContext
|
|
786
|
+
or handle._issuer is not self
|
|
787
|
+
or self._contexts.get(handle.public_reference['contextId']) is not handle):
|
|
788
|
+
_logical_fail('generation-authority-context-unverified')
|
|
789
|
+
entry = handle._trust
|
|
790
|
+
if self._entries.get(entry._entry_id) is not entry:
|
|
791
|
+
_logical_fail('generation-authority-context-unverified')
|
|
792
|
+
_verify_durable_context(
|
|
793
|
+
_ContextJournal(self._registry_path, self._registry_id), entry,
|
|
794
|
+
handle.public_reference)
|
|
795
|
+
return handle
|
|
796
|
+
|
|
797
|
+
def _recover_registered_context(
|
|
798
|
+
self, context_id: str, entry: OriginalGenerationTrustEnrollment
|
|
799
|
+
) -> GenerationEnrollmentAuthorityContext:
|
|
800
|
+
_require_registered_issuer(self, 'production')
|
|
801
|
+
context_id = _uuid(context_id)
|
|
802
|
+
existing = self._contexts.get(context_id)
|
|
803
|
+
if existing is None:
|
|
804
|
+
# Read-only: do not create context journal/lock and do not enroll anew.
|
|
805
|
+
projection = _ContextJournal(self._registry_path, self._registry_id).find(context_id)
|
|
806
|
+
if projection is None:
|
|
807
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
808
|
+
if (type(entry) is not OriginalGenerationTrustEnrollment or entry._issuer is not self
|
|
809
|
+
or self._entries.get(entry._entry_id) is not entry
|
|
810
|
+
or entry._supervisor is not self._supervisor
|
|
811
|
+
or entry._custodian is not self._custodian
|
|
812
|
+
or entry._ingress_store is not self._ingress_store):
|
|
813
|
+
_logical_fail('generation-authority-original-trust-required')
|
|
814
|
+
if existing is not None:
|
|
815
|
+
self.resolve_generation_authority_context(existing)
|
|
816
|
+
if existing._trust is not entry:
|
|
817
|
+
_logical_fail('generation-authority-context-rebound')
|
|
818
|
+
return existing
|
|
819
|
+
journal = _ContextJournal(self._registry_path, self._registry_id)
|
|
820
|
+
expected = journal.projection_for(context_id)
|
|
821
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
822
|
+
statement = _parse_canonical(entry._statement_bytes)
|
|
823
|
+
config, _ = _config(config)
|
|
824
|
+
projection = {
|
|
825
|
+
'profile': CONTEXT_PROFILE, 'contextId': context_id,
|
|
826
|
+
'trustEnrollmentDigest': _sha(entry._statement_bytes),
|
|
827
|
+
'configurationDigest': _sha(entry._configuration_bytes),
|
|
828
|
+
'supervisorId': config['supervisorId'], 'custodianId': config['custodianId'],
|
|
829
|
+
'providerId': config['providerId'], 'installationId': config['installationId'],
|
|
830
|
+
'targetCustodyDigest': _sha(_canonical(config['targetCustody'])),
|
|
831
|
+
'storeCreationReceiptDigest': statement['storeCreationReceiptDigest'],
|
|
832
|
+
'purpose': config['purpose'],
|
|
833
|
+
}
|
|
834
|
+
if expected != projection:
|
|
835
|
+
_logical_fail('generation-authority-context-rebound')
|
|
836
|
+
_verify_durable_context(journal, entry, projection)
|
|
837
|
+
logical_enrollment_id, initial_epoch = _context_identity(journal, context_id)
|
|
838
|
+
context = GenerationEnrollmentAuthorityContext(
|
|
839
|
+
_CONTEXT_SEAL, self, entry, _canonical(projection),
|
|
840
|
+
logical_enrollment_id, initial_epoch)
|
|
841
|
+
self._contexts[context_id] = context
|
|
842
|
+
return context
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _register_trust_issuer(issuer: object, origin: str) -> None:
|
|
846
|
+
"""Record an issuer only at a fixed bootstrap factory boundary."""
|
|
847
|
+
if origin == 'production':
|
|
848
|
+
issuer_type = _GenerationTrustIssuer
|
|
849
|
+
elif origin == 'source-test':
|
|
850
|
+
issuer_type = _SourceTestGenerationTrustIssuer
|
|
851
|
+
else:
|
|
852
|
+
_logical_fail('generation-authority-context-unverified')
|
|
853
|
+
if type(issuer) is not issuer_type:
|
|
854
|
+
_logical_fail('generation-authority-context-unverified')
|
|
855
|
+
_TRUST_ISSUER_ORIGINS[id(issuer)] = (
|
|
856
|
+
issuer, origin, issuer_type.resolve_generation_authority_context,
|
|
857
|
+
getattr(issuer_type, '_projection', None))
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def _require_registered_issuer(issuer: object, expected_origin: str) -> str:
|
|
861
|
+
entry = _TRUST_ISSUER_ORIGINS.get(id(issuer))
|
|
862
|
+
if entry is None or entry[0] is not issuer or entry[1] != expected_origin:
|
|
863
|
+
_logical_fail('generation-authority-context-unverified')
|
|
864
|
+
expected_type = (_SourceTestGenerationTrustIssuer if expected_origin == 'source-test'
|
|
865
|
+
else _GenerationTrustIssuer)
|
|
866
|
+
if type(issuer) is not expected_type:
|
|
867
|
+
_logical_fail('generation-authority-context-unverified')
|
|
868
|
+
resolver = expected_type.resolve_generation_authority_context
|
|
869
|
+
projection = getattr(expected_type, '_projection', None)
|
|
870
|
+
if resolver is not entry[2] or projection is not entry[3]:
|
|
871
|
+
_logical_fail('generation-authority-context-unverified')
|
|
872
|
+
return expected_origin
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def _check_issuer_purpose(origin: str, projection: dict[str, Any], purpose: str) -> None:
|
|
876
|
+
if origin == 'source-test':
|
|
877
|
+
if projection.get('sourceTestOnly') is not True or purpose != 'native-acceptance':
|
|
878
|
+
_logical_fail('generation-authority-source-test-purpose-invalid')
|
|
879
|
+
return
|
|
880
|
+
if origin == 'production':
|
|
881
|
+
if 'sourceTestOnly' in projection or purpose not in PURPOSES:
|
|
882
|
+
_logical_fail('generation-authority-context-unverified')
|
|
883
|
+
return
|
|
884
|
+
_logical_fail('generation-authority-context-unverified')
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
class _ContextJournal:
|
|
888
|
+
"""Small durable immutable context registry under original control custody."""
|
|
889
|
+
|
|
890
|
+
__slots__ = ('_path', '_registry_id')
|
|
891
|
+
|
|
892
|
+
def __init__(self, path: Path, registry_id: str):
|
|
893
|
+
self._path = path
|
|
894
|
+
self._registry_id = registry_id
|
|
895
|
+
|
|
896
|
+
def reserve_context(self, projection: dict[str, Any], entry: OriginalGenerationTrustEnrollment,
|
|
897
|
+
ledger: _Ledger) -> tuple[str, str]:
|
|
898
|
+
# An absent registry and lock is the only fresh-birth state. A partial
|
|
899
|
+
# or previously existing pair is evidence of interruption or loss and
|
|
900
|
+
# is never silently replaced.
|
|
901
|
+
context_id = projection['contextId']
|
|
902
|
+
marker_path = self._birth_marker_path(context_id)
|
|
903
|
+
fresh = not self._path.exists() and not self._path.with_name(self._path.name + '.lock').exists()
|
|
904
|
+
marker = self._read_birth_marker(context_id)
|
|
905
|
+
if fresh and marker is None:
|
|
906
|
+
ledger_lock = ledger.path.with_name(ledger.path.name + '.lock')
|
|
907
|
+
if ledger.path.exists() or ledger_lock.exists():
|
|
908
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
909
|
+
marker = self._write_birth_marker(
|
|
910
|
+
context_id, projection, entry, ledger, str(uuid.uuid4()), str(uuid.uuid4()),
|
|
911
|
+
'pending', create=True)
|
|
912
|
+
if marker is None:
|
|
913
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
914
|
+
if (marker['projection'] != projection
|
|
915
|
+
or marker['trustEntryDigest'] != _sha(entry._statement_bytes)
|
|
916
|
+
or marker['configurationDigest'] != _sha(entry._configuration_bytes)
|
|
917
|
+
or marker['ledgerPath'] != str(ledger.path)):
|
|
918
|
+
_logical_fail('generation-authority-context-rebound')
|
|
919
|
+
if fresh and marker['state'] != 'pending':
|
|
920
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
921
|
+
if not self._path.exists() and marker['state'] != 'pending':
|
|
922
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
923
|
+
create_registry = fresh or (not self._path.exists() and marker['state'] == 'pending')
|
|
924
|
+
with self._locked(create=create_registry, exclusive=True):
|
|
925
|
+
events = self._load_locked(create=create_registry)
|
|
926
|
+
context_id = projection['contextId']
|
|
927
|
+
binding = {'projection': projection, 'trustEntryDigest': _sha(entry._statement_bytes),
|
|
928
|
+
'configurationDigest': _sha(entry._configuration_bytes),
|
|
929
|
+
'ownerBootstrapContextDigest': _parse_canonical(entry._statement_bytes)[
|
|
930
|
+
'ownerBootstrapContextDigest']}
|
|
931
|
+
context_state = _context_replay(events)
|
|
932
|
+
prior = context_state.get(context_id)
|
|
933
|
+
if prior is not None:
|
|
934
|
+
if any(prior[key] != value for key, value in binding.items()):
|
|
935
|
+
_logical_fail('generation-authority-context-rebound')
|
|
936
|
+
logical_id, epoch = prior['logicalEnrollmentId'], prior['initialEpoch']
|
|
937
|
+
if (logical_id != marker['logicalEnrollmentId']
|
|
938
|
+
or epoch != marker['initialEpoch']):
|
|
939
|
+
_logical_fail('generation-authority-context-rebound')
|
|
940
|
+
if prior['confirmed']:
|
|
941
|
+
records = ledger.events(create=False)
|
|
942
|
+
identity_events = [record for record in records
|
|
943
|
+
if record['kind'] == 'identity-allocated']
|
|
944
|
+
if (len(identity_events) != 1
|
|
945
|
+
or identity_events[0]['payload'] != {'enrollmentId': logical_id,
|
|
946
|
+
'initialEpoch': epoch}
|
|
947
|
+
or identity_events[0]['digest'] != prior['ledgerBirthDigest']):
|
|
948
|
+
_logical_fail('generation-authority-original-history-missing')
|
|
949
|
+
if marker['state'] != 'confirmed':
|
|
950
|
+
self._set_birth_state(marker_path, marker, 'confirmed')
|
|
951
|
+
return logical_id, epoch
|
|
952
|
+
else:
|
|
953
|
+
logical_id, epoch = marker['logicalEnrollmentId'], marker['initialEpoch']
|
|
954
|
+
intent = {**binding, 'logicalEnrollmentId': logical_id,
|
|
955
|
+
'initialEpoch': epoch, 'ledgerPath': str(ledger.path)}
|
|
956
|
+
intent_record = self._append_event(events, 'context-birth-intent', intent)
|
|
957
|
+
events.append(intent_record)
|
|
958
|
+
# A pending intent authorizes settling only these exact IDs.
|
|
959
|
+
prior = {**intent, 'contextId': context_id,
|
|
960
|
+
'intentDigest': intent_record['digest'], 'confirmed': False,
|
|
961
|
+
'ledgerBirthDigest': None}
|
|
962
|
+
|
|
963
|
+
if prior['ledgerPath'] != str(ledger.path):
|
|
964
|
+
_logical_fail('generation-authority-context-rebound')
|
|
965
|
+
# A pending intent may complete the same ledger birth after a
|
|
966
|
+
# crash. No replacement identity or context can be allocated.
|
|
967
|
+
ledger._initialize_identity(logical_id, epoch)
|
|
968
|
+
records = ledger.events(create=False)
|
|
969
|
+
identity_event = next((record for record in records
|
|
970
|
+
if record['kind'] == 'identity-allocated'), None)
|
|
971
|
+
if (identity_event is None or identity_event['payload'] != {
|
|
972
|
+
'enrollmentId': logical_id, 'initialEpoch': epoch}):
|
|
973
|
+
_logical_fail('generation-authority-original-history-missing')
|
|
974
|
+
if marker['state'] == 'pending':
|
|
975
|
+
marker = self._set_birth_state(marker_path, marker, 'confirming')
|
|
976
|
+
confirm = {'contextId': context_id, 'intentDigest': prior['intentDigest'],
|
|
977
|
+
'ledgerBirthDigest': identity_event['digest']}
|
|
978
|
+
self._append_event(events, 'context-birth-confirmed', confirm)
|
|
979
|
+
self._set_birth_state(marker_path, marker, 'confirmed')
|
|
980
|
+
return logical_id, epoch
|
|
981
|
+
|
|
982
|
+
def _birth_marker_path(self, context_id: str) -> Path:
|
|
983
|
+
return self._path.with_name(self._path.name + '.birth-' + _uuid(context_id))
|
|
984
|
+
|
|
985
|
+
def _read_birth_marker(self, context_id: str) -> dict[str, Any] | None:
|
|
986
|
+
path = self._birth_marker_path(context_id)
|
|
987
|
+
try:
|
|
988
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
|
989
|
+
except FileNotFoundError:
|
|
990
|
+
return None
|
|
991
|
+
except OSError:
|
|
992
|
+
_logical_fail('generation-authority-registry-unavailable')
|
|
993
|
+
try:
|
|
994
|
+
st = os.fstat(fd)
|
|
995
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
996
|
+
or st.st_nlink != 1 or st.st_mode & 0o077 or st.st_size > _MAX_REQUEST):
|
|
997
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
998
|
+
data = os.read(fd, _MAX_REQUEST + 1)
|
|
999
|
+
finally:
|
|
1000
|
+
os.close(fd)
|
|
1001
|
+
marker = _parse_canonical(data)
|
|
1002
|
+
_closed(marker, {'profile','registryId','contextId','projection','trustEntryDigest',
|
|
1003
|
+
'configurationDigest','ownerBootstrapContextDigest','ledgerPath',
|
|
1004
|
+
'logicalEnrollmentId','initialEpoch','state'},
|
|
1005
|
+
'generation-authority-registry-corrupt')
|
|
1006
|
+
if (marker['profile'] != 'umf.generation-authority-context-birth/0.1'
|
|
1007
|
+
or marker['registryId'] != self._registry_id
|
|
1008
|
+
or marker['contextId'] != context_id
|
|
1009
|
+
or marker['state'] not in ('pending','confirming','confirmed')):
|
|
1010
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1011
|
+
_validate_context_projection(marker['projection'])
|
|
1012
|
+
for field in ('trustEntryDigest','configurationDigest','ownerBootstrapContextDigest'):
|
|
1013
|
+
_digest(marker[field])
|
|
1014
|
+
_text(marker['ledgerPath'], 4096)
|
|
1015
|
+
_uuid(marker['logicalEnrollmentId']); _uuid(marker['initialEpoch'])
|
|
1016
|
+
return marker
|
|
1017
|
+
|
|
1018
|
+
def _write_birth_marker(self, context_id: str, projection: dict[str, Any],
|
|
1019
|
+
entry: OriginalGenerationTrustEnrollment, ledger: _Ledger,
|
|
1020
|
+
logical_id: str, epoch: str, state: str, *,
|
|
1021
|
+
create: bool = False) -> dict[str, Any]:
|
|
1022
|
+
statement = _parse_canonical(entry._statement_bytes)
|
|
1023
|
+
marker = {'profile':'umf.generation-authority-context-birth/0.1',
|
|
1024
|
+
'registryId':self._registry_id,'contextId':context_id,
|
|
1025
|
+
'projection':projection,'trustEntryDigest':_sha(entry._statement_bytes),
|
|
1026
|
+
'configurationDigest':_sha(entry._configuration_bytes),
|
|
1027
|
+
'ownerBootstrapContextDigest':statement['ownerBootstrapContextDigest'],
|
|
1028
|
+
'ledgerPath':str(ledger.path),'logicalEnrollmentId':logical_id,
|
|
1029
|
+
'initialEpoch':epoch,'state':state}
|
|
1030
|
+
_uuid(logical_id); _uuid(epoch)
|
|
1031
|
+
data = _canonical(marker)
|
|
1032
|
+
path = self._birth_marker_path(context_id)
|
|
1033
|
+
if not create:
|
|
1034
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1035
|
+
temp = path.with_name(path.name + '.tmp-' + str(uuid.uuid4()))
|
|
1036
|
+
try:
|
|
1037
|
+
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
1038
|
+
| getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
1039
|
+
try:
|
|
1040
|
+
view = memoryview(data)
|
|
1041
|
+
while view:
|
|
1042
|
+
written = os.write(fd, view)
|
|
1043
|
+
if written <= 0:
|
|
1044
|
+
_logical_fail('generation-authority-registry-write-failed')
|
|
1045
|
+
view = view[written:]
|
|
1046
|
+
os.fsync(fd)
|
|
1047
|
+
finally:
|
|
1048
|
+
os.close(fd)
|
|
1049
|
+
try:
|
|
1050
|
+
os.link(temp, path, follow_symlinks=False)
|
|
1051
|
+
except FileExistsError:
|
|
1052
|
+
existing = self._read_birth_marker(context_id)
|
|
1053
|
+
if (existing is None or existing['projection'] != projection
|
|
1054
|
+
or existing['trustEntryDigest'] != marker['trustEntryDigest']
|
|
1055
|
+
or existing['configurationDigest'] != marker['configurationDigest']
|
|
1056
|
+
or existing['ledgerPath'] != marker['ledgerPath']):
|
|
1057
|
+
_logical_fail('generation-authority-context-rebound')
|
|
1058
|
+
return existing
|
|
1059
|
+
except OSError:
|
|
1060
|
+
_logical_fail('generation-authority-registry-write-failed')
|
|
1061
|
+
finally:
|
|
1062
|
+
try:
|
|
1063
|
+
temp.unlink(missing_ok=True)
|
|
1064
|
+
except OSError:
|
|
1065
|
+
pass
|
|
1066
|
+
parent_fd = os.open(self._path.parent, os.O_RDONLY)
|
|
1067
|
+
try:
|
|
1068
|
+
os.fsync(parent_fd)
|
|
1069
|
+
finally:
|
|
1070
|
+
os.close(parent_fd)
|
|
1071
|
+
return marker
|
|
1072
|
+
|
|
1073
|
+
def _set_birth_state(self, path: Path, marker: dict[str, Any], state: str
|
|
1074
|
+
) -> dict[str, Any]:
|
|
1075
|
+
allowed = {'pending': {'confirming', 'confirmed'},
|
|
1076
|
+
'confirming': {'confirmed'}, 'confirmed': {'confirmed'}}
|
|
1077
|
+
if state not in allowed.get(marker['state'], set()):
|
|
1078
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1079
|
+
updated = {**marker, 'state':state}
|
|
1080
|
+
temp = path.with_name(path.name + '.tmp-' + str(uuid.uuid4()))
|
|
1081
|
+
data = _canonical(updated)
|
|
1082
|
+
try:
|
|
1083
|
+
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
1084
|
+
| getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
1085
|
+
try:
|
|
1086
|
+
os.write(fd, data); os.fsync(fd)
|
|
1087
|
+
finally:
|
|
1088
|
+
os.close(fd)
|
|
1089
|
+
os.replace(temp, path)
|
|
1090
|
+
parent_fd = os.open(path.parent, os.O_RDONLY)
|
|
1091
|
+
try:
|
|
1092
|
+
os.fsync(parent_fd)
|
|
1093
|
+
finally:
|
|
1094
|
+
os.close(parent_fd)
|
|
1095
|
+
except OSError:
|
|
1096
|
+
try:
|
|
1097
|
+
temp.unlink(missing_ok=True)
|
|
1098
|
+
except OSError:
|
|
1099
|
+
pass
|
|
1100
|
+
_logical_fail('generation-authority-registry-write-failed')
|
|
1101
|
+
return updated
|
|
1102
|
+
|
|
1103
|
+
def _append_event(self, events: list[dict[str, Any]], kind: str,
|
|
1104
|
+
payload: dict[str, Any]) -> dict[str, Any]:
|
|
1105
|
+
record = {'profile': _CONTEXT_REGISTRY_PROFILE,
|
|
1106
|
+
'registryId': self._registry_id, 'sequence': len(events) + 1,
|
|
1107
|
+
'previousDigest': events[-1]['digest'] if events else '0' * 64,
|
|
1108
|
+
'kind': kind, 'payload': payload}
|
|
1109
|
+
record['digest'] = _sha(_canonical(record))
|
|
1110
|
+
self._append(record)
|
|
1111
|
+
return record
|
|
1112
|
+
|
|
1113
|
+
def _load(self, *, create: bool) -> list[dict[str, Any]]:
|
|
1114
|
+
with self._locked(create=create):
|
|
1115
|
+
return self._load_locked(create=create)
|
|
1116
|
+
|
|
1117
|
+
@contextmanager
|
|
1118
|
+
def _locked(self, *, create: bool, exclusive: bool = False):
|
|
1119
|
+
parent = self._path.parent
|
|
1120
|
+
try:
|
|
1121
|
+
st = parent.lstat()
|
|
1122
|
+
if (not stat.S_ISDIR(st.st_mode) or stat.S_ISLNK(st.st_mode)
|
|
1123
|
+
or st.st_uid != os.geteuid() or st.st_mode & 0o077):
|
|
1124
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
1125
|
+
except OSError:
|
|
1126
|
+
_logical_fail('generation-authority-registry-unavailable')
|
|
1127
|
+
lock_path = self._path.with_name(self._path.name + '.lock')
|
|
1128
|
+
flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0) | (os.O_CREAT if create else 0)
|
|
1129
|
+
try:
|
|
1130
|
+
lock_fd = os.open(lock_path, flags, 0o600)
|
|
1131
|
+
except OSError:
|
|
1132
|
+
_logical_fail('generation-authority-original-context-missing' if not create
|
|
1133
|
+
else 'generation-authority-registry-unavailable')
|
|
1134
|
+
try:
|
|
1135
|
+
st = os.fstat(lock_fd)
|
|
1136
|
+
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid() or st.st_nlink != 1 or st.st_mode & 0o077:
|
|
1137
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
1138
|
+
fcntl.flock(lock_fd, fcntl.LOCK_EX if create or exclusive else fcntl.LOCK_SH)
|
|
1139
|
+
yield lock_fd
|
|
1140
|
+
finally:
|
|
1141
|
+
os.close(lock_fd)
|
|
1142
|
+
|
|
1143
|
+
def _load_locked(self, *, create: bool) -> list[dict[str, Any]]:
|
|
1144
|
+
parent = self._path.parent
|
|
1145
|
+
try:
|
|
1146
|
+
try:
|
|
1147
|
+
fd = os.open(self._path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
|
1148
|
+
except FileNotFoundError:
|
|
1149
|
+
if not create:
|
|
1150
|
+
_logical_fail('generation-authority-original-context-missing')
|
|
1151
|
+
fd = os.open(self._path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
1152
|
+
| getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
1153
|
+
os.fsync(fd); os.close(fd)
|
|
1154
|
+
parent_fd = os.open(parent, os.O_RDONLY)
|
|
1155
|
+
try:
|
|
1156
|
+
os.fsync(parent_fd)
|
|
1157
|
+
finally:
|
|
1158
|
+
os.close(parent_fd)
|
|
1159
|
+
return []
|
|
1160
|
+
try:
|
|
1161
|
+
st = os.fstat(fd)
|
|
1162
|
+
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid() or st.st_nlink != 1 or st.st_mode & 0o077 or st.st_size > 1_048_576:
|
|
1163
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
1164
|
+
chunks=[]
|
|
1165
|
+
while True:
|
|
1166
|
+
data=os.read(fd,65536)
|
|
1167
|
+
if not data: break
|
|
1168
|
+
chunks.append(data)
|
|
1169
|
+
finally:
|
|
1170
|
+
os.close(fd)
|
|
1171
|
+
raw=b''.join(chunks)
|
|
1172
|
+
if not raw: return []
|
|
1173
|
+
if not raw.endswith(b'\n'):
|
|
1174
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1175
|
+
events=[]; previous='0'*64; seen_contexts:set[str]=set()
|
|
1176
|
+
for n,line in enumerate(raw.splitlines(),1):
|
|
1177
|
+
record=_parse_canonical(line)
|
|
1178
|
+
_closed(record, {'profile','registryId','sequence','previousDigest','kind',
|
|
1179
|
+
'payload','digest'},
|
|
1180
|
+
'generation-authority-registry-corrupt')
|
|
1181
|
+
digest=record.pop('digest')
|
|
1182
|
+
if (record['profile'] != _CONTEXT_REGISTRY_PROFILE
|
|
1183
|
+
or record['registryId']!=self._registry_id or record['sequence']!=n
|
|
1184
|
+
or record['previousDigest']!=previous or record['kind'] not in _CONTEXT_EVENT_KINDS
|
|
1185
|
+
or digest!=_sha(_canonical(record))):
|
|
1186
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1187
|
+
payload = record['payload']
|
|
1188
|
+
if type(payload) is not dict:
|
|
1189
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1190
|
+
if record['kind'] == 'context-birth-intent':
|
|
1191
|
+
_closed(payload, {'projection','trustEntryDigest','configurationDigest',
|
|
1192
|
+
'ownerBootstrapContextDigest','logicalEnrollmentId',
|
|
1193
|
+
'initialEpoch','ledgerPath'},
|
|
1194
|
+
'generation-authority-registry-corrupt')
|
|
1195
|
+
projection=payload['projection']
|
|
1196
|
+
_validate_context_projection(projection)
|
|
1197
|
+
context_id=_uuid(projection['contextId'])
|
|
1198
|
+
if context_id in seen_contexts:
|
|
1199
|
+
_logical_fail('generation-authority-registry-corrupt')
|
|
1200
|
+
seen_contexts.add(context_id)
|
|
1201
|
+
_uuid(payload['logicalEnrollmentId']); _uuid(payload['initialEpoch'])
|
|
1202
|
+
_text(payload['ledgerPath'], 4096)
|
|
1203
|
+
for field in ('trustEntryDigest','configurationDigest','ownerBootstrapContextDigest'):
|
|
1204
|
+
_digest(payload[field])
|
|
1205
|
+
else:
|
|
1206
|
+
_closed(payload, {'contextId','intentDigest','ledgerBirthDigest'},
|
|
1207
|
+
'generation-authority-registry-corrupt')
|
|
1208
|
+
_uuid(payload['contextId']); _digest(payload['intentDigest'])
|
|
1209
|
+
_digest(payload['ledgerBirthDigest'])
|
|
1210
|
+
record['digest']=digest; previous=digest; events.append(record)
|
|
1211
|
+
if len(events)>_MAX_RECORDS: _logical_fail('generation-authority-capacity')
|
|
1212
|
+
_context_replay(events)
|
|
1213
|
+
return events
|
|
1214
|
+
except OSError:
|
|
1215
|
+
_logical_fail('generation-authority-registry-unavailable')
|
|
1216
|
+
|
|
1217
|
+
def _append(self, record: dict[str, Any]) -> None:
|
|
1218
|
+
data = _canonical(record) + b'\n'
|
|
1219
|
+
current = self._path.stat(follow_symlinks=False)
|
|
1220
|
+
if (not stat.S_ISREG(current.st_mode) or current.st_uid != os.geteuid()
|
|
1221
|
+
or current.st_nlink != 1 or current.st_mode & 0o077
|
|
1222
|
+
or current.st_size + len(data) > 1_048_576):
|
|
1223
|
+
_logical_fail('generation-authority-registry-capacity')
|
|
1224
|
+
fd = os.open(self._path, os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0))
|
|
1225
|
+
try:
|
|
1226
|
+
st = os.fstat(fd)
|
|
1227
|
+
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid() or st.st_nlink != 1 or st.st_mode & 0o077:
|
|
1228
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
1229
|
+
view = memoryview(data)
|
|
1230
|
+
while view:
|
|
1231
|
+
written = os.write(fd, view)
|
|
1232
|
+
if written <= 0:
|
|
1233
|
+
_logical_fail('generation-authority-registry-write-failed')
|
|
1234
|
+
view = view[written:]
|
|
1235
|
+
os.fsync(fd)
|
|
1236
|
+
except OSError:
|
|
1237
|
+
_logical_fail('generation-authority-registry-write-failed')
|
|
1238
|
+
finally:
|
|
1239
|
+
os.close(fd)
|
|
1240
|
+
|
|
1241
|
+
def find(self, context_id: str) -> dict[str, Any] | None:
|
|
1242
|
+
events = self._load(create=False)
|
|
1243
|
+
state = _context_replay(events).get(context_id)
|
|
1244
|
+
return state['projection'] if state is not None and state['confirmed'] else None
|
|
1245
|
+
|
|
1246
|
+
def context_for(self, context_id: str) -> dict[str, Any] | None:
|
|
1247
|
+
_uuid(context_id)
|
|
1248
|
+
return _context_replay(self._load(create=False)).get(context_id)
|
|
1249
|
+
|
|
1250
|
+
def projection_for(self, context_id: str) -> dict[str, Any] | None:
|
|
1251
|
+
return self.find(context_id)
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
# The following source-test issuer is deliberately incapable of issuing any
|
|
1255
|
+
# native/provider capability. Production enrollment must come from the
|
|
1256
|
+
# original LocalPostgresSupervisor deployment registry, which is not yet
|
|
1257
|
+
# integrated with this module.
|
|
1258
|
+
_SOURCE_TEST_ISSUER_SEAL = object()
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
class _SourceTestGenerationTrustIssuer(_GenerationTrustIssuer):
|
|
1262
|
+
"""Test-only context issuer; never accepted for native effect binding."""
|
|
1263
|
+
|
|
1264
|
+
__slots__ = ('_source_test_only',)
|
|
1265
|
+
|
|
1266
|
+
def __init__(self, seal: object, *, registry_id: str, registry: object,
|
|
1267
|
+
supervisor: object, custodian: object, ingress_store: object,
|
|
1268
|
+
registry_path: Path):
|
|
1269
|
+
if seal is not _SOURCE_TEST_ISSUER_SEAL:
|
|
1270
|
+
raise TypeError('source-test trust issuer is test-only')
|
|
1271
|
+
super().__init__(_TRUST_SEAL, registry_id=registry_id, registry=registry,
|
|
1272
|
+
supervisor=supervisor, custodian=custodian,
|
|
1273
|
+
ingress_store=ingress_store, registry_path=registry_path)
|
|
1274
|
+
self._source_test_only = True
|
|
1275
|
+
|
|
1276
|
+
def _issue_original_trust_entry(self, statement: object, configuration: object,
|
|
1277
|
+
*, ledger_path: str | os.PathLike[str]
|
|
1278
|
+
) -> OriginalGenerationTrustEnrollment:
|
|
1279
|
+
"""Create a marked fixture enrollment only for source-level tests."""
|
|
1280
|
+
record = _json_copy(statement)
|
|
1281
|
+
config, _keys = _config(configuration)
|
|
1282
|
+
expected = {'profile', 'enrollmentId', 'ownerBootstrapContextDigest',
|
|
1283
|
+
'configurationDigest', 'supervisorId', 'custodianId', 'providerId',
|
|
1284
|
+
'installationId', 'targetCustodyDigest', 'storeCreationReceiptDigest',
|
|
1285
|
+
'custodySequence'}
|
|
1286
|
+
_closed(record, expected, 'generation-authority-trust-invalid')
|
|
1287
|
+
if (record['profile'] != TRUST_PROFILE
|
|
1288
|
+
or record['configurationDigest'] != _sha(_canonical(config))
|
|
1289
|
+
or record['supervisorId'] != config['supervisorId']
|
|
1290
|
+
or record['custodianId'] != config['custodianId']
|
|
1291
|
+
or record['providerId'] != config['providerId']
|
|
1292
|
+
or record['installationId'] != config['installationId']
|
|
1293
|
+
or record['targetCustodyDigest'] != _sha(_canonical(config['targetCustody']))):
|
|
1294
|
+
_logical_fail('generation-authority-trust-invalid')
|
|
1295
|
+
_uuid(record['enrollmentId'])
|
|
1296
|
+
for key in ('ownerBootstrapContextDigest', 'configurationDigest',
|
|
1297
|
+
'targetCustodyDigest', 'storeCreationReceiptDigest'):
|
|
1298
|
+
_digest(record[key])
|
|
1299
|
+
_uint(record['custodySequence'], 1, _MAX_SAFE_INT)
|
|
1300
|
+
path = Path(os.fspath(ledger_path))
|
|
1301
|
+
if not path.is_absolute() or os.path.normpath(str(path)) != str(path):
|
|
1302
|
+
_logical_fail('generation-authority-ledger-path-invalid')
|
|
1303
|
+
statement_bytes = _canonical(record); configuration_bytes = _canonical(config)
|
|
1304
|
+
with self._lock:
|
|
1305
|
+
prior = self._entries.get(record['enrollmentId'])
|
|
1306
|
+
if prior is not None:
|
|
1307
|
+
if (prior._statement_bytes != statement_bytes
|
|
1308
|
+
or prior._configuration_bytes != configuration_bytes
|
|
1309
|
+
or prior._ledger_path != path):
|
|
1310
|
+
_logical_fail('generation-authority-trust-rebound')
|
|
1311
|
+
return prior
|
|
1312
|
+
entry = OriginalGenerationTrustEnrollment(
|
|
1313
|
+
_TRUST_SEAL, self, statement_bytes=statement_bytes,
|
|
1314
|
+
configuration_bytes=configuration_bytes, supervisor=self._supervisor,
|
|
1315
|
+
custodian=self._custodian, ingress_store=self._ingress_store,
|
|
1316
|
+
ledger_path=path, entry_id=record['enrollmentId'])
|
|
1317
|
+
self._entries[entry._entry_id] = entry
|
|
1318
|
+
return entry
|
|
1319
|
+
|
|
1320
|
+
def enroll_generation_authority(self, original_trust_enrollment: object,
|
|
1321
|
+
original_supervisor: object, original_custodian: object,
|
|
1322
|
+
original_ingress_store: object
|
|
1323
|
+
) -> GenerationEnrollmentAuthorityContext:
|
|
1324
|
+
entry = original_trust_enrollment
|
|
1325
|
+
if (type(entry) is not OriginalGenerationTrustEnrollment
|
|
1326
|
+
or entry._issuer is not self or self._entries.get(entry._entry_id) is not entry
|
|
1327
|
+
or original_supervisor is not self._supervisor
|
|
1328
|
+
or original_custodian is not self._custodian
|
|
1329
|
+
or original_ingress_store is not self._ingress_store):
|
|
1330
|
+
_logical_fail('generation-authority-original-trust-required')
|
|
1331
|
+
projection = self._projection(entry)
|
|
1332
|
+
logical_enrollment_id, initial_epoch = self._reserve_context(entry, projection)
|
|
1333
|
+
existing = self._contexts.get(entry._entry_id)
|
|
1334
|
+
if existing is not None:
|
|
1335
|
+
return existing
|
|
1336
|
+
context = GenerationEnrollmentAuthorityContext(
|
|
1337
|
+
_CONTEXT_SEAL, self, entry, _canonical(projection),
|
|
1338
|
+
logical_enrollment_id, initial_epoch)
|
|
1339
|
+
self._contexts[entry._entry_id] = context
|
|
1340
|
+
return context
|
|
1341
|
+
|
|
1342
|
+
def resolve_generation_authority_context(
|
|
1343
|
+
self, handle: object) -> GenerationEnrollmentAuthorityContext:
|
|
1344
|
+
_require_registered_issuer(self, 'source-test')
|
|
1345
|
+
if (type(handle) is not GenerationEnrollmentAuthorityContext
|
|
1346
|
+
or handle._issuer is not self
|
|
1347
|
+
or self._contexts.get(handle._trust._entry_id) is not handle
|
|
1348
|
+
or not handle.public_reference.get('sourceTestOnly')):
|
|
1349
|
+
_logical_fail('generation-authority-context-unverified')
|
|
1350
|
+
entry = handle._trust
|
|
1351
|
+
if self._entries.get(entry._entry_id) is not entry:
|
|
1352
|
+
_logical_fail('generation-authority-context-unverified')
|
|
1353
|
+
projection = _ContextJournal(self._registry_path, self._registry_id).projection_for(
|
|
1354
|
+
entry._entry_id)
|
|
1355
|
+
if projection != handle.public_reference:
|
|
1356
|
+
_logical_fail('generation-authority-context-unverified')
|
|
1357
|
+
_verify_durable_context(
|
|
1358
|
+
_ContextJournal(self._registry_path, self._registry_id), entry, projection)
|
|
1359
|
+
return handle
|
|
1360
|
+
|
|
1361
|
+
def recover_generation_authority_context(
|
|
1362
|
+
self, context_id: str, original_trust_enrollment: object,
|
|
1363
|
+
original_supervisor: object, original_custodian: object,
|
|
1364
|
+
original_ingress_store: object) -> GenerationEnrollmentAuthorityContext:
|
|
1365
|
+
context_id = _uuid(context_id)
|
|
1366
|
+
entry = original_trust_enrollment
|
|
1367
|
+
if (type(entry) is not OriginalGenerationTrustEnrollment or entry._issuer is not self
|
|
1368
|
+
or self._entries.get(entry._entry_id) is not entry
|
|
1369
|
+
or entry._entry_id != context_id or original_supervisor is not self._supervisor
|
|
1370
|
+
or original_custodian is not self._custodian
|
|
1371
|
+
or original_ingress_store is not self._ingress_store):
|
|
1372
|
+
_logical_fail('generation-authority-original-trust-required')
|
|
1373
|
+
expected = _ContextJournal(self._registry_path, self._registry_id).projection_for(context_id)
|
|
1374
|
+
projection = self._projection(entry)
|
|
1375
|
+
if expected != projection:
|
|
1376
|
+
_logical_fail('generation-authority-context-rebound')
|
|
1377
|
+
existing = self._contexts.get(context_id)
|
|
1378
|
+
if existing is not None:
|
|
1379
|
+
return self.resolve_generation_authority_context(existing)
|
|
1380
|
+
logical_enrollment_id, initial_epoch = _context_identity(
|
|
1381
|
+
_ContextJournal(self._registry_path, self._registry_id), context_id)
|
|
1382
|
+
context = GenerationEnrollmentAuthorityContext(
|
|
1383
|
+
_CONTEXT_SEAL, self, entry, _canonical(projection),
|
|
1384
|
+
logical_enrollment_id, initial_epoch)
|
|
1385
|
+
self._contexts[context_id] = context
|
|
1386
|
+
return context
|
|
1387
|
+
|
|
1388
|
+
def _projection(self, entry: OriginalGenerationTrustEnrollment) -> dict[str, Any]:
|
|
1389
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
1390
|
+
statement = _parse_canonical(entry._statement_bytes)
|
|
1391
|
+
return {
|
|
1392
|
+
'profile': CONTEXT_PROFILE, 'contextId': entry._entry_id,
|
|
1393
|
+
'trustEnrollmentDigest': _sha(entry._statement_bytes),
|
|
1394
|
+
'configurationDigest': _sha(entry._configuration_bytes),
|
|
1395
|
+
'supervisorId': config['supervisorId'], 'custodianId': config['custodianId'],
|
|
1396
|
+
'providerId': config['providerId'], 'installationId': config['installationId'],
|
|
1397
|
+
'targetCustodyDigest': _sha(_canonical(config['targetCustody'])),
|
|
1398
|
+
'storeCreationReceiptDigest': statement['storeCreationReceiptDigest'],
|
|
1399
|
+
'purpose': config['purpose'], 'sourceTestOnly': True,
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
def _reserve_context(self, entry: OriginalGenerationTrustEnrollment,
|
|
1403
|
+
projection: dict[str, Any]) -> tuple[str, str]:
|
|
1404
|
+
# Test-only enrollment is still durable and exact; its provenance is
|
|
1405
|
+
# explicit in the projection and can never satisfy production checks.
|
|
1406
|
+
config = _parse_canonical(entry._configuration_bytes, maximum=_MAX_CONFIG)
|
|
1407
|
+
ledger = _Ledger(entry._ledger_path, config['authorityId'],
|
|
1408
|
+
_sha(entry._configuration_bytes), _sha(_canonical(projection)),
|
|
1409
|
+
config['purpose'])
|
|
1410
|
+
journal = _ContextJournal(self._registry_path, self._registry_id)
|
|
1411
|
+
return journal.reserve_context(projection, entry, ledger)
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
def _source_test_generation_trust_issuer(*, registry_id: str, registry: object,
|
|
1415
|
+
supervisor: object, custodian: object,
|
|
1416
|
+
ingress_store: object,
|
|
1417
|
+
registry_path: str | os.PathLike[str]
|
|
1418
|
+
) -> _SourceTestGenerationTrustIssuer:
|
|
1419
|
+
"""Private test fixture constructor; has no production/native authority."""
|
|
1420
|
+
path = Path(os.fspath(registry_path))
|
|
1421
|
+
if not path.is_absolute() or os.path.normpath(str(path)) != str(path):
|
|
1422
|
+
_logical_fail('generation-authority-registry-path-invalid')
|
|
1423
|
+
issuer = _SourceTestGenerationTrustIssuer(
|
|
1424
|
+
_SOURCE_TEST_ISSUER_SEAL, registry_id=registry_id, registry=registry,
|
|
1425
|
+
supervisor=supervisor, custodian=custodian, ingress_store=ingress_store,
|
|
1426
|
+
registry_path=path)
|
|
1427
|
+
_register_trust_issuer(issuer, 'source-test')
|
|
1428
|
+
return issuer
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
|
|
1433
|
+
class ConfiguredGenerationAuthorityRootVerifier:
|
|
1434
|
+
"""Exact Ed25519 verifier for the new ROOT trust signing domain."""
|
|
1435
|
+
|
|
1436
|
+
__slots__ = ('_policy', '_purpose')
|
|
1437
|
+
|
|
1438
|
+
def __init__(self, policy: dict[str, Any], *, purpose: str):
|
|
1439
|
+
self._policy = policy
|
|
1440
|
+
self._purpose = purpose
|
|
1441
|
+
|
|
1442
|
+
def verify_approval(self, payload: object, signature: object) -> str:
|
|
1443
|
+
"""Verify one policy-selected original root key; no key is caller supplied."""
|
|
1444
|
+
try:
|
|
1445
|
+
from cryptography import __version__ as crypto_version
|
|
1446
|
+
from cryptography.exceptions import InvalidSignature
|
|
1447
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
1448
|
+
Ed25519PublicKey,
|
|
1449
|
+
)
|
|
1450
|
+
except ImportError:
|
|
1451
|
+
_fail('generation-root-crypto-unavailable')
|
|
1452
|
+
if crypto_version != '50.0.2':
|
|
1453
|
+
_fail('generation-root-crypto-version-unsupported')
|
|
1454
|
+
exact = _closed(payload, {
|
|
1455
|
+
'profile', 'scope', 'rootAuthorityId', 'rootPolicyRevision', 'keyId',
|
|
1456
|
+
'principalId', 'approvalId', 'purpose', 'bootstrapEnrollmentId',
|
|
1457
|
+
'rootPolicyDigest', 'supervisorId', 'custodianId', 'providerId',
|
|
1458
|
+
'installationId', 'intentDigest'}, 'generation-root-approval-invalid')
|
|
1459
|
+
policy = _closed(self._policy, {'profile', 'authorityId', 'policyRevision', 'keys'},
|
|
1460
|
+
'generation-root-policy-invalid')
|
|
1461
|
+
if (exact['profile'] != ROOT_APPROVAL_PROFILE
|
|
1462
|
+
or exact['scope'] != 'enroll-generation-authority'
|
|
1463
|
+
or exact['rootAuthorityId'] != policy['authorityId']
|
|
1464
|
+
or exact['rootPolicyRevision'] != policy['policyRevision']
|
|
1465
|
+
or exact['purpose'] != self._purpose):
|
|
1466
|
+
_fail('generation-root-approval-invalid')
|
|
1467
|
+
selected = [item for item in policy['keys']
|
|
1468
|
+
if item.get('keyId') == exact['keyId']
|
|
1469
|
+
and item.get('principalId') == exact['principalId']]
|
|
1470
|
+
if len(selected) != 1:
|
|
1471
|
+
_fail('generation-root-key-unavailable')
|
|
1472
|
+
item = selected[0]
|
|
1473
|
+
if 'umf.configured-generation-enrollment-authority/0.1' not in item['configurationProfiles']:
|
|
1474
|
+
_fail('generation-root-profile-denied')
|
|
1475
|
+
if exact['purpose'] not in ('production', 'native-acceptance'):
|
|
1476
|
+
_fail('generation-root-purpose-denied')
|
|
1477
|
+
if (type(signature) is not str or not re.fullmatch(r'[A-Za-z0-9_-]{86}', signature)):
|
|
1478
|
+
_fail('generation-root-signature-invalid')
|
|
1479
|
+
try:
|
|
1480
|
+
raw_key = base64.urlsafe_b64decode(item['publicKey'] + '=')
|
|
1481
|
+
raw_sig = base64.urlsafe_b64decode(signature + '==')
|
|
1482
|
+
if len(raw_key) != 32 or len(raw_sig) != 64:
|
|
1483
|
+
_fail('generation-root-signature-invalid')
|
|
1484
|
+
message = (ROOT_APPROVAL_PROFILE.encode('ascii') + b'\x00'
|
|
1485
|
+
+ _canonical(exact))
|
|
1486
|
+
Ed25519PublicKey.from_public_bytes(raw_key).verify(raw_sig, message)
|
|
1487
|
+
except InvalidSignature:
|
|
1488
|
+
_fail('generation-root-signature-invalid')
|
|
1489
|
+
except (ValueError, TypeError):
|
|
1490
|
+
_fail('generation-root-signature-invalid')
|
|
1491
|
+
return exact['approvalId']
|