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,1108 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Separate signed authority for existing-head initial generation enrollment.
|
|
3
|
+
|
|
4
|
+
This module owns only the logical two-scope approval domain. It does not
|
|
5
|
+
create PostgreSQL roles, epochs, fences, or public generation capabilities.
|
|
6
|
+
Those effects require the original native provider and its independently
|
|
7
|
+
qualified issuer.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import uuid
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from ..canonical import canonical_json
|
|
21
|
+
|
|
22
|
+
AUTHORITY_PROFILE = 'umf.configured-generation-enrollment-authority/0.1'
|
|
23
|
+
CONFIG_PROFILE = AUTHORITY_PROFILE
|
|
24
|
+
SOURCE_POLICY_PROFILE = 'umf.existing-head-enrollment-policy/0.1'
|
|
25
|
+
TRUST_PROFILE = 'umf.generation-authority-trust-enrollment/0.1'
|
|
26
|
+
CONTEXT_PROFILE = 'umf.generation-authority-context/0.1'
|
|
27
|
+
APPROVAL_PROFILE = 'umf.initial-generation-enrollment-approval/0.1'
|
|
28
|
+
LEDGER_PROFILE = 'umf.initial-generation-enrollment-ledger/0.1'
|
|
29
|
+
PREPARE_INTENT_PROFILE = 'umf.initial-generation-enrollment-prepare/0.1'
|
|
30
|
+
ACTIVATE_INTENT_PROFILE = 'umf.initial-generation-enrollment-activate/0.1'
|
|
31
|
+
PREPARE_SCOPE = 'prepare-initial-enrollment'
|
|
32
|
+
ACTIVATE_SCOPE = 'activate-initial-enrollment'
|
|
33
|
+
SCOPES = (PREPARE_SCOPE, ACTIVATE_SCOPE)
|
|
34
|
+
PURPOSES = ('production', 'native-acceptance')
|
|
35
|
+
SIGNING_DOMAIN = b'umf.initial-generation-enrollment-approval/0.1\x00'
|
|
36
|
+
|
|
37
|
+
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
|
|
38
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
39
|
+
_B64URL = re.compile(r'^[A-Za-z0-9_-]+$')
|
|
40
|
+
_MAX_CONFIG = 1_048_576
|
|
41
|
+
_MAX_REQUEST = 1_048_576
|
|
42
|
+
_MAX_LEDGER = 8 * 1024 * 1024
|
|
43
|
+
_MAX_RECORDS = 4096
|
|
44
|
+
_MAX_SAFE_INT = 9_007_199_254_740_991
|
|
45
|
+
_ROLE_FLAGS = ('canLogin', 'superuser', 'createDatabase', 'createRole',
|
|
46
|
+
'replication', 'bypassRls', 'inherit')
|
|
47
|
+
_EVENT_KINDS = {'identity-allocated', 'request-prepared', 'approval-verified',
|
|
48
|
+
'effect-reserved', 'effect-settled'}
|
|
49
|
+
_CONTEXT_EVENT_KINDS = {'context-birth-intent', 'context-birth-confirmed'}
|
|
50
|
+
_CONTEXT_REGISTRY_PROFILE = 'umf.generation-authority-context-registry/0.2'
|
|
51
|
+
_REQUEST_SEAL = object()
|
|
52
|
+
_APPROVAL_SEAL = object()
|
|
53
|
+
_RESERVATION_SEAL = object()
|
|
54
|
+
_OUTCOME_SEAL = object()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _ImmutableOpaque:
|
|
58
|
+
__slots__ = ()
|
|
59
|
+
|
|
60
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
61
|
+
if hasattr(self, name):
|
|
62
|
+
raise AttributeError('opaque authority values are immutable')
|
|
63
|
+
object.__setattr__(self, name, value)
|
|
64
|
+
|
|
65
|
+
def __delattr__(self, name: str) -> None:
|
|
66
|
+
raise AttributeError('opaque authority values are immutable')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _fail(code: str) -> None:
|
|
70
|
+
raise GenerationEnrollmentAuthorityError(code)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _closed(value: object, keys: set[str], code: str = 'generation-authority-invalid') -> dict[str, Any]:
|
|
74
|
+
if type(value) is not dict or set(value) != keys or any(type(key) is not str for key in value):
|
|
75
|
+
_fail(code)
|
|
76
|
+
return value
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _text(value: object, limit: int = 256) -> str:
|
|
80
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
81
|
+
_fail('generation-authority-invalid')
|
|
82
|
+
try:
|
|
83
|
+
if len(value.encode('utf-8')) > limit:
|
|
84
|
+
_fail('generation-authority-invalid')
|
|
85
|
+
except UnicodeEncodeError:
|
|
86
|
+
_fail('generation-authority-invalid')
|
|
87
|
+
return value
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _uuid(value: object) -> str:
|
|
91
|
+
if type(value) is not str or not _UUID.fullmatch(value):
|
|
92
|
+
_fail('generation-authority-invalid')
|
|
93
|
+
try:
|
|
94
|
+
if str(uuid.UUID(value)) != value:
|
|
95
|
+
_fail('generation-authority-invalid')
|
|
96
|
+
except ValueError:
|
|
97
|
+
_fail('generation-authority-invalid')
|
|
98
|
+
return value
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _digest(value: object) -> str:
|
|
102
|
+
if type(value) is not str or not _HEX.fullmatch(value):
|
|
103
|
+
_fail('generation-authority-invalid')
|
|
104
|
+
return value
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _uint(value: object, minimum: int, maximum: int) -> int:
|
|
108
|
+
if type(value) is not int or not minimum <= value <= maximum:
|
|
109
|
+
_fail('generation-authority-invalid')
|
|
110
|
+
return value
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _json_copy(value: object, *, depth: int = 0, count: list[int] | None = None) -> object:
|
|
114
|
+
if count is None:
|
|
115
|
+
count = [0]
|
|
116
|
+
count[0] += 1
|
|
117
|
+
if count[0] > 100_000 or depth > 48:
|
|
118
|
+
_fail('generation-authority-capacity')
|
|
119
|
+
if value is None or type(value) is bool:
|
|
120
|
+
return value
|
|
121
|
+
if type(value) is int:
|
|
122
|
+
if abs(value) > _MAX_SAFE_INT:
|
|
123
|
+
_fail('generation-authority-invalid')
|
|
124
|
+
return value
|
|
125
|
+
if type(value) is str:
|
|
126
|
+
_text(value, _MAX_REQUEST)
|
|
127
|
+
return value
|
|
128
|
+
if type(value) is list:
|
|
129
|
+
if len(value) > 4096:
|
|
130
|
+
_fail('generation-authority-capacity')
|
|
131
|
+
return [_json_copy(item, depth=depth + 1, count=count) for item in value]
|
|
132
|
+
if type(value) is dict:
|
|
133
|
+
if len(value) > 128 or any(type(key) is not str or not key.isascii() for key in value):
|
|
134
|
+
_fail('generation-authority-invalid')
|
|
135
|
+
return {key: _json_copy(item, depth=depth + 1, count=count)
|
|
136
|
+
for key, item in value.items()}
|
|
137
|
+
_fail('generation-authority-invalid')
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _canonical(value: object) -> bytes:
|
|
141
|
+
try:
|
|
142
|
+
copied = _json_copy(value)
|
|
143
|
+
encoded = canonical_json(copied).encode('utf-8')
|
|
144
|
+
except GenerationEnrollmentAuthorityError:
|
|
145
|
+
raise
|
|
146
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
147
|
+
_fail('generation-authority-invalid')
|
|
148
|
+
if len(encoded) > _MAX_REQUEST:
|
|
149
|
+
_fail('generation-authority-capacity')
|
|
150
|
+
return encoded
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _parse_canonical(data: object, *, maximum: int = _MAX_REQUEST) -> dict[str, Any]:
|
|
154
|
+
if type(data) is not bytes or not 1 <= len(data) <= maximum:
|
|
155
|
+
_fail('generation-authority-capacity')
|
|
156
|
+
|
|
157
|
+
def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
158
|
+
parsed: dict[str, Any] = {}
|
|
159
|
+
for key, value in items:
|
|
160
|
+
if key in parsed:
|
|
161
|
+
_fail('generation-authority-invalid')
|
|
162
|
+
parsed[key] = value
|
|
163
|
+
return parsed
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
value = json.loads(data.decode('utf-8'), object_pairs_hook=pairs,
|
|
167
|
+
parse_float=lambda _v: _fail('generation-authority-invalid'),
|
|
168
|
+
parse_constant=lambda _v: _fail('generation-authority-invalid'))
|
|
169
|
+
except GenerationEnrollmentAuthorityError:
|
|
170
|
+
raise
|
|
171
|
+
except (UnicodeError, ValueError, RecursionError):
|
|
172
|
+
_fail('generation-authority-invalid')
|
|
173
|
+
copied = _json_copy(value)
|
|
174
|
+
if type(copied) is not dict or _canonical(copied) != data:
|
|
175
|
+
_fail('generation-authority-noncanonical')
|
|
176
|
+
return copied
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _sha(data: bytes) -> str:
|
|
180
|
+
return hashlib.sha256(data).hexdigest()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _b64decode(value: object, size: int) -> bytes:
|
|
184
|
+
if type(value) is not str or not _B64URL.fullmatch(value):
|
|
185
|
+
_fail('generation-authority-signature-invalid')
|
|
186
|
+
try:
|
|
187
|
+
raw = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
|
|
188
|
+
except (ValueError, TypeError):
|
|
189
|
+
_fail('generation-authority-signature-invalid')
|
|
190
|
+
if len(raw) != size or base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=') != value:
|
|
191
|
+
_fail('generation-authority-signature-invalid')
|
|
192
|
+
return raw
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _target_custody(value: object) -> dict[str, Any]:
|
|
196
|
+
target = _closed(value, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
197
|
+
'incarnation', 'registrationDigest'})
|
|
198
|
+
if target['profile'] != 'umf.native-target-custody/0.1':
|
|
199
|
+
_fail('generation-authority-target-invalid')
|
|
200
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
201
|
+
_uuid(target[key])
|
|
202
|
+
_digest(target['registrationDigest'])
|
|
203
|
+
return target
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _name(value: object) -> str:
|
|
207
|
+
# Native role identifiers may be quoted UTF-8 names; preserve their
|
|
208
|
+
# semantics while enforcing PostgreSQL's established 63-byte bound.
|
|
209
|
+
return _text(value, 63)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _flags(value: object) -> dict[str, bool]:
|
|
213
|
+
flags = _closed(value, set(_ROLE_FLAGS))
|
|
214
|
+
if any(type(flags[key]) is not bool for key in _ROLE_FLAGS):
|
|
215
|
+
_fail('generation-authority-invalid')
|
|
216
|
+
return flags
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _membership_list(value: object) -> list[dict[str, Any]]:
|
|
220
|
+
if type(value) is not list or len(value) > 1024:
|
|
221
|
+
_fail('generation-authority-invalid')
|
|
222
|
+
result = []
|
|
223
|
+
seen_oids: set[int] = set()
|
|
224
|
+
seen_names: set[str] = set()
|
|
225
|
+
for entry in value:
|
|
226
|
+
item = _closed(entry, {'roleOid', 'roleName', 'inherit', 'set', 'admin'})
|
|
227
|
+
oid = _uint(item['roleOid'], 1, 4_294_967_295)
|
|
228
|
+
name = _name(item['roleName'])
|
|
229
|
+
if oid in seen_oids or name in seen_names:
|
|
230
|
+
_fail('generation-authority-invalid')
|
|
231
|
+
if any(type(item[key]) is not bool for key in ('inherit', 'set', 'admin')):
|
|
232
|
+
_fail('generation-authority-invalid')
|
|
233
|
+
seen_oids.add(oid); seen_names.add(name)
|
|
234
|
+
result.append({'roleOid': oid, 'roleName': name,
|
|
235
|
+
'inherit': item['inherit'], 'set': item['set'], 'admin': item['admin']})
|
|
236
|
+
return result
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _config(value: object) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
|
|
240
|
+
config = _closed(value, {'profile', 'authorityId', 'policyRevision', 'purpose',
|
|
241
|
+
'supervisorId', 'custodianId', 'providerId', 'installationId',
|
|
242
|
+
'targetCustody', 'storeId', 'sourcePolicy', 'keys'})
|
|
243
|
+
if config['profile'] != CONFIG_PROFILE or config['purpose'] not in PURPOSES:
|
|
244
|
+
_fail('generation-authority-configuration-invalid')
|
|
245
|
+
_uuid(config['authorityId']); _uuid(config['supervisorId']); _uuid(config['custodianId'])
|
|
246
|
+
_uuid(config['providerId']); _text(config['installationId'], 256)
|
|
247
|
+
_text(config['policyRevision'], 128)
|
|
248
|
+
target = _target_custody(config['targetCustody'])
|
|
249
|
+
if target['custodianId'] != config['custodianId'] or config['storeId'] != config['providerId']:
|
|
250
|
+
_fail('generation-authority-configuration-invalid')
|
|
251
|
+
policy = _closed(config['sourcePolicy'], {'profile', 'approvedCohorts', 'approvedSubjects',
|
|
252
|
+
'issuerProfile', 'maximumSubjects',
|
|
253
|
+
'allowLegacyLoginConversion'})
|
|
254
|
+
if (policy['profile'] != SOURCE_POLICY_PROFILE
|
|
255
|
+
or policy['allowLegacyLoginConversion'] is not True):
|
|
256
|
+
_fail('generation-authority-configuration-invalid')
|
|
257
|
+
maximum_subjects = _uint(policy['maximumSubjects'], 1, 256)
|
|
258
|
+
_text(policy['issuerProfile'], 256)
|
|
259
|
+
cohorts = policy['approvedCohorts']
|
|
260
|
+
if type(cohorts) is not list or not 1 <= len(cohorts) <= 256:
|
|
261
|
+
_fail('generation-authority-configuration-invalid')
|
|
262
|
+
cohort_seen: set[bytes] = set()
|
|
263
|
+
normalized_cohorts = []
|
|
264
|
+
for cohort in cohorts:
|
|
265
|
+
item = _closed(cohort, {'sourceDigest', 'bundleDigest', 'sourceCohortDigest',
|
|
266
|
+
'executionPolicyDigest'})
|
|
267
|
+
for key in ('sourceDigest', 'bundleDigest', 'sourceCohortDigest', 'executionPolicyDigest'):
|
|
268
|
+
_digest(item[key])
|
|
269
|
+
encoded = _canonical(item)
|
|
270
|
+
if encoded in cohort_seen:
|
|
271
|
+
_fail('generation-authority-configuration-invalid')
|
|
272
|
+
cohort_seen.add(encoded); normalized_cohorts.append(item)
|
|
273
|
+
subjects = policy['approvedSubjects']
|
|
274
|
+
if type(subjects) is not list or not 1 <= len(subjects) <= maximum_subjects:
|
|
275
|
+
_fail('generation-authority-configuration-invalid')
|
|
276
|
+
normalized_subjects = []
|
|
277
|
+
seen_subjects: set[tuple[int, str]] = set()
|
|
278
|
+
seen_subject_oids: set[int] = set()
|
|
279
|
+
seen_subject_names: set[str] = set()
|
|
280
|
+
for subject in subjects:
|
|
281
|
+
item = _closed(subject, {'subject', 'audience', 'ownershipReceiptDigest',
|
|
282
|
+
'membershipsDigest', 'flagsDigest'})
|
|
283
|
+
ref = _closed(item['subject'], {'oid', 'name'})
|
|
284
|
+
oid = _uint(ref['oid'], 1, 4_294_967_295); name = _name(ref['name'])
|
|
285
|
+
if ((oid, name) in seen_subjects or oid in seen_subject_oids
|
|
286
|
+
or name in seen_subject_names or item['audience'] not in ('person', 'batch')):
|
|
287
|
+
_fail('generation-authority-configuration-invalid')
|
|
288
|
+
seen_subjects.add((oid, name)); seen_subject_oids.add(oid); seen_subject_names.add(name)
|
|
289
|
+
for key in ('ownershipReceiptDigest', 'membershipsDigest', 'flagsDigest'):
|
|
290
|
+
_digest(item[key])
|
|
291
|
+
normalized_subjects.append({'subject': {'oid': oid, 'name': name},
|
|
292
|
+
'audience': item['audience'],
|
|
293
|
+
'ownershipReceiptDigest': item['ownershipReceiptDigest'],
|
|
294
|
+
'membershipsDigest': item['membershipsDigest'],
|
|
295
|
+
'flagsDigest': item['flagsDigest']})
|
|
296
|
+
if len(normalized_subjects) > maximum_subjects:
|
|
297
|
+
_fail('generation-authority-configuration-invalid')
|
|
298
|
+
keys = config['keys']
|
|
299
|
+
if type(keys) is not list or not 1 <= len(keys) <= 32:
|
|
300
|
+
_fail('generation-authority-configuration-invalid')
|
|
301
|
+
keys_by_id: dict[str, dict[str, Any]] = {}
|
|
302
|
+
scope_order = {scope: index for index, scope in enumerate(SCOPES)}
|
|
303
|
+
for key in keys:
|
|
304
|
+
item = _closed(key, {'keyId', 'publicKey', 'principalId', 'scopes'})
|
|
305
|
+
key_id = _text(item['keyId'], 128); _text(item['principalId'], 128)
|
|
306
|
+
public = _b64decode(item['publicKey'], 32)
|
|
307
|
+
scopes = item['scopes']
|
|
308
|
+
if (type(scopes) is not list or not scopes or len(scopes) > 2
|
|
309
|
+
or any(type(s) is not str or s not in SCOPES for s in scopes)
|
|
310
|
+
or len(set(scopes)) != len(scopes)
|
|
311
|
+
or scopes != sorted(scopes, key=scope_order.__getitem__)):
|
|
312
|
+
_fail('generation-authority-configuration-invalid')
|
|
313
|
+
if key_id in keys_by_id:
|
|
314
|
+
_fail('generation-authority-configuration-invalid')
|
|
315
|
+
keys_by_id[key_id] = {'keyId': key_id, 'publicKeyBytes': public,
|
|
316
|
+
'principalId': item['principalId'], 'scopes': tuple(scopes)}
|
|
317
|
+
normalized = _json_copy(config)
|
|
318
|
+
if len(_canonical(normalized)) > _MAX_CONFIG:
|
|
319
|
+
_fail('generation-authority-capacity')
|
|
320
|
+
# Force full bounded validation while retaining the original exact config.
|
|
321
|
+
return normalized, keys_by_id
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _validate_subjects(value: object, policy: dict[str, Any]) -> list[dict[str, Any]]:
|
|
325
|
+
if type(value) is not list or not 1 <= len(value) <= policy['maximumSubjects']:
|
|
326
|
+
_fail('generation-authority-intent-invalid')
|
|
327
|
+
approved = policy['approvedSubjects']
|
|
328
|
+
if len(value) != len(approved):
|
|
329
|
+
_fail('generation-authority-subject-coverage-mismatch')
|
|
330
|
+
seen_oid: set[int] = set(); seen_name: set[str] = set(); all_names: set[str] = set()
|
|
331
|
+
result = []
|
|
332
|
+
edge_count = 0
|
|
333
|
+
for index, raw in enumerate(value):
|
|
334
|
+
item = _closed(raw, {'subject', 'audience', 'observedFlags', 'memberships',
|
|
335
|
+
'ownershipReceiptDigest', 'newLoginName'},
|
|
336
|
+
'generation-authority-intent-invalid')
|
|
337
|
+
sub = _closed(item['subject'], {'oid', 'name'}, 'generation-authority-intent-invalid')
|
|
338
|
+
oid = _uint(sub['oid'], 1, 4_294_967_295); name = _name(sub['name'])
|
|
339
|
+
if oid in seen_oid or name in seen_name:
|
|
340
|
+
_fail('generation-authority-intent-invalid')
|
|
341
|
+
seen_oid.add(oid); seen_name.add(name); all_names.add(name)
|
|
342
|
+
if item['audience'] not in ('person', 'batch'):
|
|
343
|
+
_fail('generation-authority-intent-invalid')
|
|
344
|
+
flags = _flags(item['observedFlags'])
|
|
345
|
+
if not flags['canLogin'] or any(flags[k] for k in _ROLE_FLAGS if k not in ('canLogin', 'inherit')):
|
|
346
|
+
_fail('generation-authority-subject-flags-mismatch')
|
|
347
|
+
memberships = _membership_list(item['memberships'])
|
|
348
|
+
edge_count += len(memberships)
|
|
349
|
+
if edge_count > 1024:
|
|
350
|
+
_fail('generation-authority-capacity')
|
|
351
|
+
ownership = _digest(item['ownershipReceiptDigest'])
|
|
352
|
+
new_login = _name(item['newLoginName'])
|
|
353
|
+
if new_login in all_names or new_login in {r['newLoginName'] for r in result}:
|
|
354
|
+
_fail('generation-authority-intent-invalid')
|
|
355
|
+
expected = approved[index]
|
|
356
|
+
subject_ref = {'oid': oid, 'name': name}
|
|
357
|
+
if (expected['subject'] != subject_ref or expected['audience'] != item['audience']
|
|
358
|
+
or expected['ownershipReceiptDigest'] != ownership
|
|
359
|
+
or expected['membershipsDigest'] != _sha(_canonical(memberships))
|
|
360
|
+
or expected['flagsDigest'] != _sha(_canonical(flags))):
|
|
361
|
+
_fail('generation-authority-subject-coverage-mismatch')
|
|
362
|
+
result.append({'subject': subject_ref, 'audience': item['audience'],
|
|
363
|
+
'observedFlags': flags, 'memberships': memberships,
|
|
364
|
+
'ownershipReceiptDigest': ownership, 'newLoginName': new_login})
|
|
365
|
+
if all_names.intersection(r['newLoginName'] for r in result):
|
|
366
|
+
_fail('generation-authority-intent-invalid')
|
|
367
|
+
return result
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _validate_principals(value: object, prepared: dict[str, Any]) -> list[dict[str, Any]]:
|
|
371
|
+
if type(value) is not list or len(value) != len(prepared['subjects']):
|
|
372
|
+
_fail('generation-authority-intent-invalid')
|
|
373
|
+
result = []
|
|
374
|
+
seen_login: set[int] = set(); seen_subject: set[int] = set()
|
|
375
|
+
for i, raw in enumerate(value):
|
|
376
|
+
item = _closed(raw, {'login', 'subject', 'audience', 'issuerProfile',
|
|
377
|
+
'issuerReceiptDigest', 'ownershipReceiptDigest', 'memberships'},
|
|
378
|
+
'generation-authority-intent-invalid')
|
|
379
|
+
roles = {}
|
|
380
|
+
for key in ('login', 'subject'):
|
|
381
|
+
role = _closed(item[key], {'oid', 'name'}, 'generation-authority-intent-invalid')
|
|
382
|
+
roles[key] = {'oid': _uint(role['oid'], 1, 4_294_967_295),
|
|
383
|
+
'name': _name(role['name'])}
|
|
384
|
+
if roles['login']['oid'] in seen_login or roles['subject']['oid'] in seen_subject:
|
|
385
|
+
_fail('generation-authority-intent-invalid')
|
|
386
|
+
seen_login.add(roles['login']['oid']); seen_subject.add(roles['subject']['oid'])
|
|
387
|
+
original = prepared['subjects'][i]
|
|
388
|
+
if (roles['subject'] != original['subject']
|
|
389
|
+
or roles['login']['name'] != original['newLoginName']
|
|
390
|
+
or item['audience'] != original['audience']):
|
|
391
|
+
_fail('generation-authority-intent-invalid')
|
|
392
|
+
issuer = _text(item['issuerProfile'], 256)
|
|
393
|
+
issuer_receipt = _digest(item['issuerReceiptDigest'])
|
|
394
|
+
ownership = _digest(item['ownershipReceiptDigest'])
|
|
395
|
+
memberships = _membership_list(item['memberships'])
|
|
396
|
+
if (issuer != prepared['issuerProfile']
|
|
397
|
+
or ownership != original['ownershipReceiptDigest']
|
|
398
|
+
or memberships != original['memberships']):
|
|
399
|
+
_fail('generation-authority-intent-invalid')
|
|
400
|
+
result.append({'login': roles['login'], 'subject': roles['subject'],
|
|
401
|
+
'audience': item['audience'], 'issuerProfile': issuer,
|
|
402
|
+
'issuerReceiptDigest': issuer_receipt,
|
|
403
|
+
'ownershipReceiptDigest': ownership, 'memberships': memberships})
|
|
404
|
+
return result
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _validate_intent(scope: str, raw: dict[str, Any], config: dict[str, Any],
|
|
408
|
+
identity: InitialEnrollmentIdentity | None,
|
|
409
|
+
prepared: dict[str, Any] | None
|
|
410
|
+
) -> tuple[dict[str, Any], tuple[str, str, str]]:
|
|
411
|
+
policy = config['sourcePolicy']
|
|
412
|
+
if scope == PREPARE_SCOPE:
|
|
413
|
+
fields = {'profile', 'providerId', 'enrollmentId', 'installationId', 'targetCustody',
|
|
414
|
+
'storeId', 'source', 'bundleDigest', 'expectedHead', 'sourceCohortDigest',
|
|
415
|
+
'executionPolicyDigest', 'issuerProfile', 'initialEpoch', 'subjects',
|
|
416
|
+
'maximumRoles'}
|
|
417
|
+
item = _closed(raw, fields, 'generation-authority-intent-invalid')
|
|
418
|
+
if item['profile'] != PREPARE_INTENT_PROFILE:
|
|
419
|
+
_fail('generation-authority-intent-invalid')
|
|
420
|
+
if identity is None or type(identity._context) is not GenerationEnrollmentAuthorityContext:
|
|
421
|
+
_fail('generation-authority-identity-required')
|
|
422
|
+
if (item['providerId'] != config['providerId'] or item['storeId'] != config['storeId']
|
|
423
|
+
or item['installationId'] != config['installationId']
|
|
424
|
+
or item['enrollmentId'] != identity.enrollment_id
|
|
425
|
+
or item['initialEpoch'] != identity.initial_epoch
|
|
426
|
+
or _target_custody(item['targetCustody']) != config['targetCustody']):
|
|
427
|
+
_fail('generation-authority-target-mismatch')
|
|
428
|
+
source = _closed(item['source'], {'format', 'sha256'}, 'generation-authority-intent-invalid')
|
|
429
|
+
if source['format'] != 'json':
|
|
430
|
+
_fail('generation-authority-intent-invalid')
|
|
431
|
+
_digest(source['sha256'])
|
|
432
|
+
for key in ('bundleDigest', 'expectedHead', 'sourceCohortDigest', 'executionPolicyDigest'):
|
|
433
|
+
_digest(item[key])
|
|
434
|
+
_text(item['issuerProfile'], 256)
|
|
435
|
+
if item['issuerProfile'] != policy['issuerProfile']:
|
|
436
|
+
_fail('generation-authority-policy-mismatch')
|
|
437
|
+
cohort = {'sourceDigest': source['sha256'], 'bundleDigest': item['bundleDigest'],
|
|
438
|
+
'sourceCohortDigest': item['sourceCohortDigest'],
|
|
439
|
+
'executionPolicyDigest': item['executionPolicyDigest']}
|
|
440
|
+
if not any(_canonical(cohort) == _canonical(approved)
|
|
441
|
+
for approved in policy['approvedCohorts']):
|
|
442
|
+
_fail('generation-authority-cohort-not-approved')
|
|
443
|
+
subjects = _validate_subjects(item['subjects'], policy)
|
|
444
|
+
if (type(item['maximumRoles']) is not int or item['maximumRoles'] != len(subjects)
|
|
445
|
+
or item['maximumRoles'] > 256):
|
|
446
|
+
_fail('generation-authority-intent-invalid')
|
|
447
|
+
return {**item, 'source': source, 'subjects': subjects}, (scope, item['providerId'], item['enrollmentId'])
|
|
448
|
+
|
|
449
|
+
fields = {'profile', 'providerId', 'enrollmentId', 'installationId', 'targetCustody',
|
|
450
|
+
'storeId', 'prepareRequestDigest', 'prepareApprovalDigest',
|
|
451
|
+
'preparationReceiptDigest', 'source', 'bundleDigest', 'expectedHead',
|
|
452
|
+
'sourceCohortDigest', 'executionPolicyDigest', 'initialEpoch', 'principals',
|
|
453
|
+
'principalsDigest', 'fenceReceiptDigest', 'externalReservationDigest'}
|
|
454
|
+
item = _closed(raw, fields, 'generation-authority-intent-invalid')
|
|
455
|
+
if item['profile'] != ACTIVATE_INTENT_PROFILE or prepared is None:
|
|
456
|
+
_fail('generation-authority-activation-preparation-required')
|
|
457
|
+
original = prepared['intent']
|
|
458
|
+
for key, source_key in (('providerId', 'providerId'), ('enrollmentId', 'enrollmentId'),
|
|
459
|
+
('installationId', 'installationId'), ('targetCustody', 'targetCustody'),
|
|
460
|
+
('storeId', 'storeId'), ('source', 'source'), ('bundleDigest', 'bundleDigest'),
|
|
461
|
+
('expectedHead', 'expectedHead'), ('sourceCohortDigest', 'sourceCohortDigest'),
|
|
462
|
+
('executionPolicyDigest', 'executionPolicyDigest'), ('initialEpoch', 'initialEpoch')):
|
|
463
|
+
if item[key] != original[source_key]:
|
|
464
|
+
_fail('generation-authority-activation-binding-mismatch')
|
|
465
|
+
_digest(item['prepareRequestDigest']); _digest(item['prepareApprovalDigest'])
|
|
466
|
+
_digest(item['preparationReceiptDigest']); _digest(item['principalsDigest'])
|
|
467
|
+
_digest(item['fenceReceiptDigest']); _digest(item['externalReservationDigest'])
|
|
468
|
+
principals = _validate_principals(item['principals'], original)
|
|
469
|
+
if _sha(_canonical(principals)) != item['principalsDigest']:
|
|
470
|
+
_fail('generation-authority-principals-digest-mismatch')
|
|
471
|
+
# The receipt digest is asserted by the native provider. The logical
|
|
472
|
+
# authority binds the activation request to the exact earlier signed
|
|
473
|
+
# preparation, but cannot manufacture or authenticate that provider receipt.
|
|
474
|
+
if (item['prepareRequestDigest'] != prepared['intentDigest']
|
|
475
|
+
or item['prepareApprovalDigest'] != prepared['approvalDigest']):
|
|
476
|
+
_fail('generation-authority-activation-binding-mismatch')
|
|
477
|
+
return {**item, 'principals': principals}, (scope, item['providerId'], item['enrollmentId'])
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
from .generation_enrollment_ledger import (
|
|
481
|
+
GenerationEnrollmentAuthorityError,
|
|
482
|
+
_Ledger,
|
|
483
|
+
_replay,
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _b64encode_bytes(value: bytes) -> str:
|
|
488
|
+
return base64.urlsafe_b64encode(value).decode('ascii').rstrip('=')
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _b64decode_bytes(value: object) -> bytes:
|
|
492
|
+
if type(value) is not str or not _B64URL.fullmatch(value):
|
|
493
|
+
_fail('generation-authority-ledger-corrupt')
|
|
494
|
+
try:
|
|
495
|
+
result = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
|
|
496
|
+
except (ValueError, TypeError):
|
|
497
|
+
_fail('generation-authority-ledger-corrupt')
|
|
498
|
+
if base64.urlsafe_b64encode(result).decode('ascii').rstrip('=') != value:
|
|
499
|
+
_fail('generation-authority-ledger-corrupt')
|
|
500
|
+
return result
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
from .generation_authority_bootstrap import (
|
|
504
|
+
_SOURCE_TEST_ISSUER_SEAL,
|
|
505
|
+
_TRUST_ISSUER_ORIGINS,
|
|
506
|
+
GenerationEnrollmentAuthorityContext,
|
|
507
|
+
OriginalGenerationTrustEnrollment,
|
|
508
|
+
_check_issuer_purpose,
|
|
509
|
+
_ContextJournal,
|
|
510
|
+
_GenerationTrustIssuer,
|
|
511
|
+
_require_registered_issuer,
|
|
512
|
+
_source_test_generation_trust_issuer,
|
|
513
|
+
_SourceTestGenerationTrustIssuer,
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
__all__ = (
|
|
517
|
+
'_SOURCE_TEST_ISSUER_SEAL',
|
|
518
|
+
'_TRUST_ISSUER_ORIGINS',
|
|
519
|
+
'GenerationEnrollmentAuthorityContext',
|
|
520
|
+
'OriginalGenerationTrustEnrollment',
|
|
521
|
+
'_ContextJournal',
|
|
522
|
+
'_GenerationTrustIssuer',
|
|
523
|
+
'_SourceTestGenerationTrustIssuer',
|
|
524
|
+
'_check_issuer_purpose',
|
|
525
|
+
'_source_test_generation_trust_issuer',
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
class InitialEnrollmentIdentity(_ImmutableOpaque):
|
|
529
|
+
"""Opaque pair of original enrollment and preallocated initial epoch IDs."""
|
|
530
|
+
|
|
531
|
+
__slots__ = ('_context', '_issuer', 'enrollment_id', 'initial_epoch')
|
|
532
|
+
|
|
533
|
+
def __init__(self, seal: object, issuer: object, context: GenerationEnrollmentAuthorityContext,
|
|
534
|
+
enrollment_id: str, initial_epoch: str):
|
|
535
|
+
if seal is not _REQUEST_SEAL:
|
|
536
|
+
raise TypeError('initial enrollment identity is authority-issued')
|
|
537
|
+
self._issuer = issuer
|
|
538
|
+
self._context = context
|
|
539
|
+
self.enrollment_id = enrollment_id
|
|
540
|
+
self.initial_epoch = initial_epoch
|
|
541
|
+
|
|
542
|
+
def __reduce_ex__(self, _protocol: int):
|
|
543
|
+
raise TypeError('initial enrollment identity is not serializable')
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
class InitialGenerationEnrollmentRequest(_ImmutableOpaque):
|
|
547
|
+
__slots__ = (
|
|
548
|
+
'_effect_key',
|
|
549
|
+
'_identity',
|
|
550
|
+
'_intent_bytes',
|
|
551
|
+
'_intent_digest',
|
|
552
|
+
'_issuer',
|
|
553
|
+
'_payload_bytes',
|
|
554
|
+
'_request_id',
|
|
555
|
+
'_scope',
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
def __init__(self, seal: object, issuer: object, *, request_id: str, scope: str,
|
|
559
|
+
effect_key: tuple[str, str, str], intent_bytes: bytes,
|
|
560
|
+
intent_digest: str, payload_bytes: bytes,
|
|
561
|
+
identity: InitialEnrollmentIdentity):
|
|
562
|
+
if seal is not _REQUEST_SEAL:
|
|
563
|
+
raise TypeError('generation enrollment request is authority-issued')
|
|
564
|
+
self._issuer = issuer; self._request_id = request_id; self._scope = scope
|
|
565
|
+
self._effect_key = effect_key; self._intent_bytes = bytes(intent_bytes)
|
|
566
|
+
self._intent_digest = intent_digest; self._payload_bytes = bytes(payload_bytes)
|
|
567
|
+
self._identity = identity
|
|
568
|
+
|
|
569
|
+
@property
|
|
570
|
+
def request_id(self) -> str:
|
|
571
|
+
return self._request_id
|
|
572
|
+
|
|
573
|
+
@property
|
|
574
|
+
def scope(self) -> str:
|
|
575
|
+
return self._scope
|
|
576
|
+
|
|
577
|
+
@property
|
|
578
|
+
def effect_key(self) -> tuple[str, str, str]:
|
|
579
|
+
return self._effect_key
|
|
580
|
+
|
|
581
|
+
@property
|
|
582
|
+
def intent_digest(self) -> str:
|
|
583
|
+
return self._intent_digest
|
|
584
|
+
|
|
585
|
+
def __reduce_ex__(self, _protocol: int):
|
|
586
|
+
raise TypeError('generation enrollment request is not serializable')
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
class VerifiedInitialGenerationApproval(_ImmutableOpaque):
|
|
590
|
+
__slots__ = ('_approval_digest', '_envelope_bytes', '_issuer', '_request')
|
|
591
|
+
|
|
592
|
+
def __init__(self, seal: object, issuer: object,
|
|
593
|
+
request: InitialGenerationEnrollmentRequest,
|
|
594
|
+
approval_digest: str, envelope_bytes: bytes):
|
|
595
|
+
if seal is not _APPROVAL_SEAL:
|
|
596
|
+
raise TypeError('generation enrollment approval is authority-issued')
|
|
597
|
+
self._issuer = issuer; self._request = request
|
|
598
|
+
self._approval_digest = approval_digest; self._envelope_bytes = bytes(envelope_bytes)
|
|
599
|
+
|
|
600
|
+
@property
|
|
601
|
+
def request_id(self) -> str:
|
|
602
|
+
return self._request.request_id
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def scope(self) -> str:
|
|
606
|
+
return self._request.scope
|
|
607
|
+
|
|
608
|
+
@property
|
|
609
|
+
def approval_digest(self) -> str:
|
|
610
|
+
return self._approval_digest
|
|
611
|
+
|
|
612
|
+
def __reduce_ex__(self, _protocol: int):
|
|
613
|
+
raise TypeError('generation enrollment approval is not serializable')
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
class InitialGenerationReservation(_ImmutableOpaque):
|
|
617
|
+
"""One-shot logical reservation; not authority to perform a native effect."""
|
|
618
|
+
|
|
619
|
+
__slots__ = ('_issuer', '_request', '_reservation_digest', '_reservation_id')
|
|
620
|
+
|
|
621
|
+
def __init__(self, seal: object, issuer: object,
|
|
622
|
+
request: InitialGenerationEnrollmentRequest,
|
|
623
|
+
reservation_id: str, reservation_digest: str):
|
|
624
|
+
if seal is not _RESERVATION_SEAL:
|
|
625
|
+
raise TypeError('generation reservation is authority-issued')
|
|
626
|
+
self._issuer = issuer; self._request = request
|
|
627
|
+
self._reservation_id = reservation_id
|
|
628
|
+
self._reservation_digest = reservation_digest
|
|
629
|
+
|
|
630
|
+
@property
|
|
631
|
+
def reservation_id(self) -> str:
|
|
632
|
+
return self._reservation_id
|
|
633
|
+
|
|
634
|
+
@property
|
|
635
|
+
def journal_record_digest(self) -> str:
|
|
636
|
+
return self._reservation_digest
|
|
637
|
+
|
|
638
|
+
def __reduce_ex__(self, _protocol: int):
|
|
639
|
+
raise TypeError('generation reservation is not serializable')
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
class _VerifiedInitialGenerationOutcome(_ImmutableOpaque):
|
|
643
|
+
"""Opaque source/native-provider outcome. The source-test path is marked."""
|
|
644
|
+
|
|
645
|
+
__slots__ = ('_issuer', '_receipt_digest', '_reservation', '_source_test_only', '_status')
|
|
646
|
+
|
|
647
|
+
def __init__(self, seal: object, issuer: object, reservation: InitialGenerationReservation,
|
|
648
|
+
status: str, receipt_digest: str, *, source_test_only: bool):
|
|
649
|
+
if seal is not _OUTCOME_SEAL:
|
|
650
|
+
raise TypeError('generation outcome is provider-issued')
|
|
651
|
+
self._issuer = issuer; self._reservation = reservation; self._status = status
|
|
652
|
+
self._receipt_digest = receipt_digest; self._source_test_only = source_test_only
|
|
653
|
+
|
|
654
|
+
@property
|
|
655
|
+
def status(self) -> str:
|
|
656
|
+
return self._status
|
|
657
|
+
|
|
658
|
+
@property
|
|
659
|
+
def receipt_digest(self) -> str:
|
|
660
|
+
return self._receipt_digest
|
|
661
|
+
|
|
662
|
+
def __reduce_ex__(self, _protocol: int):
|
|
663
|
+
raise TypeError('generation outcome is not serializable')
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
class ConfiguredGenerationEnrollmentAuthority:
|
|
667
|
+
"""Configured two-scope authority; it never performs native effects."""
|
|
668
|
+
|
|
669
|
+
__slots__ = (
|
|
670
|
+
'_approvals',
|
|
671
|
+
'_config',
|
|
672
|
+
'_config_bytes',
|
|
673
|
+
'_config_digest',
|
|
674
|
+
'_context',
|
|
675
|
+
'_context_digest',
|
|
676
|
+
'_identities',
|
|
677
|
+
'_issuer',
|
|
678
|
+
'_keys',
|
|
679
|
+
'_ledger',
|
|
680
|
+
'_outcomes',
|
|
681
|
+
'_prepared',
|
|
682
|
+
'_requests',
|
|
683
|
+
'_requests_by_id',
|
|
684
|
+
'_reservations',
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
def __init__(self, configuration: object, *, context: GenerationEnrollmentAuthorityContext,
|
|
688
|
+
ledger_path: str | os.PathLike[str]):
|
|
689
|
+
if type(context) is not GenerationEnrollmentAuthorityContext:
|
|
690
|
+
_fail('generation-authority-context-unverified')
|
|
691
|
+
issuer = context._issuer
|
|
692
|
+
if type(issuer) is _SourceTestGenerationTrustIssuer:
|
|
693
|
+
origin = _require_registered_issuer(issuer, 'source-test')
|
|
694
|
+
resolver = _SourceTestGenerationTrustIssuer.resolve_generation_authority_context
|
|
695
|
+
elif type(issuer) is _GenerationTrustIssuer:
|
|
696
|
+
origin = _require_registered_issuer(issuer, 'production')
|
|
697
|
+
resolver = _GenerationTrustIssuer.resolve_generation_authority_context
|
|
698
|
+
else:
|
|
699
|
+
_fail('generation-authority-context-unverified')
|
|
700
|
+
resolver(issuer, context)
|
|
701
|
+
config, keys = _config(configuration)
|
|
702
|
+
projection = context.public_reference
|
|
703
|
+
_check_issuer_purpose(origin, projection, config['purpose'])
|
|
704
|
+
encoded = _canonical(config)
|
|
705
|
+
if encoded != context._trust._configuration_bytes:
|
|
706
|
+
_fail('generation-authority-configuration-mismatch')
|
|
707
|
+
projection = context.public_reference
|
|
708
|
+
self._config = config; self._config_bytes = encoded
|
|
709
|
+
self._config_digest = _sha(encoded); self._keys = keys
|
|
710
|
+
self._context = context; self._context_digest = _sha(context._projection_bytes)
|
|
711
|
+
self._issuer = issuer
|
|
712
|
+
self._ledger = _Ledger(ledger_path, config['authorityId'], self._config_digest,
|
|
713
|
+
self._context_digest, config['purpose'])
|
|
714
|
+
if Path(os.fspath(ledger_path)) != context._trust._ledger_path:
|
|
715
|
+
_fail('generation-authority-ledger-path-mismatch')
|
|
716
|
+
if projection['configurationDigest'] != self._config_digest:
|
|
717
|
+
_fail('generation-authority-context-mismatch')
|
|
718
|
+
# A context is already an original enrollment. Therefore its missing
|
|
719
|
+
# ledger or lock is evidence loss, never permission to initialize a new
|
|
720
|
+
# history. First-ledger creation belongs to the original bootstrap
|
|
721
|
+
# enrollment path, which is not yet integrated for production.
|
|
722
|
+
records = self._ledger.events(create=False)
|
|
723
|
+
replay = _replay(records)
|
|
724
|
+
self._identities: dict[str, InitialEnrollmentIdentity] = {}
|
|
725
|
+
self._requests: dict[int, InitialGenerationEnrollmentRequest] = {}
|
|
726
|
+
self._requests_by_id: dict[str, InitialGenerationEnrollmentRequest] = {}
|
|
727
|
+
self._approvals: dict[int, VerifiedInitialGenerationApproval] = {}
|
|
728
|
+
self._reservations: dict[int, InitialGenerationReservation] = {}
|
|
729
|
+
self._outcomes: dict[int, _VerifiedInitialGenerationOutcome] = {}
|
|
730
|
+
self._prepared = replay['requests']
|
|
731
|
+
|
|
732
|
+
@property
|
|
733
|
+
def authority_id(self) -> str:
|
|
734
|
+
return self._config['authorityId']
|
|
735
|
+
|
|
736
|
+
@property
|
|
737
|
+
def purpose(self) -> str:
|
|
738
|
+
return self._config['purpose']
|
|
739
|
+
|
|
740
|
+
@property
|
|
741
|
+
def context(self) -> GenerationEnrollmentAuthorityContext:
|
|
742
|
+
return self._context
|
|
743
|
+
|
|
744
|
+
def allocate_identity(self) -> InitialEnrollmentIdentity:
|
|
745
|
+
# The original issuer durably reserved both logical IDs at context
|
|
746
|
+
# birth. They are separate from the trust-registry entry ID.
|
|
747
|
+
enrollment_id = self._context._logical_enrollment_id
|
|
748
|
+
epoch = self._context._initial_epoch
|
|
749
|
+
entries = [event['payload'] for event in self._ledger.events(create=False)
|
|
750
|
+
if event['kind'] == 'identity-allocated']
|
|
751
|
+
if entries != [{'enrollmentId': enrollment_id, 'initialEpoch': epoch}]:
|
|
752
|
+
_fail('generation-authority-original-identity-mismatch')
|
|
753
|
+
prior = self._identities.get(enrollment_id)
|
|
754
|
+
if prior is not None:
|
|
755
|
+
if prior.initial_epoch != epoch or prior._context is not self._context:
|
|
756
|
+
_fail('generation-authority-original-identity-mismatch')
|
|
757
|
+
return prior
|
|
758
|
+
identity = InitialEnrollmentIdentity(_REQUEST_SEAL, self, self._context,
|
|
759
|
+
enrollment_id, epoch)
|
|
760
|
+
self._identities[enrollment_id] = identity
|
|
761
|
+
return identity
|
|
762
|
+
|
|
763
|
+
def prepare_request(self, scope: str, exact_intent_bytes: bytes,
|
|
764
|
+
identity: InitialEnrollmentIdentity,
|
|
765
|
+
*, preparation: VerifiedInitialGenerationApproval | None = None
|
|
766
|
+
) -> InitialGenerationEnrollmentRequest:
|
|
767
|
+
self._require_identity(identity)
|
|
768
|
+
if scope not in SCOPES:
|
|
769
|
+
_fail('generation-authority-scope-invalid')
|
|
770
|
+
raw = _parse_canonical(exact_intent_bytes, maximum=_MAX_REQUEST)
|
|
771
|
+
prepared = None
|
|
772
|
+
if scope == ACTIVATE_SCOPE:
|
|
773
|
+
if type(preparation) is not VerifiedInitialGenerationApproval:
|
|
774
|
+
_fail('generation-authority-activation-preparation-required')
|
|
775
|
+
previous = self._require_approval(preparation)
|
|
776
|
+
if previous._request._identity is not identity:
|
|
777
|
+
_fail('generation-authority-activation-identity-mismatch')
|
|
778
|
+
prepared = self._prepared.get(previous.request_id)
|
|
779
|
+
if prepared is None or prepared['approvedEnvelope'] is None:
|
|
780
|
+
_fail('generation-authority-activation-preparation-required')
|
|
781
|
+
_parse_canonical(_b64decode_bytes(prepared['payload']['signedPayloadBytes']))
|
|
782
|
+
prepared = {'intent': _parse_canonical(_b64decode_bytes(prepared['payload']['intentBytes'])),
|
|
783
|
+
'intentDigest': prepared['payload']['intentDigest'],
|
|
784
|
+
'approvalDigest': _sha(_canonical(prepared['approvedEnvelope'])),
|
|
785
|
+
'preparationReceiptDigest': None}
|
|
786
|
+
normalized, effect_key = _validate_intent(scope, raw, self._config, identity, prepared)
|
|
787
|
+
intent_bytes = _canonical(normalized)
|
|
788
|
+
current = _replay(self._ledger.events(create=False))
|
|
789
|
+
previous_id = current['effectKeys'].get(effect_key)
|
|
790
|
+
if previous_id is not None:
|
|
791
|
+
saved = current['requests'][previous_id]['payload']
|
|
792
|
+
if (saved['identityEnrollmentId'] != identity.enrollment_id
|
|
793
|
+
or _b64decode_bytes(saved['intentBytes']) != intent_bytes):
|
|
794
|
+
_fail('generation-authority-original-request-mismatch')
|
|
795
|
+
return self.recover_request(scope, intent_bytes, identity, previous_id)
|
|
796
|
+
request_id = str(uuid.uuid4())
|
|
797
|
+
key = next((item for item in self._config['keys']
|
|
798
|
+
if scope in item['scopes']), None)
|
|
799
|
+
if key is None:
|
|
800
|
+
_fail('generation-authority-key-unavailable')
|
|
801
|
+
payload = {'profile': APPROVAL_PROFILE, 'authorityId': self.authority_id,
|
|
802
|
+
'principalId': key['principalId'], 'keyId': key['keyId'],
|
|
803
|
+
'requestId': request_id, 'purpose': self.purpose, 'scope': scope,
|
|
804
|
+
'policyRevision': self._config['policyRevision'],
|
|
805
|
+
'configurationDigest': self._config_digest,
|
|
806
|
+
'contextDigest': self._context_digest,
|
|
807
|
+
'targetCustody': self._config['targetCustody'], 'intent': normalized}
|
|
808
|
+
payload_bytes = _canonical(payload)
|
|
809
|
+
logpayload = {'requestId': request_id, 'scope': scope,
|
|
810
|
+
'effectKey': list(effect_key), 'intentBytes': _b64encode_bytes(intent_bytes),
|
|
811
|
+
'intentDigest': _sha(intent_bytes),
|
|
812
|
+
'signedPayloadBytes': _b64encode_bytes(payload_bytes),
|
|
813
|
+
'identityEnrollmentId': identity.enrollment_id}
|
|
814
|
+
try:
|
|
815
|
+
self._ledger._append('request-prepared', logpayload)
|
|
816
|
+
except GenerationEnrollmentAuthorityError:
|
|
817
|
+
# A process may have appended the stable effect key concurrently.
|
|
818
|
+
latest = _replay(self._ledger.events(create=False))
|
|
819
|
+
winner_id = latest['effectKeys'].get(effect_key)
|
|
820
|
+
if winner_id is None:
|
|
821
|
+
raise
|
|
822
|
+
winner = latest['requests'][winner_id]['payload']
|
|
823
|
+
if (winner['identityEnrollmentId'] != identity.enrollment_id
|
|
824
|
+
or _b64decode_bytes(winner['intentBytes']) != intent_bytes):
|
|
825
|
+
_fail('generation-authority-original-request-mismatch')
|
|
826
|
+
return self.recover_request(scope, intent_bytes, identity, winner_id)
|
|
827
|
+
request = InitialGenerationEnrollmentRequest(
|
|
828
|
+
_REQUEST_SEAL, self, request_id=request_id, scope=scope,
|
|
829
|
+
effect_key=effect_key, intent_bytes=intent_bytes,
|
|
830
|
+
intent_digest=_sha(intent_bytes), payload_bytes=payload_bytes, identity=identity)
|
|
831
|
+
self._requests[id(request)] = request; self._requests_by_id[request_id] = request
|
|
832
|
+
self._prepared[request_id] = {'payload': logpayload, 'signedPayload': payload,
|
|
833
|
+
'approvedEnvelope': None, 'reservation': None,
|
|
834
|
+
'settlement': None}
|
|
835
|
+
return request
|
|
836
|
+
|
|
837
|
+
def export_signing_request(self, request: InitialGenerationEnrollmentRequest) -> dict[str, Any]:
|
|
838
|
+
request = self._require_request(request)
|
|
839
|
+
return {'domain': SIGNING_DOMAIN.decode('ascii'),
|
|
840
|
+
'payload': _parse_canonical(request._payload_bytes),
|
|
841
|
+
'intent': _parse_canonical(request._intent_bytes)}
|
|
842
|
+
|
|
843
|
+
def verify_approval(self, request: InitialGenerationEnrollmentRequest,
|
|
844
|
+
signed_envelope: object) -> VerifiedInitialGenerationApproval:
|
|
845
|
+
request = self._require_request(request)
|
|
846
|
+
envelope = _json_copy(signed_envelope)
|
|
847
|
+
_closed(envelope, {'payload', 'keyId', 'signature'},
|
|
848
|
+
'generation-authority-envelope-invalid')
|
|
849
|
+
if type(envelope['payload']) is not dict:
|
|
850
|
+
_fail('generation-authority-envelope-invalid')
|
|
851
|
+
payload_bytes = _canonical(envelope['payload'])
|
|
852
|
+
if payload_bytes != request._payload_bytes:
|
|
853
|
+
_fail('generation-authority-request-mismatch')
|
|
854
|
+
if envelope['keyId'] != envelope['payload'].get('keyId'):
|
|
855
|
+
_fail('generation-authority-key-mismatch')
|
|
856
|
+
key = self._keys.get(envelope['keyId'])
|
|
857
|
+
if key is None or request.scope not in key['scopes']:
|
|
858
|
+
_fail('generation-authority-key-untrusted')
|
|
859
|
+
sig = _b64decode(envelope['signature'], 64)
|
|
860
|
+
try:
|
|
861
|
+
from cryptography import __version__ as crypto_version
|
|
862
|
+
from cryptography.exceptions import InvalidSignature
|
|
863
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
864
|
+
Ed25519PublicKey,
|
|
865
|
+
)
|
|
866
|
+
except ImportError:
|
|
867
|
+
_fail('generation-authority-crypto-unavailable')
|
|
868
|
+
if crypto_version != '50.0.2':
|
|
869
|
+
_fail('generation-authority-crypto-version-unqualified')
|
|
870
|
+
try:
|
|
871
|
+
Ed25519PublicKey.from_public_bytes(key['publicKeyBytes']).verify(
|
|
872
|
+
sig, SIGNING_DOMAIN + payload_bytes)
|
|
873
|
+
except InvalidSignature:
|
|
874
|
+
_fail('generation-authority-signature-invalid')
|
|
875
|
+
except (TypeError, ValueError):
|
|
876
|
+
_fail('generation-authority-key-invalid')
|
|
877
|
+
envelope_bytes = _canonical(envelope)
|
|
878
|
+
digest = _sha(envelope_bytes)
|
|
879
|
+
prior = self._prepared[request.request_id]
|
|
880
|
+
if prior['approvedEnvelope'] is not None:
|
|
881
|
+
if _canonical(prior['approvedEnvelope']) != envelope_bytes:
|
|
882
|
+
_fail('generation-authority-replay-conflict')
|
|
883
|
+
existing = next((v for v in self._approvals.values() if v._request is request), None)
|
|
884
|
+
if existing is not None:
|
|
885
|
+
return existing
|
|
886
|
+
else:
|
|
887
|
+
# Re-read before appending so a concurrent process that verified
|
|
888
|
+
# this exact signed envelope is observed as the original decision.
|
|
889
|
+
current = _replay(self._ledger.events(create=False))['requests'].get(
|
|
890
|
+
request.request_id)
|
|
891
|
+
if current is None:
|
|
892
|
+
_fail('generation-authority-original-request-missing')
|
|
893
|
+
if current['approvedEnvelope'] is not None:
|
|
894
|
+
if _canonical(current['approvedEnvelope']) != envelope_bytes:
|
|
895
|
+
_fail('generation-authority-replay-conflict')
|
|
896
|
+
else:
|
|
897
|
+
self._ledger._append('approval-verified', {
|
|
898
|
+
'requestId': request.request_id,
|
|
899
|
+
'envelopeBytes': _b64encode_bytes(envelope_bytes),
|
|
900
|
+
'approvalDigest': digest})
|
|
901
|
+
prior['approvedEnvelope'] = envelope
|
|
902
|
+
verified = VerifiedInitialGenerationApproval(
|
|
903
|
+
_APPROVAL_SEAL, self, request, digest, envelope_bytes)
|
|
904
|
+
self._approvals[id(verified)] = verified
|
|
905
|
+
return verified
|
|
906
|
+
|
|
907
|
+
def reserve_effect(self, approval: VerifiedInitialGenerationApproval
|
|
908
|
+
) -> InitialGenerationReservation:
|
|
909
|
+
approval = self._require_approval(approval)
|
|
910
|
+
request = approval._request
|
|
911
|
+
prior = self._prepared[request.request_id]
|
|
912
|
+
if prior['reservation'] is not None:
|
|
913
|
+
_fail('generation-authority-effect-already-reserved')
|
|
914
|
+
reservation_id = str(uuid.uuid4())
|
|
915
|
+
payload = {'requestId': request.request_id, 'reservationId': reservation_id,
|
|
916
|
+
'approvalDigest': approval.approval_digest,
|
|
917
|
+
'effectKey': list(request.effect_key)}
|
|
918
|
+
record = self._ledger._append('effect-reserved', payload)
|
|
919
|
+
reservation = InitialGenerationReservation(_RESERVATION_SEAL, self, request,
|
|
920
|
+
reservation_id, record['digest'])
|
|
921
|
+
self._reservations[id(reservation)] = reservation
|
|
922
|
+
prior['reservation'] = payload
|
|
923
|
+
return reservation
|
|
924
|
+
|
|
925
|
+
def observe(self, request: InitialGenerationEnrollmentRequest) -> dict[str, Any]:
|
|
926
|
+
request = self._require_request(request)
|
|
927
|
+
events = self._ledger.events(create=False)
|
|
928
|
+
replay = _replay(events)['requests'].get(request.request_id)
|
|
929
|
+
if replay is None:
|
|
930
|
+
_fail('generation-authority-original-request-missing')
|
|
931
|
+
return {'requestId': request.request_id, 'scope': request.scope,
|
|
932
|
+
'intentDigest': request.intent_digest,
|
|
933
|
+
'approvalStatus': 'verified' if replay['approvedEnvelope'] else 'prepared',
|
|
934
|
+
'approvalDigest': (_sha(_canonical(replay['approvedEnvelope']))
|
|
935
|
+
if replay['approvedEnvelope'] else None),
|
|
936
|
+
'effectStatus': (replay['settlement']['status'] if replay['settlement']
|
|
937
|
+
else 'reserved' if replay['reservation'] else 'not-reserved'),
|
|
938
|
+
'reservationId': (replay['reservation']['reservationId']
|
|
939
|
+
if replay['reservation'] else None),
|
|
940
|
+
'reservationDigest': next((event['digest'] for event in events
|
|
941
|
+
if event['kind'] == 'effect-reserved'
|
|
942
|
+
and event['payload']['requestId'] == request.request_id), None),
|
|
943
|
+
'effectReceiptDigest': (replay['settlement']['receiptDigest']
|
|
944
|
+
if replay['settlement'] else None)}
|
|
945
|
+
|
|
946
|
+
def recover_request(self, scope: str, exact_intent_bytes: bytes,
|
|
947
|
+
identity: InitialEnrollmentIdentity,
|
|
948
|
+
expected_request_id: str) -> InitialGenerationEnrollmentRequest:
|
|
949
|
+
identity = self._require_identity(identity)
|
|
950
|
+
expected_request_id = _uuid(expected_request_id)
|
|
951
|
+
if scope not in SCOPES:
|
|
952
|
+
_fail('generation-authority-scope-invalid')
|
|
953
|
+
events = self._ledger.events(create=False)
|
|
954
|
+
matches = [e['payload'] for e in events if e['kind'] == 'request-prepared'
|
|
955
|
+
and e['payload']['requestId'] == expected_request_id]
|
|
956
|
+
if len(matches) != 1:
|
|
957
|
+
_fail('generation-authority-original-request-missing')
|
|
958
|
+
payload = matches[0]
|
|
959
|
+
if (payload['scope'] != scope or payload['identityEnrollmentId'] != identity.enrollment_id
|
|
960
|
+
or _b64decode_bytes(payload['intentBytes']) != exact_intent_bytes):
|
|
961
|
+
_fail('generation-authority-original-request-mismatch')
|
|
962
|
+
signed_payload = _b64decode_bytes(payload['signedPayloadBytes'])
|
|
963
|
+
request = InitialGenerationEnrollmentRequest(
|
|
964
|
+
_REQUEST_SEAL, self, request_id=expected_request_id, scope=scope,
|
|
965
|
+
effect_key=tuple(payload['effectKey']), intent_bytes=exact_intent_bytes,
|
|
966
|
+
intent_digest=_sha(exact_intent_bytes), payload_bytes=signed_payload,
|
|
967
|
+
identity=identity)
|
|
968
|
+
self._requests[id(request)] = request; self._requests_by_id[expected_request_id] = request
|
|
969
|
+
return request
|
|
970
|
+
|
|
971
|
+
def recover_approval(self, request: InitialGenerationEnrollmentRequest
|
|
972
|
+
) -> VerifiedInitialGenerationApproval:
|
|
973
|
+
request = self._require_request(request)
|
|
974
|
+
events = self._ledger.events(create=False)
|
|
975
|
+
matches = [event['payload'] for event in events
|
|
976
|
+
if event['kind'] == 'approval-verified'
|
|
977
|
+
and event['payload']['requestId'] == request.request_id]
|
|
978
|
+
if len(matches) != 1:
|
|
979
|
+
_fail('generation-authority-original-approval-missing')
|
|
980
|
+
envelope = _parse_canonical(_b64decode_bytes(matches[0]['envelopeBytes']))
|
|
981
|
+
return self.verify_approval(request, envelope)
|
|
982
|
+
|
|
983
|
+
def recover_reservation(self, request: InitialGenerationEnrollmentRequest,
|
|
984
|
+
expected_reservation_id: str
|
|
985
|
+
) -> InitialGenerationReservation:
|
|
986
|
+
request = self._require_request(request)
|
|
987
|
+
expected_reservation_id = _uuid(expected_reservation_id)
|
|
988
|
+
events = self._ledger.events(create=False)
|
|
989
|
+
replay = _replay(events)['requests'].get(request.request_id)
|
|
990
|
+
if replay is None or replay['reservation'] is None:
|
|
991
|
+
_fail('generation-authority-original-reservation-missing')
|
|
992
|
+
saved = replay['reservation']
|
|
993
|
+
if saved['reservationId'] != expected_reservation_id:
|
|
994
|
+
_fail('generation-authority-original-reservation-mismatch')
|
|
995
|
+
record = next(event for event in events
|
|
996
|
+
if event['kind'] == 'effect-reserved'
|
|
997
|
+
and event['payload']['requestId'] == request.request_id)
|
|
998
|
+
reservation = InitialGenerationReservation(
|
|
999
|
+
_RESERVATION_SEAL, self, request, expected_reservation_id, record['digest'])
|
|
1000
|
+
self._reservations[id(reservation)] = reservation
|
|
1001
|
+
self._prepared[request.request_id]['reservation'] = saved
|
|
1002
|
+
return reservation
|
|
1003
|
+
|
|
1004
|
+
def recover_identity(self, enrollment_id: str) -> InitialEnrollmentIdentity:
|
|
1005
|
+
enrollment_id = _uuid(enrollment_id)
|
|
1006
|
+
events = self._ledger.events(create=False)
|
|
1007
|
+
entries = [e['payload'] for e in events if e['kind'] == 'identity-allocated'
|
|
1008
|
+
and e['payload']['enrollmentId'] == enrollment_id]
|
|
1009
|
+
if len(entries) != 1:
|
|
1010
|
+
_fail('generation-authority-original-identity-missing')
|
|
1011
|
+
prior = self._identities.get(enrollment_id)
|
|
1012
|
+
if prior is not None:
|
|
1013
|
+
if prior.initial_epoch != entries[0]['initialEpoch']:
|
|
1014
|
+
_fail('generation-authority-original-identity-mismatch')
|
|
1015
|
+
return prior
|
|
1016
|
+
identity = InitialEnrollmentIdentity(
|
|
1017
|
+
_REQUEST_SEAL, self, self._context, enrollment_id, entries[0]['initialEpoch'])
|
|
1018
|
+
self._identities[enrollment_id] = identity
|
|
1019
|
+
return identity
|
|
1020
|
+
|
|
1021
|
+
def _require_identity(self, value: object) -> InitialEnrollmentIdentity:
|
|
1022
|
+
if (type(value) is not InitialEnrollmentIdentity or value._issuer is not self
|
|
1023
|
+
or value._context is not self._context
|
|
1024
|
+
or self._identities.get(value.enrollment_id) is not value
|
|
1025
|
+
or value.enrollment_id != self._context._logical_enrollment_id
|
|
1026
|
+
or value.initial_epoch != self._context._initial_epoch):
|
|
1027
|
+
_fail('generation-authority-identity-required')
|
|
1028
|
+
return value
|
|
1029
|
+
|
|
1030
|
+
def _require_request(self, value: object) -> InitialGenerationEnrollmentRequest:
|
|
1031
|
+
if (type(value) is not InitialGenerationEnrollmentRequest or value._issuer is not self
|
|
1032
|
+
or self._requests.get(id(value)) is not value):
|
|
1033
|
+
_fail('generation-authority-request-required')
|
|
1034
|
+
_uuid(value._request_id)
|
|
1035
|
+
identity = self._require_identity(value._identity)
|
|
1036
|
+
if (value._scope not in SCOPES or value._intent_digest != _sha(value._intent_bytes)
|
|
1037
|
+
or _parse_canonical(value._payload_bytes).get('scope') != value._scope
|
|
1038
|
+
or _parse_canonical(value._payload_bytes).get('requestId') != value._request_id
|
|
1039
|
+
or _parse_canonical(value._payload_bytes).get('contextDigest') != self._context_digest
|
|
1040
|
+
or _parse_canonical(value._payload_bytes).get('configurationDigest') != self._config_digest):
|
|
1041
|
+
_fail('generation-authority-request-mismatch')
|
|
1042
|
+
replay = _replay(self._ledger.events(create=False))
|
|
1043
|
+
saved = replay['requests'].get(value._request_id)
|
|
1044
|
+
if (saved is None
|
|
1045
|
+
or saved['payload']['identityEnrollmentId'] != identity.enrollment_id
|
|
1046
|
+
or saved['payload']['scope'] != value._scope
|
|
1047
|
+
or saved['payload']['intentDigest'] != value._intent_digest
|
|
1048
|
+
or _b64decode_bytes(saved['payload']['intentBytes']) != value._intent_bytes
|
|
1049
|
+
or _b64decode_bytes(saved['payload']['signedPayloadBytes']) != value._payload_bytes
|
|
1050
|
+
or tuple(saved['payload']['effectKey']) != value._effect_key):
|
|
1051
|
+
_fail('generation-authority-request-mismatch')
|
|
1052
|
+
return value
|
|
1053
|
+
|
|
1054
|
+
def _require_approval(self, value: object) -> VerifiedInitialGenerationApproval:
|
|
1055
|
+
if (type(value) is not VerifiedInitialGenerationApproval or value._issuer is not self
|
|
1056
|
+
or self._approvals.get(id(value)) is not value):
|
|
1057
|
+
_fail('generation-authority-approval-required')
|
|
1058
|
+
request = self._require_request(value._request)
|
|
1059
|
+
envelope = _parse_canonical(value._envelope_bytes)
|
|
1060
|
+
if (value._approval_digest != _sha(value._envelope_bytes)
|
|
1061
|
+
or envelope.get('payload') != _parse_canonical(request._payload_bytes)):
|
|
1062
|
+
_fail('generation-authority-approval-required')
|
|
1063
|
+
replay = _replay(self._ledger.events(create=False))['requests'].get(request.request_id)
|
|
1064
|
+
if (replay is None or replay['approvedEnvelope'] is None
|
|
1065
|
+
or _canonical(replay['approvedEnvelope']) != value._envelope_bytes):
|
|
1066
|
+
_fail('generation-authority-approval-required')
|
|
1067
|
+
return value
|
|
1068
|
+
|
|
1069
|
+
def _resolve_native_reservation(self, value: object,
|
|
1070
|
+
approval: VerifiedInitialGenerationApproval) -> InitialGenerationReservation:
|
|
1071
|
+
approval = self._require_approval(approval)
|
|
1072
|
+
if (self._context.public_reference.get('sourceTestOnly') is True
|
|
1073
|
+
or type(value) is not InitialGenerationReservation
|
|
1074
|
+
or value._issuer is not self or self._reservations.get(id(value)) is not value
|
|
1075
|
+
or value._request is not approval._request):
|
|
1076
|
+
_fail('generation-authority-native-reservation-unavailable')
|
|
1077
|
+
_fail('generation-authority-native-provider-unavailable')
|
|
1078
|
+
|
|
1079
|
+
def _resolve_native_outcome(self, outcome: object,
|
|
1080
|
+
reservation: InitialGenerationReservation) -> _VerifiedInitialGenerationOutcome:
|
|
1081
|
+
if (self._context.public_reference.get('sourceTestOnly') is True
|
|
1082
|
+
or type(outcome) is not _VerifiedInitialGenerationOutcome
|
|
1083
|
+
or outcome._issuer is not self or outcome._reservation is not reservation
|
|
1084
|
+
or outcome._source_test_only):
|
|
1085
|
+
_fail('generation-authority-native-outcome-unavailable')
|
|
1086
|
+
return outcome
|
|
1087
|
+
|
|
1088
|
+
def _record_source_test_outcome(self, reservation: InitialGenerationReservation,
|
|
1089
|
+
status: str, receipt_digest: str
|
|
1090
|
+
) -> dict[str, Any]:
|
|
1091
|
+
"""Test-only logical exercise; explicitly unavailable to production contexts."""
|
|
1092
|
+
if (self._context.public_reference.get('sourceTestOnly') is not True
|
|
1093
|
+
or type(reservation) is not InitialGenerationReservation
|
|
1094
|
+
or reservation._issuer is not self
|
|
1095
|
+
or self._reservations.get(id(reservation)) is not reservation
|
|
1096
|
+
or status not in ('confirmed', 'known-aborted')):
|
|
1097
|
+
_fail('generation-authority-source-test-only')
|
|
1098
|
+
_digest(receipt_digest)
|
|
1099
|
+
request = reservation._request
|
|
1100
|
+
payload = {'requestId': request.request_id,
|
|
1101
|
+
'reservationId': reservation.reservation_id,
|
|
1102
|
+
'status': status, 'receiptDigest': receipt_digest}
|
|
1103
|
+
record = self._ledger._append('effect-settled', payload)
|
|
1104
|
+
self._prepared[request.request_id]['settlement'] = payload
|
|
1105
|
+
return {'status': status, 'journalRecordDigest': record['digest'],
|
|
1106
|
+
'sourceTestOnly': True}
|
|
1107
|
+
|
|
1108
|
+
|