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.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,698 @@
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 fcntl
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import stat
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
+
25
+ AUTHORITY_PROFILE = 'umf.configured-generation-enrollment-authority/0.1'
26
+ CONFIG_PROFILE = AUTHORITY_PROFILE
27
+ SOURCE_POLICY_PROFILE = 'umf.existing-head-enrollment-policy/0.1'
28
+ TRUST_PROFILE = 'umf.generation-authority-trust-enrollment/0.1'
29
+ CONTEXT_PROFILE = 'umf.generation-authority-context/0.1'
30
+ APPROVAL_PROFILE = 'umf.initial-generation-enrollment-approval/0.1'
31
+ LEDGER_PROFILE = 'umf.initial-generation-enrollment-ledger/0.1'
32
+ PREPARE_INTENT_PROFILE = 'umf.initial-generation-enrollment-prepare/0.1'
33
+ ACTIVATE_INTENT_PROFILE = 'umf.initial-generation-enrollment-activate/0.1'
34
+ PREPARE_SCOPE = 'prepare-initial-enrollment'
35
+ ACTIVATE_SCOPE = 'activate-initial-enrollment'
36
+ SCOPES = (PREPARE_SCOPE, ACTIVATE_SCOPE)
37
+ PURPOSES = ('production', 'native-acceptance')
38
+ SIGNING_DOMAIN = b'umf.initial-generation-enrollment-approval/0.1\x00'
39
+
40
+ _UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
41
+ _HEX = re.compile(r'^[a-f0-9]{64}$')
42
+ _B64URL = re.compile(r'^[A-Za-z0-9_-]+$')
43
+ _MAX_CONFIG = 1_048_576
44
+ _MAX_REQUEST = 1_048_576
45
+ _MAX_LEDGER = 8 * 1024 * 1024
46
+ _MAX_RECORDS = 4096
47
+ _MAX_SAFE_INT = 9_007_199_254_740_991
48
+ _ROLE_FLAGS = ('canLogin', 'superuser', 'createDatabase', 'createRole',
49
+ 'replication', 'bypassRls', 'inherit')
50
+ _EVENT_KINDS = {'identity-allocated', 'request-prepared', 'approval-verified',
51
+ 'effect-reserved', 'effect-settled'}
52
+ _CONTEXT_EVENT_KINDS = {'context-birth-intent', 'context-birth-confirmed'}
53
+ _CONTEXT_SEAL = object()
54
+ _CONTEXT_REGISTRY_PROFILE = 'umf.generation-authority-context-registry/0.2'
55
+ _TRUST_SEAL = object()
56
+ _TRUST_ISSUER_ORIGINS: dict[int, tuple[object, str, object, object]] = {}
57
+ _REQUEST_SEAL = object()
58
+ _APPROVAL_SEAL = object()
59
+ _RESERVATION_SEAL = object()
60
+ _OUTCOME_SEAL = object()
61
+
62
+
63
+ class GenerationEnrollmentAuthorityError(RuntimeError):
64
+ """Fixed refusal without signed payloads, secrets, or filesystem paths."""
65
+
66
+ def __init__(self, code: str):
67
+ super().__init__(code)
68
+ self.code = code
69
+
70
+
71
+ class _ImmutableOpaque:
72
+ __slots__ = ()
73
+
74
+ def __setattr__(self, name: str, value: object) -> None:
75
+ if hasattr(self, name):
76
+ raise AttributeError('opaque authority values are immutable')
77
+ object.__setattr__(self, name, value)
78
+
79
+ def __delattr__(self, name: str) -> None:
80
+ raise AttributeError('opaque authority values are immutable')
81
+
82
+
83
+ def _fail(code: str) -> None:
84
+ raise GenerationEnrollmentAuthorityError(code)
85
+
86
+
87
+ def _closed(value: object, keys: set[str], code: str = 'generation-authority-invalid') -> dict[str, Any]:
88
+ if type(value) is not dict or set(value) != keys or any(type(key) is not str for key in value):
89
+ _fail(code)
90
+ return value
91
+
92
+
93
+ def _text(value: object, limit: int = 256) -> str:
94
+ if type(value) is not str or not value or '\x00' in value:
95
+ _fail('generation-authority-invalid')
96
+ try:
97
+ if len(value.encode('utf-8')) > limit:
98
+ _fail('generation-authority-invalid')
99
+ except UnicodeEncodeError:
100
+ _fail('generation-authority-invalid')
101
+ return value
102
+
103
+
104
+ def _uuid(value: object) -> str:
105
+ if type(value) is not str or not _UUID.fullmatch(value):
106
+ _fail('generation-authority-invalid')
107
+ try:
108
+ if str(uuid.UUID(value)) != value:
109
+ _fail('generation-authority-invalid')
110
+ except ValueError:
111
+ _fail('generation-authority-invalid')
112
+ return value
113
+
114
+
115
+ def _digest(value: object) -> str:
116
+ if type(value) is not str or not _HEX.fullmatch(value):
117
+ _fail('generation-authority-invalid')
118
+ return value
119
+
120
+
121
+ def _uint(value: object, minimum: int, maximum: int) -> int:
122
+ if type(value) is not int or not minimum <= value <= maximum:
123
+ _fail('generation-authority-invalid')
124
+ return value
125
+
126
+
127
+ def _json_copy(value: object, *, depth: int = 0, count: list[int] | None = None) -> object:
128
+ if count is None:
129
+ count = [0]
130
+ count[0] += 1
131
+ if count[0] > 100_000 or depth > 48:
132
+ _fail('generation-authority-capacity')
133
+ if value is None or type(value) is bool:
134
+ return value
135
+ if type(value) is int:
136
+ if abs(value) > _MAX_SAFE_INT:
137
+ _fail('generation-authority-invalid')
138
+ return value
139
+ if type(value) is str:
140
+ _text(value, _MAX_REQUEST)
141
+ return value
142
+ if type(value) is list:
143
+ if len(value) > 4096:
144
+ _fail('generation-authority-capacity')
145
+ return [_json_copy(item, depth=depth + 1, count=count) for item in value]
146
+ if type(value) is dict:
147
+ if len(value) > 128 or any(type(key) is not str or not key.isascii() for key in value):
148
+ _fail('generation-authority-invalid')
149
+ return {key: _json_copy(item, depth=depth + 1, count=count)
150
+ for key, item in value.items()}
151
+ _fail('generation-authority-invalid')
152
+
153
+
154
+ def _canonical(value: object) -> bytes:
155
+ try:
156
+ copied = _json_copy(value)
157
+ encoded = canonical_json(copied).encode('utf-8')
158
+ except GenerationEnrollmentAuthorityError:
159
+ raise
160
+ except (TypeError, ValueError, UnicodeError, RecursionError):
161
+ _fail('generation-authority-invalid')
162
+ if len(encoded) > _MAX_REQUEST:
163
+ _fail('generation-authority-capacity')
164
+ return encoded
165
+
166
+
167
+ def _parse_canonical(data: object, *, maximum: int = _MAX_REQUEST) -> dict[str, Any]:
168
+ if type(data) is not bytes or not 1 <= len(data) <= maximum:
169
+ _fail('generation-authority-capacity')
170
+
171
+ def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
172
+ parsed: dict[str, Any] = {}
173
+ for key, value in items:
174
+ if key in parsed:
175
+ _fail('generation-authority-invalid')
176
+ parsed[key] = value
177
+ return parsed
178
+
179
+ try:
180
+ value = json.loads(data.decode('utf-8'), object_pairs_hook=pairs,
181
+ parse_float=lambda _v: _fail('generation-authority-invalid'),
182
+ parse_constant=lambda _v: _fail('generation-authority-invalid'))
183
+ except GenerationEnrollmentAuthorityError:
184
+ raise
185
+ except (UnicodeError, ValueError, RecursionError):
186
+ _fail('generation-authority-invalid')
187
+ copied = _json_copy(value)
188
+ if type(copied) is not dict or _canonical(copied) != data:
189
+ _fail('generation-authority-noncanonical')
190
+ return copied
191
+
192
+
193
+ def _sha(data: bytes) -> str:
194
+ return hashlib.sha256(data).hexdigest()
195
+
196
+
197
+ def _b64decode(value: object, size: int) -> bytes:
198
+ if type(value) is not str or not _B64URL.fullmatch(value):
199
+ _fail('generation-authority-signature-invalid')
200
+ try:
201
+ raw = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
202
+ except (ValueError, TypeError):
203
+ _fail('generation-authority-signature-invalid')
204
+ if len(raw) != size or base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=') != value:
205
+ _fail('generation-authority-signature-invalid')
206
+ return raw
207
+
208
+
209
+ def _b64decode_bytes(value: object) -> bytes:
210
+ if type(value) is not str or not _B64URL.fullmatch(value):
211
+ _fail('generation-authority-ledger-corrupt')
212
+ try:
213
+ result = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
214
+ except (ValueError, TypeError):
215
+ _fail('generation-authority-ledger-corrupt')
216
+ if base64.urlsafe_b64encode(result).decode('ascii').rstrip('=') != value:
217
+ _fail('generation-authority-ledger-corrupt')
218
+ return result
219
+
220
+
221
+ def _target_custody(value: object) -> dict[str, Any]:
222
+ target = _closed(value, {'profile', 'custodianId', 'registrationId', 'resourceId',
223
+ 'incarnation', 'registrationDigest'})
224
+ if target['profile'] != 'umf.native-target-custody/0.1':
225
+ _fail('generation-authority-target-invalid')
226
+ for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
227
+ _uuid(target[key])
228
+ _digest(target['registrationDigest'])
229
+ return target
230
+
231
+
232
+ def _name(value: object) -> str:
233
+ # Native role identifiers may be quoted UTF-8 names; preserve their
234
+ # semantics while enforcing PostgreSQL's established 63-byte bound.
235
+ return _text(value, 63)
236
+
237
+
238
+ def _flags(value: object) -> dict[str, bool]:
239
+ flags = _closed(value, set(_ROLE_FLAGS))
240
+ if any(type(flags[key]) is not bool for key in _ROLE_FLAGS):
241
+ _fail('generation-authority-invalid')
242
+ return flags
243
+
244
+
245
+ def _membership_list(value: object) -> list[dict[str, Any]]:
246
+ if type(value) is not list or len(value) > 1024:
247
+ _fail('generation-authority-invalid')
248
+ result = []
249
+ seen_oids: set[int] = set()
250
+ seen_names: set[str] = set()
251
+ for entry in value:
252
+ item = _closed(entry, {'roleOid', 'roleName', 'inherit', 'set', 'admin'})
253
+ oid = _uint(item['roleOid'], 1, 4_294_967_295)
254
+ name = _name(item['roleName'])
255
+ if oid in seen_oids or name in seen_names:
256
+ _fail('generation-authority-invalid')
257
+ if any(type(item[key]) is not bool for key in ('inherit', 'set', 'admin')):
258
+ _fail('generation-authority-invalid')
259
+ seen_oids.add(oid); seen_names.add(name)
260
+ result.append({'roleOid': oid, 'roleName': name,
261
+ 'inherit': item['inherit'], 'set': item['set'], 'admin': item['admin']})
262
+ return result
263
+
264
+
265
+ def _config(value: object) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
266
+ config = _closed(value, {'profile', 'authorityId', 'policyRevision', 'purpose',
267
+ 'supervisorId', 'custodianId', 'providerId', 'installationId',
268
+ 'targetCustody', 'storeId', 'sourcePolicy', 'keys'})
269
+ if config['profile'] != CONFIG_PROFILE or config['purpose'] not in PURPOSES:
270
+ _fail('generation-authority-configuration-invalid')
271
+ _uuid(config['authorityId']); _uuid(config['supervisorId']); _uuid(config['custodianId'])
272
+ _uuid(config['providerId']); _text(config['installationId'], 256)
273
+ _text(config['policyRevision'], 128)
274
+ target = _target_custody(config['targetCustody'])
275
+ if target['custodianId'] != config['custodianId'] or config['storeId'] != config['providerId']:
276
+ _fail('generation-authority-configuration-invalid')
277
+ policy = _closed(config['sourcePolicy'], {'profile', 'approvedCohorts', 'approvedSubjects',
278
+ 'issuerProfile', 'maximumSubjects',
279
+ 'allowLegacyLoginConversion'})
280
+ if (policy['profile'] != SOURCE_POLICY_PROFILE
281
+ or policy['allowLegacyLoginConversion'] is not True):
282
+ _fail('generation-authority-configuration-invalid')
283
+ maximum_subjects = _uint(policy['maximumSubjects'], 1, 256)
284
+ _text(policy['issuerProfile'], 256)
285
+ cohorts = policy['approvedCohorts']
286
+ if type(cohorts) is not list or not 1 <= len(cohorts) <= 256:
287
+ _fail('generation-authority-configuration-invalid')
288
+ cohort_seen: set[bytes] = set()
289
+ normalized_cohorts = []
290
+ for cohort in cohorts:
291
+ item = _closed(cohort, {'sourceDigest', 'bundleDigest', 'sourceCohortDigest',
292
+ 'executionPolicyDigest'})
293
+ for key in ('sourceDigest', 'bundleDigest', 'sourceCohortDigest', 'executionPolicyDigest'):
294
+ _digest(item[key])
295
+ encoded = _canonical(item)
296
+ if encoded in cohort_seen:
297
+ _fail('generation-authority-configuration-invalid')
298
+ cohort_seen.add(encoded); normalized_cohorts.append(item)
299
+ subjects = policy['approvedSubjects']
300
+ if type(subjects) is not list or not 1 <= len(subjects) <= maximum_subjects:
301
+ _fail('generation-authority-configuration-invalid')
302
+ normalized_subjects = []
303
+ seen_subjects: set[tuple[int, str]] = set()
304
+ seen_subject_oids: set[int] = set()
305
+ seen_subject_names: set[str] = set()
306
+ for subject in subjects:
307
+ item = _closed(subject, {'subject', 'audience', 'ownershipReceiptDigest',
308
+ 'membershipsDigest', 'flagsDigest'})
309
+ ref = _closed(item['subject'], {'oid', 'name'})
310
+ oid = _uint(ref['oid'], 1, 4_294_967_295); name = _name(ref['name'])
311
+ if ((oid, name) in seen_subjects or oid in seen_subject_oids
312
+ or name in seen_subject_names or item['audience'] not in ('person', 'batch')):
313
+ _fail('generation-authority-configuration-invalid')
314
+ seen_subjects.add((oid, name)); seen_subject_oids.add(oid); seen_subject_names.add(name)
315
+ for key in ('ownershipReceiptDigest', 'membershipsDigest', 'flagsDigest'):
316
+ _digest(item[key])
317
+ normalized_subjects.append({'subject': {'oid': oid, 'name': name},
318
+ 'audience': item['audience'],
319
+ 'ownershipReceiptDigest': item['ownershipReceiptDigest'],
320
+ 'membershipsDigest': item['membershipsDigest'],
321
+ 'flagsDigest': item['flagsDigest']})
322
+ if len(normalized_subjects) > maximum_subjects:
323
+ _fail('generation-authority-configuration-invalid')
324
+ keys = config['keys']
325
+ if type(keys) is not list or not 1 <= len(keys) <= 32:
326
+ _fail('generation-authority-configuration-invalid')
327
+ keys_by_id: dict[str, dict[str, Any]] = {}
328
+ scope_order = {scope: index for index, scope in enumerate(SCOPES)}
329
+ for key in keys:
330
+ item = _closed(key, {'keyId', 'publicKey', 'principalId', 'scopes'})
331
+ key_id = _text(item['keyId'], 128); _text(item['principalId'], 128)
332
+ public = _b64decode(item['publicKey'], 32)
333
+ scopes = item['scopes']
334
+ if (type(scopes) is not list or not scopes or len(scopes) > 2
335
+ or any(type(s) is not str or s not in SCOPES for s in scopes)
336
+ or len(set(scopes)) != len(scopes)
337
+ or scopes != sorted(scopes, key=scope_order.__getitem__)):
338
+ _fail('generation-authority-configuration-invalid')
339
+ if key_id in keys_by_id:
340
+ _fail('generation-authority-configuration-invalid')
341
+ keys_by_id[key_id] = {'keyId': key_id, 'publicKeyBytes': public,
342
+ 'principalId': item['principalId'], 'scopes': tuple(scopes)}
343
+ normalized = _json_copy(config)
344
+ if len(_canonical(normalized)) > _MAX_CONFIG:
345
+ _fail('generation-authority-capacity')
346
+ # Force full bounded validation while retaining the original exact config.
347
+ return normalized, keys_by_id
348
+
349
+
350
+ def _validate_subjects(value: object, policy: dict[str, Any]) -> list[dict[str, Any]]:
351
+ if type(value) is not list or not 1 <= len(value) <= policy['maximumSubjects']:
352
+ _fail('generation-authority-intent-invalid')
353
+ approved = policy['approvedSubjects']
354
+ if len(value) != len(approved):
355
+ _fail('generation-authority-subject-coverage-mismatch')
356
+ seen_oid: set[int] = set(); seen_name: set[str] = set(); all_names: set[str] = set()
357
+ result = []
358
+ edge_count = 0
359
+ for index, raw in enumerate(value):
360
+ item = _closed(raw, {'subject', 'audience', 'observedFlags', 'memberships',
361
+ 'ownershipReceiptDigest', 'newLoginName'},
362
+ 'generation-authority-intent-invalid')
363
+ sub = _closed(item['subject'], {'oid', 'name'}, 'generation-authority-intent-invalid')
364
+ oid = _uint(sub['oid'], 1, 4_294_967_295); name = _name(sub['name'])
365
+ if oid in seen_oid or name in seen_name:
366
+ _fail('generation-authority-intent-invalid')
367
+ seen_oid.add(oid); seen_name.add(name); all_names.add(name)
368
+ if item['audience'] not in ('person', 'batch'):
369
+ _fail('generation-authority-intent-invalid')
370
+ flags = _flags(item['observedFlags'])
371
+ if not flags['canLogin'] or any(flags[k] for k in _ROLE_FLAGS if k not in ('canLogin', 'inherit')):
372
+ _fail('generation-authority-subject-flags-mismatch')
373
+ memberships = _membership_list(item['memberships'])
374
+ edge_count += len(memberships)
375
+ if edge_count > 1024:
376
+ _fail('generation-authority-capacity')
377
+ ownership = _digest(item['ownershipReceiptDigest'])
378
+ new_login = _name(item['newLoginName'])
379
+ if new_login in all_names or new_login in {r['newLoginName'] for r in result}:
380
+ _fail('generation-authority-intent-invalid')
381
+ expected = approved[index]
382
+ subject_ref = {'oid': oid, 'name': name}
383
+ if (expected['subject'] != subject_ref or expected['audience'] != item['audience']
384
+ or expected['ownershipReceiptDigest'] != ownership
385
+ or expected['membershipsDigest'] != _sha(_canonical(memberships))
386
+ or expected['flagsDigest'] != _sha(_canonical(flags))):
387
+ _fail('generation-authority-subject-coverage-mismatch')
388
+ result.append({'subject': subject_ref, 'audience': item['audience'],
389
+ 'observedFlags': flags, 'memberships': memberships,
390
+ 'ownershipReceiptDigest': ownership, 'newLoginName': new_login})
391
+ if all_names.intersection(r['newLoginName'] for r in result):
392
+ _fail('generation-authority-intent-invalid')
393
+ return result
394
+
395
+
396
+ def _validate_principals(value: object, prepared: dict[str, Any]) -> list[dict[str, Any]]:
397
+ if type(value) is not list or len(value) != len(prepared['subjects']):
398
+ _fail('generation-authority-intent-invalid')
399
+ result = []
400
+ seen_login: set[int] = set(); seen_subject: set[int] = set()
401
+ for i, raw in enumerate(value):
402
+ item = _closed(raw, {'login', 'subject', 'audience', 'issuerProfile',
403
+ 'issuerReceiptDigest', 'ownershipReceiptDigest', 'memberships'},
404
+ 'generation-authority-intent-invalid')
405
+ roles = {}
406
+ for key in ('login', 'subject'):
407
+ role = _closed(item[key], {'oid', 'name'}, 'generation-authority-intent-invalid')
408
+ roles[key] = {'oid': _uint(role['oid'], 1, 4_294_967_295),
409
+ 'name': _name(role['name'])}
410
+ if roles['login']['oid'] in seen_login or roles['subject']['oid'] in seen_subject:
411
+ _fail('generation-authority-intent-invalid')
412
+ seen_login.add(roles['login']['oid']); seen_subject.add(roles['subject']['oid'])
413
+ original = prepared['subjects'][i]
414
+ if (roles['subject'] != original['subject']
415
+ or roles['login']['name'] != original['newLoginName']
416
+ or item['audience'] != original['audience']):
417
+ _fail('generation-authority-intent-invalid')
418
+ issuer = _text(item['issuerProfile'], 256)
419
+ issuer_receipt = _digest(item['issuerReceiptDigest'])
420
+ ownership = _digest(item['ownershipReceiptDigest'])
421
+ memberships = _membership_list(item['memberships'])
422
+ if (issuer != prepared['issuerProfile']
423
+ or ownership != original['ownershipReceiptDigest']
424
+ or memberships != original['memberships']):
425
+ _fail('generation-authority-intent-invalid')
426
+ result.append({'login': roles['login'], 'subject': roles['subject'],
427
+ 'audience': item['audience'], 'issuerProfile': issuer,
428
+ 'issuerReceiptDigest': issuer_receipt,
429
+ 'ownershipReceiptDigest': ownership, 'memberships': memberships})
430
+ return result
431
+
432
+
433
+ class _Ledger:
434
+ """Bound append-only ledger; existing-history reads never create files."""
435
+
436
+ __slots__ = ('_authority_id', '_config_digest', '_context_digest', '_path', '_purpose')
437
+
438
+ def __init__(self, path: str | os.PathLike[str], authority_id: str,
439
+ config_digest: str, context_digest: str, purpose: str):
440
+ raw = os.fspath(path)
441
+ if type(raw) is not str or not raw.startswith('/') or os.path.normpath(raw) != raw:
442
+ _fail('generation-authority-ledger-path-invalid')
443
+ self._path = Path(raw)
444
+ self._authority_id = authority_id
445
+ self._config_digest = config_digest
446
+ self._context_digest = context_digest
447
+ self._purpose = purpose
448
+
449
+ @property
450
+ def path(self) -> Path:
451
+ return self._path
452
+
453
+ @contextmanager
454
+ def _locked(self, *, create: bool, birth: bool = False, exclusive: bool = False):
455
+ # The lock and ledger must already live in an owned private directory.
456
+ parent = self._path.parent
457
+ try:
458
+ pstat = parent.lstat()
459
+ except OSError:
460
+ _fail('generation-authority-ledger-unavailable')
461
+ if (not stat.S_ISDIR(pstat.st_mode) or stat.S_ISLNK(pstat.st_mode)
462
+ or pstat.st_uid != os.geteuid() or pstat.st_mode & 0o077):
463
+ _fail('generation-authority-ledger-path-invalid')
464
+ lock_path = self._path.with_name(self._path.name + '.lock')
465
+ if create and not birth and (self._path.exists() or lock_path.exists()):
466
+ _fail('generation-authority-original-history-missing')
467
+ flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
468
+ if create:
469
+ flags |= os.O_CREAT
470
+ try:
471
+ lock_fd = os.open(lock_path, flags, 0o600)
472
+ except OSError:
473
+ _fail('generation-authority-ledger-unavailable')
474
+ try:
475
+ st = os.fstat(lock_fd)
476
+ if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
477
+ or st.st_nlink != 1 or st.st_mode & 0o077):
478
+ _fail('generation-authority-ledger-path-invalid')
479
+ fcntl.flock(lock_fd, fcntl.LOCK_EX if create or exclusive else fcntl.LOCK_SH)
480
+ yield lock_fd
481
+ finally:
482
+ os.close(lock_fd)
483
+
484
+ def _read(self, *, create: bool) -> list[dict[str, Any]]:
485
+ with self._locked(create=create):
486
+ return self._read_locked(create=create)
487
+
488
+ def _read_locked(self, *, create: bool) -> list[dict[str, Any]]:
489
+ flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)
490
+ try:
491
+ fd = os.open(self._path, flags)
492
+ except FileNotFoundError:
493
+ if not create:
494
+ _fail('generation-authority-original-history-missing')
495
+ fd = os.open(self._path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
496
+ | getattr(os, 'O_NOFOLLOW', 0), 0o600)
497
+ os.fsync(fd)
498
+ os.close(fd)
499
+ parent_fd = os.open(self._path.parent, os.O_RDONLY)
500
+ try:
501
+ os.fsync(parent_fd)
502
+ finally:
503
+ os.close(parent_fd)
504
+ return []
505
+ except OSError:
506
+ _fail('generation-authority-ledger-unavailable')
507
+ try:
508
+ st = os.fstat(fd)
509
+ if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
510
+ or st.st_nlink != 1 or st.st_mode & 0o077
511
+ or st.st_size > _MAX_LEDGER):
512
+ _fail('generation-authority-ledger-path-invalid')
513
+ chunks = []
514
+ while True:
515
+ block = os.read(fd, 65536)
516
+ if not block:
517
+ break
518
+ chunks.append(block)
519
+ data = b''.join(chunks)
520
+ finally:
521
+ os.close(fd)
522
+ if not data:
523
+ return []
524
+ if not data.endswith(b'\n'):
525
+ _fail('generation-authority-ledger-corrupt')
526
+ try:
527
+ records = [_parse_canonical(line, maximum=_MAX_LEDGER)
528
+ for line in data.splitlines()]
529
+ except GenerationEnrollmentAuthorityError:
530
+ _fail('generation-authority-ledger-corrupt')
531
+ if len(records) > _MAX_RECORDS:
532
+ _fail('generation-authority-ledger-capacity')
533
+ previous = '0' * 64
534
+ for sequence, record in enumerate(records, 1):
535
+ _closed(record, {'profile', 'authorityId', 'configurationDigest',
536
+ 'contextDigest', 'purpose', 'sequence', 'previousDigest',
537
+ 'kind', 'payload', 'digest'},
538
+ 'generation-authority-ledger-corrupt')
539
+ digest = record.pop('digest')
540
+ if (record['profile'] != LEDGER_PROFILE
541
+ or record['authorityId'] != self._authority_id
542
+ or record['configurationDigest'] != self._config_digest
543
+ or record['contextDigest'] != self._context_digest
544
+ or record['purpose'] != self._purpose
545
+ or record['sequence'] != sequence or record['previousDigest'] != previous
546
+ or record['kind'] not in _EVENT_KINDS
547
+ or digest != _sha(_canonical(record))):
548
+ _fail('generation-authority-ledger-corrupt')
549
+ record['digest'] = digest
550
+ previous = digest
551
+ _replay(records)
552
+ return records
553
+
554
+ def _append(self, kind: str, payload: dict[str, Any]) -> dict[str, Any]:
555
+ # The read/validate/append sequence must be exclusive across processes;
556
+ # a shared lock can let two effect-key contenders both validate empty history.
557
+ with self._locked(create=False, exclusive=True):
558
+ records = self._read_locked(create=False)
559
+ return self._append_locked(records, kind, payload)
560
+
561
+ def _initialize_identity(self, enrollment_id: str, initial_epoch: str) -> None:
562
+ """Settle only the exact IDs in a durable pending context-birth intent."""
563
+ enrollment_id = _uuid(enrollment_id); initial_epoch = _uuid(initial_epoch)
564
+ with self._locked(create=True, birth=True):
565
+ records = self._read_locked(create=True)
566
+ identities = [record for record in records
567
+ if record['kind'] == 'identity-allocated']
568
+ expected = {'enrollmentId': enrollment_id, 'initialEpoch': initial_epoch}
569
+ if identities:
570
+ if len(identities) != 1 or identities[0]['payload'] != expected:
571
+ _fail('generation-authority-ledger-birth-id-mismatch')
572
+ return
573
+ if records:
574
+ _fail('generation-authority-ledger-corrupt')
575
+ self._append_locked(records, 'identity-allocated', expected)
576
+
577
+ def _append_locked(self, records: list[dict[str, Any]], kind: str,
578
+ payload: dict[str, Any]) -> dict[str, Any]:
579
+ if len(records) >= _MAX_RECORDS:
580
+ _fail('generation-authority-ledger-capacity')
581
+ previous = records[-1]['digest'] if records else '0' * 64
582
+ record = {'profile': LEDGER_PROFILE, 'authorityId': self._authority_id,
583
+ 'configurationDigest': self._config_digest,
584
+ 'contextDigest': self._context_digest, 'purpose': self._purpose,
585
+ 'sequence': len(records) + 1, 'previousDigest': previous,
586
+ 'kind': kind, 'payload': _json_copy(payload)}
587
+ record['digest'] = _sha(_canonical(record))
588
+ encoded = _canonical(record) + b'\n'
589
+ if sum(len(_canonical(item)) + 1 for item in records) + len(encoded) > _MAX_LEDGER:
590
+ _fail('generation-authority-ledger-capacity')
591
+ # Validate the full state transition before durable append. This
592
+ # rejects duplicate effect keys atomically across processes.
593
+ _replay([*records, record])
594
+ try:
595
+ fd = os.open(self._path, os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0))
596
+ except OSError:
597
+ _fail('generation-authority-ledger-write-failed')
598
+ try:
599
+ st = os.fstat(fd)
600
+ if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
601
+ or st.st_nlink != 1 or st.st_mode & 0o077):
602
+ _fail('generation-authority-ledger-path-invalid')
603
+ view = memoryview(encoded)
604
+ while view:
605
+ written = os.write(fd, view)
606
+ if written <= 0:
607
+ _fail('generation-authority-ledger-write-failed')
608
+ view = view[written:]
609
+ os.fsync(fd)
610
+ except OSError:
611
+ _fail('generation-authority-ledger-write-failed')
612
+ finally:
613
+ os.close(fd)
614
+ return record
615
+
616
+ def events(self, *, create: bool = False) -> list[dict[str, Any]]:
617
+ return self._read(create=create)
618
+
619
+
620
+ def _replay(records: list[dict[str, Any]]) -> dict[str, Any]:
621
+ identities: dict[str, dict[str, Any]] = {}
622
+ requests: dict[str, dict[str, Any]] = {}
623
+ effect_keys: dict[tuple[str, str, str], str] = {}
624
+ for record in records:
625
+ kind, payload = record['kind'], record['payload']
626
+ if type(payload) is not dict:
627
+ _fail('generation-authority-ledger-corrupt')
628
+ if kind == 'identity-allocated':
629
+ _closed(payload, {'enrollmentId', 'initialEpoch'}, 'generation-authority-ledger-corrupt')
630
+ enrollment_id = _uuid(payload['enrollmentId']); epoch = _uuid(payload['initialEpoch'])
631
+ if enrollment_id in identities or any(v['initialEpoch'] == epoch for v in identities.values()):
632
+ _fail('generation-authority-ledger-corrupt')
633
+ identities[enrollment_id] = {'initialEpoch': epoch}
634
+ elif kind == 'request-prepared':
635
+ _closed(payload, {'requestId', 'scope', 'effectKey', 'intentBytes', 'intentDigest',
636
+ 'signedPayloadBytes', 'identityEnrollmentId'},
637
+ 'generation-authority-ledger-corrupt')
638
+ request_id = _uuid(payload['requestId'])
639
+ if request_id in requests or payload['scope'] not in SCOPES:
640
+ _fail('generation-authority-ledger-corrupt')
641
+ key = payload['effectKey']
642
+ if (type(key) is not list or len(key) != 3 or key[0] != payload['scope']
643
+ or not all(type(x) is str for x in key)):
644
+ _fail('generation-authority-ledger-corrupt')
645
+ effect_key = tuple(key)
646
+ if effect_key in effect_keys:
647
+ _fail('generation-authority-ledger-corrupt')
648
+ intent_bytes = _b64decode_bytes(payload['intentBytes'])
649
+ signed_bytes = _b64decode_bytes(payload['signedPayloadBytes'])
650
+ if _sha(intent_bytes) != payload['intentDigest']:
651
+ _fail('generation-authority-ledger-corrupt')
652
+ _parse_canonical(intent_bytes)
653
+ signed_payload = _parse_canonical(signed_bytes)
654
+ if (signed_payload.get('requestId') != request_id
655
+ or signed_payload.get('scope') != payload['scope']):
656
+ _fail('generation-authority-ledger-corrupt')
657
+ identity_id = payload['identityEnrollmentId']
658
+ if identity_id is not None and identity_id not in identities:
659
+ _fail('generation-authority-ledger-corrupt')
660
+ requests[request_id] = {'payload': payload, 'signedPayload': signed_payload,
661
+ 'approvedEnvelope': None, 'reservation': None,
662
+ 'settlement': None}
663
+ effect_keys[effect_key] = request_id
664
+ elif kind == 'approval-verified':
665
+ _closed(payload, {'requestId', 'envelopeBytes', 'approvalDigest'},
666
+ 'generation-authority-ledger-corrupt')
667
+ request = requests.get(_uuid(payload['requestId']))
668
+ envelope_bytes = _b64decode_bytes(payload['envelopeBytes'])
669
+ if request is None or request['approvedEnvelope'] is not None:
670
+ _fail('generation-authority-ledger-corrupt')
671
+ if _sha(envelope_bytes) != payload['approvalDigest']:
672
+ _fail('generation-authority-ledger-corrupt')
673
+ request['approvedEnvelope'] = _parse_canonical(envelope_bytes)
674
+ request['approvalDigest'] = payload['approvalDigest']
675
+ elif kind == 'effect-reserved':
676
+ _closed(payload, {'requestId', 'reservationId', 'approvalDigest', 'effectKey'},
677
+ 'generation-authority-ledger-corrupt')
678
+ request = requests.get(_uuid(payload['requestId']))
679
+ if (request is None or request['approvedEnvelope'] is None
680
+ or request['reservation'] is not None
681
+ or payload['approvalDigest'] != request.get('approvalDigest')
682
+ or tuple(payload['effectKey']) != tuple(request['payload']['effectKey'])):
683
+ _fail('generation-authority-ledger-corrupt')
684
+ _uuid(payload['reservationId'])
685
+ request['reservation'] = payload
686
+ elif kind == 'effect-settled':
687
+ _closed(payload, {'requestId', 'reservationId', 'status', 'receiptDigest'},
688
+ 'generation-authority-ledger-corrupt')
689
+ request = requests.get(_uuid(payload['requestId']))
690
+ if (request is None or request['reservation'] is None or request['settlement'] is not None
691
+ or payload['reservationId'] != request['reservation']['reservationId']
692
+ or payload['status'] not in ('confirmed', 'known-aborted')):
693
+ _fail('generation-authority-ledger-corrupt')
694
+ _digest(payload['receiptDigest'])
695
+ request['settlement'] = payload
696
+ return {'identities': identities, 'requests': requests, 'effectKeys': effect_keys}
697
+
698
+