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,1251 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Native-free supervisor journal profile codec."""
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import posixpath
9
+ import re
10
+ from typing import Any
11
+
12
+ MAX_EVENTS = 4096
13
+ MAX_BYTES = 8 * 1024 * 1024
14
+ LEGACY_PROFILE = 'umf.local-postgresql-supervisor-journal/0.1'
15
+ JOURNAL_PROFILE_02 = 'umf.local-postgresql-owner-journal/0.2'
16
+ DEFINITION_PROFILE = 'umf.supervisor-journal-definition/0.1'
17
+ BIRTH_PROFILE = 'umf.original-supervisor-journal-birth/0.1'
18
+ ANCHOR_PROFILE = 'umf.original-supervisor-journal-anchor/0.1'
19
+ CONTEXT_METADATA_PROFILE = 'umf.owner-context-journal-metadata/0.1'
20
+ ENROLLMENT_03 = 'umf.local-owner-bootstrap-enrollment/0.3'
21
+ ENROLLMENT_05 = 'umf.local-owner-bootstrap-enrollment/0.5'
22
+ TARGET_CUSTODY_JOURNAL_PROFILE_02 = 'umf.local-target-custody-journal/0.2'
23
+ TARGET_CUSTODY_BIRTH_PROFILE = 'umf.original-target-custody-journal-birth/0.1'
24
+ TARGET_CUSTODY_DEFINITION_PROFILE = 'umf.target-custody-journal-definition/0.1'
25
+ TARGET_CUSTODY_METADATA_PROFILE_02 = 'umf.owner-context-journal-metadata/0.2'
26
+ TARGET_CUSTODY_EVENT_KINDS = (
27
+ 'registration-intent', 'registration-observation', 'registration-confirmed',
28
+ 'epoch-provision-reserved', 'epoch-provision-observation', 'epoch-provision-confirmed',
29
+ 'transition-reserved', 'transition-observation', 'transition-confirmed',
30
+ 'originals-store-reserved', 'originals-store-observation', 'originals-store-confirmed',
31
+ )
32
+ _HEX = re.compile(r'^[a-f0-9]{64}$')
33
+ _UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
34
+
35
+ class SupervisorJournalCodecError(ValueError):
36
+ def __init__(self, code: str):
37
+ super().__init__(code); self.code = code
38
+
39
+ def canonical(value: Any) -> bytes:
40
+ stack = [(value, 0)]
41
+ count = 0
42
+ while stack:
43
+ item, depth = stack.pop()
44
+ count += 1
45
+ if count > 100_000 or depth > 64:
46
+ raise SupervisorJournalCodecError('supervisor-journal-capacity')
47
+ if item is None or type(item) is bool:
48
+ continue
49
+ if type(item) is int:
50
+ if abs(item) > 9_007_199_254_740_991:
51
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
52
+ elif type(item) is str:
53
+ try:
54
+ item.encode('utf-8')
55
+ except UnicodeEncodeError:
56
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
57
+ if '\x00' in item:
58
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
59
+ elif type(item) is list:
60
+ if len(item) > MAX_EVENTS:
61
+ raise SupervisorJournalCodecError('supervisor-journal-capacity')
62
+ stack.extend((child, depth + 1) for child in item)
63
+ elif type(item) is dict:
64
+ if any(type(key) is not str or not key.isascii() for key in item):
65
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
66
+ stack.extend((key, depth + 1) for key in item)
67
+ stack.extend((child, depth + 1) for child in item.values())
68
+ else:
69
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
70
+ try:
71
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8')
72
+ except (TypeError, ValueError, UnicodeError, RecursionError):
73
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
74
+
75
+ def digest(value: Any) -> str:
76
+ return hashlib.sha256(canonical(value)).hexdigest()
77
+
78
+ _digest = digest
79
+
80
+
81
+ def _validate_native_evidence_bytes(raw: bytes) -> dict[str, Any]:
82
+ """Require canonical JSON-object bytes, without claiming native authority."""
83
+ def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
84
+ result: dict[str, Any] = {}
85
+ for key, value in items:
86
+ if key in result:
87
+ raise SupervisorJournalCodecError(
88
+ 'supervisor-journal-root-observation-invalid')
89
+ result[key] = value
90
+ return result
91
+
92
+ def reject_number(_value: str) -> Any:
93
+ raise SupervisorJournalCodecError(
94
+ 'supervisor-journal-root-observation-invalid')
95
+
96
+ try:
97
+ value = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs,
98
+ parse_float=reject_number, parse_constant=reject_number)
99
+ except SupervisorJournalCodecError:
100
+ raise
101
+ except (UnicodeError, ValueError, RecursionError):
102
+ raise SupervisorJournalCodecError(
103
+ 'supervisor-journal-root-observation-invalid') from None
104
+ try:
105
+ canonical_bytes = canonical(value) if type(value) is dict else None
106
+ except SupervisorJournalCodecError:
107
+ raise SupervisorJournalCodecError(
108
+ 'supervisor-journal-root-observation-invalid') from None
109
+ if canonical_bytes != raw:
110
+ raise SupervisorJournalCodecError(
111
+ 'supervisor-journal-root-observation-invalid')
112
+ return value
113
+
114
+ def validate_definition(value: object) -> dict[str, Any]:
115
+ expected = {'profile': DEFINITION_PROFILE, 'journalProfile': JOURNAL_PROFILE_02,
116
+ 'physicalEvents': 'umf.supervisor-physical-events/0.2',
117
+ 'rootEvents': 'umf.supervisor-generation-root-events/0.1',
118
+ 'originalsEvents': 'umf.supervisor-originals-store-events/0.1',
119
+ 'ingressEvents': None, 'applicationEvents': None}
120
+ if type(value) is not dict or value != expected or set(value) != set(expected):
121
+ raise SupervisorJournalCodecError('supervisor-journal-definition-unsupported')
122
+ return dict(value)
123
+
124
+ def validate_metadata(value: object) -> dict[str, Any]:
125
+ keys = {'profile', 'enrollmentProfile', 'ownerContextProfile', 'ownerBootstrapContextDigest', 'supervisorJournal'}
126
+ fresh_keys = keys | {'targetCustodyJournal'}
127
+ if (type(value) is not dict or set(value) not in (keys, fresh_keys)
128
+ or value.get('profile') not in (CONTEXT_METADATA_PROFILE, TARGET_CUSTODY_METADATA_PROFILE_02)):
129
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
130
+ fresh = value['profile'] == TARGET_CUSTODY_METADATA_PROFILE_02
131
+ if fresh != (set(value) == fresh_keys) or (fresh and value.get('enrollmentProfile') != ENROLLMENT_05):
132
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
133
+ if value['ownerContextProfile'] != 'umf.local-owner-bootstrap-context/0.3' or type(value['ownerBootstrapContextDigest']) is not str or not _HEX.fullmatch(value['ownerBootstrapContextDigest']):
134
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
135
+ descriptor = value['supervisorJournal']
136
+ if value['enrollmentProfile'] in ('umf.local-owner-bootstrap-enrollment/0.1', 'umf.local-owner-bootstrap-enrollment/0.2'):
137
+ if descriptor is not None:
138
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
139
+ elif value['enrollmentProfile'] in (ENROLLMENT_03, ENROLLMENT_05):
140
+ names = {'birthDigest', 'journalProfile', 'journalId', 'definitionDigest'}
141
+ if (type(descriptor) is not dict or set(descriptor) != names or descriptor.get('journalProfile') != JOURNAL_PROFILE_02 or type(descriptor.get('journalId')) is not str or not _UUID.fullmatch(descriptor['journalId']) or any(type(descriptor.get(k)) is not str or not _HEX.fullmatch(descriptor[k]) for k in ('birthDigest', 'definitionDigest'))):
142
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
143
+ else:
144
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
145
+ if fresh:
146
+ descriptor = value['targetCustodyJournal']
147
+ names = {'birthDigest', 'journalProfile', 'definitionDigest'}
148
+ if (type(descriptor) is not dict or set(descriptor) != names
149
+ or descriptor.get('journalProfile') != TARGET_CUSTODY_JOURNAL_PROFILE_02
150
+ or any(type(descriptor.get(k)) is not str or not _HEX.fullmatch(descriptor[k])
151
+ for k in ('birthDigest', 'definitionDigest'))):
152
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
153
+ return json.loads(canonical(value))
154
+
155
+
156
+ def validate_target_custody_birth(value: object, *, enrollment: dict[str, Any]) -> dict[str, Any]:
157
+ """Validate the fixed fresh external-journal birth bound by enrollment 0.5."""
158
+ keys = {'profile', 'journalProfile', 'custodianId', 'supervisorId', 'path',
159
+ 'lockPath', 'definition', 'definitionDigest', 'initialHeaderDigest'}
160
+ if (type(value) is not dict or set(value) != keys
161
+ or value.get('profile') != TARGET_CUSTODY_BIRTH_PROFILE
162
+ or value.get('journalProfile') != TARGET_CUSTODY_JOURNAL_PROFILE_02
163
+ or type(enrollment) is not dict or enrollment.get('profile') != ENROLLMENT_05):
164
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
165
+ context = enrollment.get('context')
166
+ native = enrollment.get('nativeProfile')
167
+ if (type(context) is not dict or type(native) is not dict
168
+ or value.get('custodianId') != context.get('custodianId')
169
+ or value.get('supervisorId') != context.get('supervisorId')
170
+ or value.get('custodianId') != native.get('custodianId')
171
+ or value.get('supervisorId') != native.get('supervisorId')):
172
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
173
+ control_home = native.get('controlHome')
174
+ if (type(control_home) is not str or not control_home.startswith('/')
175
+ or '\x00' in control_home or control_home.rstrip('/') != control_home
176
+ or posixpath.normpath(control_home) != control_home):
177
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
178
+ path = control_home + '/target-custody.json'
179
+ if (value.get('path') != path
180
+ or value.get('lockPath') != path + '.lock'):
181
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
182
+ definition = {'profile': TARGET_CUSTODY_DEFINITION_PROFILE,
183
+ 'journalProfile': TARGET_CUSTODY_JOURNAL_PROFILE_02,
184
+ 'eventKinds': list(TARGET_CUSTODY_EVENT_KINDS)}
185
+ if value.get('definition') != definition:
186
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
187
+ definition_digest = hashlib.sha256(canonical(definition)).hexdigest()
188
+ initial = {'profile': TARGET_CUSTODY_JOURNAL_PROFILE_02,
189
+ 'custodianId': value['custodianId'], 'sequence': 0,
190
+ 'headDigest': '0' * 64, 'events': []}
191
+ initial_digest = hashlib.sha256(canonical(initial)).hexdigest()
192
+ if (value.get('definitionDigest') != definition_digest
193
+ or value.get('initialHeaderDigest') != initial_digest):
194
+ raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
195
+ return json.loads(canonical(value))
196
+
197
+ def expected_paths(control_home: object, supervisor_id: object) -> tuple[str, str]:
198
+ if type(control_home) is not str or not control_home.startswith('/') or '\x00' in control_home or type(supervisor_id) is not str or not _UUID.fullmatch(supervisor_id):
199
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
200
+ basename = 'owner-journal-' + supervisor_id.replace('-', '') + '.json'
201
+ path = control_home.rstrip('/') + '/' + basename
202
+ return path, path + '.lock'
203
+
204
+ def initial_record(*, supervisor_id: str, journal_id: str, definition_digest: str, anchor_digest: str) -> bytes:
205
+ return canonical({'profile': JOURNAL_PROFILE_02, 'supervisorId': supervisor_id, 'journalId': journal_id, 'definitionDigest': definition_digest, 'anchorDigest': anchor_digest, 'sequence': 0, 'headDigest': anchor_digest, 'events': []})
206
+
207
+ def validate_birth(value: object, *, enrollment: dict[str, Any],
208
+ configuration_digest: str, generation_root_policy_digest: str | None) -> dict[str, Any]:
209
+ keys = {'profile', 'journalProfile', 'journalId', 'supervisorId', 'definition',
210
+ 'definitionDigest', 'path', 'lockPath', 'anchorDigest', 'initialHeaderDigest'}
211
+ if type(value) is not dict or set(value) != keys:
212
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
213
+ if value['profile'] != BIRTH_PROFILE or value['journalProfile'] != JOURNAL_PROFILE_02:
214
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
215
+ journal_id, supervisor_id = value['journalId'], value['supervisorId']
216
+ if (type(journal_id) is not str or not _UUID.fullmatch(journal_id)
217
+ or type(supervisor_id) is not str or not _UUID.fullmatch(supervisor_id)):
218
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
219
+ expected_enrollment = {'profile', 'enrollmentId', 'purpose', 'context',
220
+ 'ownerConfiguration', 'nativeProfile',
221
+ 'generationAuthorityRoots', 'supervisorJournalBirth'}
222
+ if (type(enrollment) is dict
223
+ and enrollment.get('profile') == ENROLLMENT_05):
224
+ expected_enrollment.add('targetCustodyJournalBirth')
225
+ context, native = enrollment.get('context'), enrollment.get('nativeProfile')
226
+ if (type(context) is not dict or type(native) is not dict
227
+ or set(enrollment) != expected_enrollment
228
+ or enrollment.get('profile') not in (ENROLLMENT_03, ENROLLMENT_05)
229
+ or type(enrollment.get('enrollmentId')) is not str
230
+ or not _UUID.fullmatch(enrollment['enrollmentId'])
231
+ or enrollment.get('purpose') not in ('production', 'native-acceptance')
232
+ or type(configuration_digest) is not str
233
+ or not _HEX.fullmatch(configuration_digest)
234
+ or (generation_root_policy_digest is not None
235
+ and (type(generation_root_policy_digest) is not str
236
+ or not _HEX.fullmatch(generation_root_policy_digest)))
237
+ or supervisor_id != context.get('supervisorId')
238
+ or supervisor_id != native.get('supervisorId')):
239
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
240
+ if enrollment.get('profile') == ENROLLMENT_05:
241
+ validate_target_custody_birth(
242
+ enrollment.get('targetCustodyJournalBirth'), enrollment=enrollment)
243
+ if hashlib.sha256(canonical(enrollment['ownerConfiguration'])).hexdigest() != configuration_digest:
244
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
245
+ paths = expected_paths(native.get('controlHome'), supervisor_id)
246
+ if (value['path'], value['lockPath']) != paths:
247
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
248
+ definition = validate_definition(value['definition'])
249
+ definition_digest = hashlib.sha256(canonical(definition)).hexdigest()
250
+ if value['definitionDigest'] != definition_digest:
251
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
252
+ for name in ('anchorDigest', 'initialHeaderDigest'):
253
+ if type(value[name]) is not str or not _HEX.fullmatch(value[name]):
254
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
255
+ native_digest = hashlib.sha256(canonical(native)).hexdigest()
256
+ anchor = {'profile': ANCHOR_PROFILE, 'enrollmentId': enrollment.get('enrollmentId'),
257
+ 'purpose': enrollment.get('purpose'), 'context': context,
258
+ 'authorityConfigurationDigest': configuration_digest,
259
+ 'nativeProfileDigest': native_digest,
260
+ 'generationRootPolicyDigest': generation_root_policy_digest,
261
+ 'journalId': journal_id, 'path': paths[0], 'lockPath': paths[1],
262
+ 'definitionDigest': definition_digest}
263
+ anchor_digest = hashlib.sha256(canonical(anchor)).hexdigest()
264
+ if value['anchorDigest'] != anchor_digest:
265
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
266
+ if enrollment['supervisorJournalBirth'] != value:
267
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
268
+ initial = initial_record(supervisor_id=supervisor_id, journal_id=journal_id,
269
+ definition_digest=definition_digest,
270
+ anchor_digest=anchor_digest)
271
+ if hashlib.sha256(initial).hexdigest() != value['initialHeaderDigest']:
272
+ raise SupervisorJournalCodecError('supervisor-journal-birth-invalid')
273
+ return json.loads(canonical(value))
274
+
275
+ def validate_record(raw: object, *, birth: dict[str, Any],
276
+ owner_bootstrap_context_digest: str,
277
+ generation_root_policy_digest: str | None,
278
+ root_replay_context: object | None = None,
279
+ include_root_state: bool = False) -> dict[str, Any] | tuple[
280
+ dict[str, Any], bytes | None, bytes | None]:
281
+ if type(raw) is not bytes or not 1 <= len(raw) <= MAX_BYTES:
282
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
283
+ def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
284
+ result: dict[str, Any] = {}
285
+ for key, val in items:
286
+ if key in result:
287
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
288
+ result[key] = val
289
+ return result
290
+ try:
291
+ doc = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs,
292
+ parse_float=lambda _v: (_ for _ in ()).throw(
293
+ SupervisorJournalCodecError('supervisor-journal-corrupt')),
294
+ parse_constant=lambda _v: (_ for _ in ()).throw(
295
+ SupervisorJournalCodecError('supervisor-journal-corrupt')))
296
+ except SupervisorJournalCodecError:
297
+ raise
298
+ except (UnicodeError, ValueError, RecursionError):
299
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
300
+ if canonical(doc) != raw:
301
+ raise SupervisorJournalCodecError('supervisor-journal-noncanonical')
302
+ keys = {'profile', 'supervisorId', 'journalId', 'definitionDigest',
303
+ 'anchorDigest', 'sequence', 'headDigest', 'events'}
304
+ if (type(doc) is not dict or set(doc) != keys
305
+ or doc['profile'] != JOURNAL_PROFILE_02
306
+ or doc['supervisorId'] != birth['supervisorId']
307
+ or doc['journalId'] != birth['journalId']
308
+ or doc['definitionDigest'] != birth['definitionDigest']
309
+ or doc['anchorDigest'] != birth['anchorDigest']
310
+ or type(doc['events']) is not list or len(doc['events']) > MAX_EVENTS
311
+ or type(doc['sequence']) is not int
312
+ or doc['sequence'] != len(doc['events'])):
313
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
314
+ previous = birth['anchorDigest']
315
+ for index, event in enumerate(doc['events'], 1):
316
+ if (type(event) is not dict or set(event) != {
317
+ 'sequence', 'kind', 'payload', 'previousDigest', 'recordDigest'}
318
+ or type(event['sequence']) is not int or event['sequence'] != index
319
+ or type(event['kind']) is not str or type(event['payload']) is not dict
320
+ or event['previousDigest'] != previous):
321
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
322
+ unhashed = {key: event[key] for key in
323
+ ('sequence', 'kind', 'payload', 'previousDigest')}
324
+ if event['recordDigest'] != hashlib.sha256(canonical(unhashed)).hexdigest():
325
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
326
+ previous = event['recordDigest']
327
+ if doc['headDigest'] != previous:
328
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
329
+ if type(owner_bootstrap_context_digest) is not str or not _HEX.fullmatch(
330
+ owner_bootstrap_context_digest):
331
+ raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
332
+ if (generation_root_policy_digest is not None
333
+ and (type(generation_root_policy_digest) is not str
334
+ or not _HEX.fullmatch(generation_root_policy_digest))):
335
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
336
+ validated_root_context = _validate_root_replay_context(root_replay_context)
337
+ if validated_root_context is not None and (
338
+ generation_root_policy_digest is None
339
+ or hashlib.sha256(canonical(validated_root_context['rootPolicy'])).hexdigest()
340
+ != generation_root_policy_digest):
341
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
342
+ try:
343
+ replay = _Replay(
344
+ birth['supervisorId'],
345
+ owner_bootstrap_context_digest=owner_bootstrap_context_digest,
346
+ birth_digest=hashlib.sha256(canonical(birth)).hexdigest(),
347
+ root_replay_context=root_replay_context,
348
+ )
349
+ replay._replay(doc['events'])
350
+ except SupervisorJournalCodecError:
351
+ raise
352
+ except (AssertionError, AttributeError, IndexError, KeyError, TypeError):
353
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
354
+ return (doc, replay.root_raw, replay.pending_root_raw) if include_root_state else doc
355
+
356
+ def validate_legacy_record(raw: object, *, supervisor_id: str) -> dict[str, Any]:
357
+ """Validate the retained 0.1 bytes without selecting or upgrading 0.2."""
358
+ if type(raw) is not bytes or not 1 <= len(raw) <= MAX_BYTES:
359
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
360
+ def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
361
+ result: dict[str, Any] = {}
362
+ for key, val in items:
363
+ if key in result:
364
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
365
+ result[key] = val
366
+ return result
367
+ try:
368
+ doc = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs,
369
+ parse_float=lambda _v: (_ for _ in ()).throw(
370
+ SupervisorJournalCodecError('supervisor-journal-corrupt')),
371
+ parse_constant=lambda _v: (_ for _ in ()).throw(
372
+ SupervisorJournalCodecError('supervisor-journal-corrupt')))
373
+ except SupervisorJournalCodecError:
374
+ raise
375
+ except (UnicodeError, ValueError, RecursionError):
376
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
377
+ if canonical(doc) != raw:
378
+ raise SupervisorJournalCodecError('supervisor-journal-noncanonical')
379
+ if (type(doc) is not dict or set(doc) != {
380
+ 'profile', 'supervisorId', 'sequence', 'headDigest', 'events'}
381
+ or doc['profile'] != LEGACY_PROFILE or doc['supervisorId'] != supervisor_id
382
+ or type(doc['events']) is not list or len(doc['events']) > MAX_EVENTS
383
+ or type(doc['sequence']) is not int
384
+ or doc['sequence'] != len(doc['events'])):
385
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
386
+ previous = '0' * 64
387
+ for index, event in enumerate(doc['events'], 1):
388
+ if (type(event) is not dict or set(event) != {
389
+ 'sequence', 'kind', 'payload', 'previousDigest', 'recordDigest'}
390
+ or type(event['sequence']) is not int or event['sequence'] != index
391
+ or type(event['kind']) is not str or type(event['payload']) is not dict
392
+ or event['previousDigest'] != previous):
393
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
394
+ unhashed = {key: event[key] for key in
395
+ ('sequence', 'kind', 'payload', 'previousDigest')}
396
+ if event['recordDigest'] != hashlib.sha256(canonical(unhashed)).hexdigest():
397
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
398
+ previous = event['recordDigest']
399
+ if doc['headDigest'] != previous:
400
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
401
+ try:
402
+ _Replay(supervisor_id, LEGACY_PROFILE)._replay(doc['events'])
403
+ except SupervisorJournalCodecError:
404
+ raise
405
+ except (AssertionError, AttributeError, IndexError, KeyError, TypeError):
406
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt') from None
407
+ return doc
408
+
409
+
410
+
411
+ # Fixed state machine shared by enrolled 0.2 record validation.
412
+ _canonical = canonical
413
+ _MAX_EVENTS = MAX_EVENTS
414
+ def _uuid(value: object) -> str:
415
+ if type(value) is not str or not _UUID.fullmatch(value):
416
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
417
+ return value
418
+
419
+
420
+ def _validate_root_replay_context(value: object | None) -> dict[str, Any] | None:
421
+ if value is None:
422
+ return None
423
+ keys = {'registryId', 'anchorDigest', 'rootPolicy', 'purpose',
424
+ 'bootstrapEnrollmentId', 'initialRegistryDigest'}
425
+ if type(value) is not dict or set(value) != keys:
426
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
427
+ if (type(value['registryId']) is not str or not _UUID.fullmatch(value['registryId'])
428
+ or type(value['bootstrapEnrollmentId']) is not str
429
+ or not _UUID.fullmatch(value['bootstrapEnrollmentId'])
430
+ or value['purpose'] not in ('production', 'native-acceptance')
431
+ or any(type(value[key]) is not str or not _HEX.fullmatch(value[key])
432
+ for key in ('anchorDigest', 'initialRegistryDigest'))):
433
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
434
+ from umf_access.lifecycle import generation_authority_bootstrap as root
435
+ try:
436
+ raw = root.initial_registry_bytes(value['registryId'], value['anchorDigest'])
437
+ if hashlib.sha256(raw).hexdigest() != value['initialRegistryDigest']:
438
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
439
+ root.validate_registry(
440
+ raw, registry_id=value['registryId'], anchor_digest=value['anchorDigest'],
441
+ root_policy=value['rootPolicy'], purpose=value['purpose'],
442
+ bootstrap_enrollment_id=value['bootstrapEnrollmentId'])
443
+ except root.GenerationAuthorityBootstrapError:
444
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid') from None
445
+ copied = json.loads(canonical(value))
446
+ copied['initialBytes'] = raw
447
+ return copied
448
+
449
+
450
+ def _root_projection(raw: bytes) -> dict[str, Any]:
451
+ from umf_access.lifecycle import generation_authority_bootstrap as root
452
+ value = root._parse(raw)
453
+ return {'sequence': value['sequence'], 'digest': hashlib.sha256(raw).hexdigest()}
454
+
455
+
456
+ def _root_projection_matches(value: object, expected: dict[str, Any]) -> bool:
457
+ return (type(value) is dict and set(value) == {'sequence', 'digest'}
458
+ and type(value['sequence']) is int
459
+ and value['sequence'] == expected['sequence']
460
+ and type(value['digest']) is str
461
+ and value['digest'] == expected['digest'])
462
+
463
+
464
+ def _apply_root_mutation(payload: dict[str, Any], *, context: dict[str, Any],
465
+ prior_raw: bytes, owner_context_digest: str
466
+ ) -> tuple[bytes, dict[str, Any] | None, str | None]:
467
+ from umf_access.lifecycle import generation_authority_bootstrap as root
468
+ from umf_access.lifecycle.generation_root_registry import (
469
+ confirm_prepared,
470
+ reserve_prepared,
471
+ )
472
+ keys = {'purpose', 'mutationId', 'operation', 'registryId', 'rootRequestId',
473
+ 'rootIntentDigest', 'configurationDigest', 'ownerBootstrapContextDigest',
474
+ 'nativeEvidenceDigest', 'validationObservationEventDigest', 'prior',
475
+ 'next', 'delta', 'subordinateBirth'}
476
+ if type(payload) is not dict or set(payload) != keys:
477
+ raise SupervisorJournalCodecError('supervisor-journal-root-event-invalid')
478
+ operation = payload['operation']
479
+ if operation not in ('reserve', 'confirm'):
480
+ raise SupervisorJournalCodecError('supervisor-journal-root-event-invalid')
481
+ if (payload['purpose'] != context['purpose']
482
+ or payload['registryId'] != context['registryId']
483
+ or payload['ownerBootstrapContextDigest'] != owner_context_digest
484
+ or type(payload['mutationId']) is not str
485
+ or not _UUID.fullmatch(payload['mutationId'])
486
+ or type(payload['rootRequestId']) is not str
487
+ or not _UUID.fullmatch(payload['rootRequestId'])
488
+ or any(type(payload[name]) is not str or not _HEX.fullmatch(payload[name])
489
+ for name in ('rootIntentDigest', 'configurationDigest',
490
+ 'nativeEvidenceDigest', 'validationObservationEventDigest'))):
491
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
492
+ expected_prior = _root_projection(prior_raw)
493
+ if not _root_projection_matches(payload['prior'], expected_prior):
494
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
495
+ args = {'registry_id': context['registryId'], 'anchor_digest': context['anchorDigest'],
496
+ 'root_policy': context['rootPolicy'], 'purpose': context['purpose'],
497
+ 'bootstrap_enrollment_id': context['bootstrapEnrollmentId']}
498
+ derived_enrollment = None
499
+ subordinate_digest = None
500
+ try:
501
+ if operation == 'reserve':
502
+ if (type(payload['delta']) is not dict or set(payload['delta']) != {'request'}
503
+ or payload['subordinateBirth'] is not None):
504
+ raise SupervisorJournalCodecError('supervisor-journal-root-event-invalid')
505
+ request = payload['delta']['request']
506
+ if (type(request) is not dict or request.get('requestId') != payload['rootRequestId']
507
+ or _digest(request.get('intent')) != payload['rootIntentDigest']
508
+ or request.get('intent', {}).get('configurationDigest') != payload['configurationDigest']
509
+ or request.get('intent', {}).get('nativeEvidenceDigest') != payload['nativeEvidenceDigest']):
510
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
511
+ next_raw = reserve_prepared(prior_raw, request, **args)
512
+ else:
513
+ if (type(payload['delta']) is not dict
514
+ or set(payload['delta']) != {'requestId', 'approvalEnvelope', 'enrollment'}
515
+ or payload['delta']['requestId'] != payload['rootRequestId']):
516
+ raise SupervisorJournalCodecError('supervisor-journal-root-event-invalid')
517
+ envelope = payload['delta']['approvalEnvelope']
518
+ current = root._parse(prior_raw)
519
+ matched = [item for item in current['requests']
520
+ if item['requestId'] == payload['rootRequestId']]
521
+ if (len(matched) != 1
522
+ or _digest(matched[0]['intent']) != payload['rootIntentDigest']
523
+ or matched[0]['intent'].get('configurationDigest')
524
+ != payload['configurationDigest']
525
+ or matched[0]['intent'].get('nativeEvidenceDigest')
526
+ != payload['nativeEvidenceDigest']
527
+ or type(envelope) is not dict
528
+ or type(envelope.get('payload')) is not dict
529
+ or envelope['payload'].get('intentDigest')
530
+ != payload['rootIntentDigest']):
531
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
532
+ next_raw = confirm_prepared(
533
+ prior_raw, payload['rootRequestId'], envelope, **args)
534
+ updated = root._parse(next_raw)
535
+ matches = [item for item in updated['enrollments']
536
+ if item['requestId'] == payload['rootRequestId']]
537
+ if len(matches) != 1 or canonical(matches[0]) != canonical(payload['delta']['enrollment']):
538
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
539
+ derived_enrollment = matches[0]
540
+ subordinate = payload['subordinateBirth']
541
+ birth_keys = {'profile', 'rootRegistryId', 'contextJournalRegistryId',
542
+ 'contextId', 'rootRequestId', 'trustEnrollmentId',
543
+ 'configurationDigest', 'contextProjectionDigest',
544
+ 'logicalEnrollmentId', 'initialEpoch', 'contextJournalPath',
545
+ 'contextJournalEntryDigest', 'contextBirthMarkerPath',
546
+ 'contextBirthMarkerDigest', 'approvalLedgerPath',
547
+ 'approvalLedgerLockPath', 'approvalLedgerBirthDigest'}
548
+ if (type(subordinate) is not dict or set(subordinate) != birth_keys
549
+ or subordinate.get('profile') != 'umf.generation-authority-logical-birth/0.1'
550
+ or subordinate.get('rootRegistryId') != context['registryId']
551
+ or subordinate.get('contextId') != derived_enrollment['contextId']
552
+ or subordinate.get('rootRequestId') != payload['rootRequestId']
553
+ or subordinate.get('trustEnrollmentId') != derived_enrollment['trust']['enrollmentId']
554
+ or subordinate.get('configurationDigest') != derived_enrollment['configurationDigest']):
555
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
556
+ uuid_fields = ('rootRegistryId', 'contextJournalRegistryId', 'contextId',
557
+ 'rootRequestId', 'trustEnrollmentId', 'logicalEnrollmentId',
558
+ 'initialEpoch')
559
+ digest_fields = ('configurationDigest', 'contextProjectionDigest',
560
+ 'contextJournalEntryDigest', 'contextBirthMarkerDigest',
561
+ 'approvalLedgerBirthDigest')
562
+ path_fields = ('contextJournalPath', 'contextBirthMarkerPath',
563
+ 'approvalLedgerPath', 'approvalLedgerLockPath')
564
+ if (any(type(subordinate[name]) is not str or not _UUID.fullmatch(subordinate[name])
565
+ for name in uuid_fields)
566
+ or any(type(subordinate[name]) is not str or not _HEX.fullmatch(subordinate[name])
567
+ for name in digest_fields)
568
+ or any(type(subordinate[name]) is not str
569
+ or not subordinate[name].startswith('/')
570
+ or '\x00' in subordinate[name]
571
+ or any(part in ('.', '..') for part in subordinate[name].split('/'))
572
+ for name in path_fields)
573
+ or subordinate['approvalLedgerLockPath']
574
+ != subordinate['approvalLedgerPath'] + '.lock'):
575
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
576
+ subordinate_digest = _digest(subordinate)
577
+ except SupervisorJournalCodecError:
578
+ raise
579
+ except root.GenerationAuthorityBootstrapError:
580
+ raise SupervisorJournalCodecError('supervisor-journal-root-transition-invalid') from None
581
+ if not _root_projection_matches(payload['next'], _root_projection(next_raw)):
582
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
583
+ return next_raw, derived_enrollment, subordinate_digest
584
+
585
+ class _Replay:
586
+ __slots__ = ('birth_digest', 'owner_context_digest', 'pending_root_raw',
587
+ 'profile', 'root_context', 'root_raw', 'supervisor_id')
588
+ def __init__(self, supervisor_id: str, profile: str = JOURNAL_PROFILE_02, *,
589
+ owner_bootstrap_context_digest: str | None = None,
590
+ birth_digest: str | None = None,
591
+ root_replay_context: object | None = None):
592
+ self.supervisor_id = _uuid(supervisor_id)
593
+ self.profile = profile
594
+ self.owner_context_digest = owner_bootstrap_context_digest
595
+ self.birth_digest = birth_digest
596
+ self.root_context = _validate_root_replay_context(root_replay_context)
597
+ self.root_raw = (None if self.root_context is None else
598
+ self.root_context['initialBytes'])
599
+ self.pending_root_raw = None
600
+ def _replay(self, events: list[dict[str, Any]]) -> None:
601
+ created = initdb = False
602
+ launch_pending = False
603
+ running = False
604
+ stop_pending = False
605
+ launch_number = 0
606
+ creation: dict[str, Any] | None = None
607
+ creation_finalized: dict[str, Any] | None = None
608
+ initdb_receipt: dict[str, Any] | None = None
609
+ current_launch: dict[str, Any] | None = None
610
+ registration_done = authority_done = principal_authority_done = False
611
+ store_intent = store_done = False
612
+ registration_request: dict[str, Any] | None = None
613
+ registration_signature_verified = False
614
+ principal_request: dict[str, Any] | None = None
615
+ native_effects: dict[str, dict[str, Any]] = {}
616
+ principal_stages: dict[str, dict[str, str | None]] = {}
617
+ confirmed_process_start_token: str | None = None
618
+ original_stores: dict[tuple[str, str], dict[str, Any]] = {}
619
+ original_stores_by_reservation: dict[str, dict[str, Any]] = {}
620
+ store_effects_by_reservation: dict[str, dict[str, Any]] = {}
621
+ pending_original_store_effect: str | None = None
622
+ pending_original_store_intent_digest: str | None = None
623
+ root_observations: dict[str, dict[str, Any]] = {}
624
+ root_pending: dict[str, Any] | None = None
625
+ root_confirmations: dict[str, dict[str, Any]] = {}
626
+ root_bindings: set[tuple[str, str, str]] = set()
627
+ for event in events:
628
+ kind = event['kind']
629
+ payload = event['payload']
630
+ if root_pending is not None and kind != 'generation-authority-root-mutation-confirmed':
631
+ raise SupervisorJournalCodecError('supervisor-journal-root-order-invalid')
632
+ if pending_original_store_effect is not None and kind != 'native-effect-intent':
633
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
634
+ if kind == 'creation-intent':
635
+ expected_creation = {'profile', 'supervisorId', 'clusterId', 'incarnationId', 'installationId',
636
+ 'ownerUid', 'databaseName', 'businessOwner', 'maintenanceName',
637
+ 'controllerName', 'controlDirectory', 'dataDirectory', 'postgresPath',
638
+ 'postgresSha256', 'initdbPath', 'initdbSha256', 'port',
639
+ 'configDigest', 'hbaDigest', 'purpose', 'requestDigest',
640
+ 'approvalId', 'approvalDigest'}
641
+ if self.profile == JOURNAL_PROFILE_02:
642
+ expected_creation |= {'supervisorJournalBirthDigest',
643
+ 'ownerBootstrapContextDigest'}
644
+ if created or set(payload) != expected_creation:
645
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
646
+ if (payload['profile'] != ('umf.local-postgresql-create-request/0.2' if self.profile == JOURNAL_PROFILE_02 else 'umf.local-postgresql-create-request/0.1')
647
+ or payload['purpose'] not in ('production', 'native-acceptance')
648
+ or payload['supervisorId'] != self.supervisor_id
649
+ or not _HEX.fullmatch(payload['requestDigest'])
650
+ or not _HEX.fullmatch(payload['approvalDigest'])
651
+ or (self.profile == JOURNAL_PROFILE_02 and any(
652
+ not _HEX.fullmatch(payload[name]) for name in (
653
+ 'supervisorJournalBirthDigest',
654
+ 'ownerBootstrapContextDigest')))):
655
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
656
+ if self.profile == JOURNAL_PROFILE_02 and (
657
+ payload['supervisorJournalBirthDigest'] != self.birth_digest
658
+ or payload['ownerBootstrapContextDigest'] != self.owner_context_digest
659
+ or self.birth_digest is None or self.owner_context_digest is None):
660
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
661
+ created = True
662
+ creation = payload
663
+ elif kind == 'initdb-confirmed':
664
+ if not created or initdb or set(payload) != {'clusterId', 'dataDevice',
665
+ 'dataInode', 'ownerUid', 'initdbReceiptDigest'}:
666
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
667
+ initdb = True
668
+ initdb_receipt = payload
669
+ elif kind == 'launch-intent':
670
+ if (not initdb or running or launch_pending
671
+ or payload.get('launchNumber') != launch_number + 1
672
+ or set(payload) != {
673
+ 'launchId', 'launchNumber', 'argv', 'configDigest', 'hbaDigest',
674
+ 'binarySha256', 'dataDevice', 'dataInode'}):
675
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
676
+ assert creation is not None and initdb_receipt is not None
677
+ control = creation['controlDirectory']
678
+ expected_argv = [creation['postgresPath'], '-D', creation['dataDirectory'],
679
+ '-c', f'config_file={control}/postgresql.conf',
680
+ '-c', f'hba_file={control}/pg_hba.conf',
681
+ '-c', f'ident_file={control}/pg_ident.conf']
682
+ if (payload['argv'] != expected_argv
683
+ or payload['binarySha256'] != creation['postgresSha256']
684
+ or payload['configDigest'] != creation['configDigest']
685
+ or payload['hbaDigest'] != creation['hbaDigest']
686
+ or payload['dataDevice'] != initdb_receipt['dataDevice']
687
+ or payload['dataInode'] != initdb_receipt['dataInode']):
688
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
689
+ launch_number += 1
690
+ current_launch = payload
691
+ launch_pending = True
692
+ elif kind == 'launch-confirmed':
693
+ if not launch_pending or running or set(payload) != {'launchId', 'process',
694
+ 'nativeObservationDigest', 'endpointReceiptDigest'}:
695
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
696
+ assert current_launch is not None and creation is not None
697
+ process = payload['process']
698
+ if (type(process) is not dict or set(process) != {
699
+ 'pid', 'pgid', 'uid', 'gid', 'startSec', 'startUsec',
700
+ 'path', 'argv', 'startToken'}
701
+ or type(process['pid']) is not int or process['pid'] <= 0
702
+ or process['pgid'] != process['pid']
703
+ or process['uid'] != creation['ownerUid']
704
+ or process['path'] != creation['postgresPath']
705
+ or process['argv'] != current_launch['argv']
706
+ or type(process['startToken']) is not str
707
+ or not process['startToken']):
708
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
709
+ if (not _HEX.fullmatch(payload['nativeObservationDigest'])
710
+ or not _HEX.fullmatch(payload['endpointReceiptDigest'])):
711
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
712
+ launch_pending = False
713
+ running = True
714
+ confirmed_process_start_token = process['startToken']
715
+ elif kind == 'stop-intent':
716
+ expected_start_token = (
717
+ confirmed_process_start_token
718
+ if self.profile == JOURNAL_PROFILE_02 else
719
+ next((e['payload']['process']['startToken'] for e in reversed(events[:-1])
720
+ if e['kind'] == 'launch-confirmed'), None))
721
+ if (not running or stop_pending or current_launch is None
722
+ or set(payload) != {'launchId', 'processStartToken'}
723
+ or payload['launchId'] != current_launch['launchId']
724
+ or payload['processStartToken'] != expected_start_token):
725
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
726
+ stop_pending = True
727
+ elif kind == 'stop-confirmed':
728
+ if not stop_pending or not running or set(payload) != {
729
+ 'launchId', 'processGroupAbsent', 'controlDataDigest'}:
730
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
731
+ if payload['processGroupAbsent'] is not True:
732
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
733
+ if not _HEX.fullmatch(payload['controlDataDigest']):
734
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
735
+ running = False
736
+ stop_pending = False
737
+ if self.profile == JOURNAL_PROFILE_02:
738
+ confirmed_process_start_token = None
739
+ elif kind == 'owner-registration-approved':
740
+ if (not running or registration_done or registration_request is None
741
+ or not registration_signature_verified
742
+ or set(payload) != {'registrationId', 'payloadDigest',
743
+ 'approvalId', 'approvalDigest'}
744
+ or payload['registrationId'] != registration_request['registrationId']
745
+ or payload['approvalId'] != registration_request['approvalId']
746
+ or payload['approvalDigest'] != registration_request['approvalDigest']):
747
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
748
+ registration_done = True
749
+ elif kind == 'principal-request-prepared':
750
+ if (not running or principal_request is not None
751
+ or set(payload) != {'preparationId', 'approvalId', 'intent', 'requestDigest'}
752
+ or type(payload['intent']) is not dict
753
+ or payload['intent'].get('profile')
754
+ != 'umf.local-postgresql-principal-preparation/0.1'
755
+ or payload['intent'].get('preparationId') != payload['preparationId']
756
+ or _uuid(payload['approvalId']) != payload['approvalId']
757
+ or _uuid(payload['preparationId']) != payload['preparationId']
758
+ or _digest(payload['intent']) != payload['requestDigest']):
759
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
760
+ principal_request = payload
761
+ elif kind == 'registration-request-prepared':
762
+ if (not running or registration_request is not None
763
+ or set(payload) != {'registrationId', 'approvalId', 'intent', 'requestDigest'}
764
+ or type(payload['intent']) is not dict
765
+ or payload['intent'].get('profile')
766
+ != 'umf.owner-target-registration-intent/0.1'
767
+ or payload['intent'].get('registration', {}).get('registrationId')
768
+ != payload['registrationId']
769
+ or _uuid(payload['registrationId']) != payload['registrationId']
770
+ or _uuid(payload['approvalId']) != payload['approvalId']
771
+ or _digest(payload['intent']) != payload['requestDigest']):
772
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
773
+ if self.profile == JOURNAL_PROFILE_02:
774
+ registration = payload['intent'].get('registration')
775
+ origin = registration.get('origin') if type(registration) is dict else None
776
+ if (not created or creation_finalized is None or type(origin) is not dict
777
+ or origin.get('supervisorId') != self.supervisor_id
778
+ or origin.get('clusterId') != creation['clusterId']
779
+ or origin.get('incarnationId') != creation['incarnationId']
780
+ or origin.get('creationReceiptDigest')
781
+ != creation_finalized['receiptDigest']
782
+ or registration.get('installationId') != creation['installationId']):
783
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
784
+ registration_request = {
785
+ 'registrationId': payload['registrationId'],
786
+ 'approvalId': payload['approvalId'],
787
+ 'requestDigest': payload['requestDigest'],
788
+ 'intent': payload['intent'],
789
+ }
790
+ elif kind == 'registration-signature-verified':
791
+ if (not running or registration_done or registration_request is None
792
+ or registration_signature_verified
793
+ or set(payload) != {'registrationId', 'requestDigest',
794
+ 'approvalId', 'approvalDigest'}
795
+ or payload['registrationId'] != registration_request['registrationId']
796
+ or payload['requestDigest'] != registration_request['requestDigest']
797
+ or not all(_HEX.fullmatch(payload[key]) for key in
798
+ ('requestDigest', 'approvalDigest'))):
799
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
800
+ _uuid(payload['registrationId']); _uuid(payload['approvalId'])
801
+ registration_signature_verified = True
802
+ if self.profile == JOURNAL_PROFILE_02:
803
+ registration_request['approvalDigest'] = payload['approvalDigest']
804
+ elif kind == 'authority-preparation-approved':
805
+ if (not running or authority_done or set(payload) != {'installationId', 'payloadDigest',
806
+ 'approvalId', 'approvalDigest'}):
807
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
808
+ authority_done = True
809
+ elif kind == 'generation-authority-observed':
810
+ keys = {'purpose', 'observationId', 'configurationDigest',
811
+ 'nativeEvidenceDigest', 'nativeEvidence'}
812
+ evidence = payload.get('nativeEvidence')
813
+ if (not running or self.profile != JOURNAL_PROFILE_02
814
+ or self.root_context is None or set(payload) != keys
815
+ or payload['purpose'] != self.root_context['purpose']
816
+ or type(payload['observationId']) is not str
817
+ or not _UUID.fullmatch(payload['observationId'])
818
+ or any(type(payload[name]) is not str or not _HEX.fullmatch(payload[name])
819
+ for name in ('configurationDigest', 'nativeEvidenceDigest'))
820
+ or type(evidence) is not dict or set(evidence) != {'encoding', 'data'}
821
+ or evidence.get('encoding') != 'base64' or type(evidence.get('data')) is not str):
822
+ raise SupervisorJournalCodecError('supervisor-journal-root-observation-invalid')
823
+ try:
824
+ evidence_bytes = base64.b64decode(evidence['data'], validate=True)
825
+ except (ValueError, TypeError):
826
+ raise SupervisorJournalCodecError('supervisor-journal-root-observation-invalid') from None
827
+ if (len(evidence_bytes) > 4 * 1024 * 1024
828
+ or base64.b64encode(evidence_bytes).decode('ascii') != evidence['data']
829
+ or hashlib.sha256(evidence_bytes).hexdigest()
830
+ != payload['nativeEvidenceDigest']):
831
+ raise SupervisorJournalCodecError('supervisor-journal-root-observation-invalid')
832
+ _validate_native_evidence_bytes(evidence_bytes)
833
+ root_observations[event['recordDigest']] = {
834
+ 'purpose': payload['purpose'],
835
+ 'configurationDigest': payload['configurationDigest'],
836
+ 'nativeEvidenceDigest': payload['nativeEvidenceDigest'],
837
+ 'observationId': payload['observationId'],
838
+ }
839
+ elif kind == 'generation-authority-root-mutation-intent':
840
+ if self.profile != JOURNAL_PROFILE_02 or self.root_context is None or self.root_raw is None:
841
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
842
+ observation = root_observations.get(payload.get('validationObservationEventDigest'))
843
+ if (not running or observation is None
844
+ or observation['purpose'] != payload.get('purpose')
845
+ or observation['configurationDigest'] != payload.get('configurationDigest')):
846
+ raise SupervisorJournalCodecError('supervisor-journal-root-observation-invalid')
847
+ next_root, enrollment, subordinate_digest = _apply_root_mutation(
848
+ payload, context=self.root_context, prior_raw=self.root_raw,
849
+ owner_context_digest=self.owner_context_digest or '')
850
+ root_pending = {'payload': payload, 'intentEventDigest': event['recordDigest'],
851
+ 'nextRaw': next_root, 'enrollment': enrollment,
852
+ 'subordinateDigest': subordinate_digest}
853
+ self.pending_root_raw = next_root
854
+ elif kind == 'generation-authority-root-mutation-confirmed':
855
+ if root_pending is None:
856
+ raise SupervisorJournalCodecError('supervisor-journal-root-order-invalid')
857
+ intent = root_pending['payload']
858
+ keys = {'purpose', 'mutationId', 'intentEventDigest', 'operation',
859
+ 'registryId', 'rootRequestId', 'rootSequence', 'rootStateDigest',
860
+ 'rootEnrollmentId', 'contextId', 'subordinateBirthDigest'}
861
+ projection = _root_projection(root_pending['nextRaw'])
862
+ confirmed_enrollment = root_pending['enrollment']
863
+ expected_ids = ((None, None, None) if confirmed_enrollment is None else (
864
+ confirmed_enrollment['enrollmentId'], confirmed_enrollment['contextId'],
865
+ root_pending['subordinateDigest']))
866
+ if (set(payload) != keys or payload['purpose'] != intent['purpose']
867
+ or payload['mutationId'] != intent['mutationId']
868
+ or payload['intentEventDigest'] != root_pending['intentEventDigest']
869
+ or payload['operation'] != intent['operation']
870
+ or payload['registryId'] != intent['registryId']
871
+ or payload['rootRequestId'] != intent['rootRequestId']
872
+ or type(payload['rootSequence']) is not int
873
+ or payload['rootSequence'] != projection['sequence']
874
+ or payload['rootStateDigest'] != projection['digest']
875
+ or (payload['rootEnrollmentId'], payload['contextId'],
876
+ payload['subordinateBirthDigest']) != expected_ids):
877
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
878
+ self.root_raw = root_pending['nextRaw']
879
+ self.pending_root_raw = None
880
+ root_confirmations[intent['rootRequestId']] = {
881
+ 'eventDigest': event['recordDigest'],
882
+ 'intent': intent, 'enrollment': confirmed_enrollment,
883
+ 'subordinateDigest': root_pending['subordinateDigest'],
884
+ }
885
+ root_pending = None
886
+ elif kind == 'generation-authority-bound':
887
+ keys = {'purpose', 'registryId', 'rootEnrollmentId', 'contextId',
888
+ 'rootEntryDigest', 'configurationDigest', 'confirmEventDigest',
889
+ 'subordinateBirthDigest', 'targetCustodyDigest',
890
+ 'storeCreationReceiptDigest', 'nativeEvidenceDigest',
891
+ 'observationEventDigest'}
892
+ context = self.root_context
893
+ observation = root_observations.get(payload.get('observationEventDigest'))
894
+ confirmation = next((value for value in root_confirmations.values()
895
+ if value['eventDigest'] == payload.get('confirmEventDigest')),
896
+ None)
897
+ if self.root_raw is None or context is None:
898
+ raise SupervisorJournalCodecError('supervisor-journal-root-context-invalid')
899
+ from umf_access.lifecycle import generation_authority_bootstrap as root
900
+ registry = root._parse(self.root_raw)
901
+ matches = [entry for entry in registry['enrollments']
902
+ if entry['enrollmentId'] == payload.get('rootEnrollmentId')
903
+ and entry['contextId'] == payload.get('contextId')]
904
+ if (not running or set(payload) != keys or len(matches) != 1
905
+ or confirmation is None or confirmation['enrollment'] != matches[0]
906
+ or payload['purpose'] != context['purpose']
907
+ or payload['registryId'] != context['registryId']
908
+ or payload['rootEntryDigest'] != _digest(matches[0])
909
+ or payload['configurationDigest'] != matches[0]['configurationDigest']
910
+ or payload['subordinateBirthDigest'] != confirmation['subordinateDigest']
911
+ or payload['targetCustodyDigest'] != matches[0]['trust']['targetCustodyDigest']
912
+ or payload['storeCreationReceiptDigest'] != matches[0]['trust']['storeCreationReceiptDigest']
913
+ or payload['nativeEvidenceDigest'] != matches[0]['nativeEvidenceDigest']
914
+ or observation is None
915
+ or observation['configurationDigest'] != payload['configurationDigest']
916
+ or observation['purpose'] != payload['purpose']):
917
+ raise SupervisorJournalCodecError('supervisor-journal-root-origin-mismatch')
918
+ binding_key = (payload['registryId'], payload['rootEnrollmentId'], payload['contextId'])
919
+ if binding_key in root_bindings:
920
+ raise SupervisorJournalCodecError('supervisor-journal-root-order-invalid')
921
+ root_bindings.add(binding_key)
922
+ elif kind == 'store-creation-intent':
923
+ if (self.profile == JOURNAL_PROFILE_02 or not running or not registration_done or not authority_done or store_intent
924
+ or set(payload) != {'storeId', 'payloadDigest', 'schemaName'}):
925
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
926
+ store_intent = True
927
+ elif kind == 'store-creation-confirmed':
928
+ if (self.profile == JOURNAL_PROFILE_02 or not running or not store_intent or store_done or set(payload) != {'storeId', 'schemaOid',
929
+ 'nativeReceiptDigest'}):
930
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
931
+ store_done = True
932
+ elif kind == 'originals-store-creation-intent':
933
+ keys = {'purpose', 'reservation', 'reservationDigest',
934
+ 'custodianReservedEventDigest', 'creationRequestDigest',
935
+ 'creationApprovalDigest', 'nativeAuthorityEvidenceDigest'}
936
+ reservation = payload.get('reservation')
937
+ reservation_keys = {'profile', 'reservationId', 'providerId',
938
+ 'installationId', 'targetCustody', 'store',
939
+ 'creationRequestDigest', 'creationApprovalDigest',
940
+ 'nativeAuthorityEvidenceDigest', 'configurationDigest',
941
+ 'custodySequence'}
942
+ if (self.profile != JOURNAL_PROFILE_02 or not running
943
+ or not registration_done or not principal_authority_done
944
+ or creation_finalized is None
945
+ or pending_original_store_effect is not None
946
+ or any(item.get('nativeEffectOutcome') != 'confirmed'
947
+ for item in original_stores.values())
948
+ or set(payload) != keys or type(reservation) is not dict
949
+ or set(reservation) != reservation_keys
950
+ or reservation['profile'] != 'umf.row-originals-store-reservation/0.1'
951
+ or payload['purpose'] not in ('production', 'native-acceptance')
952
+ or type(payload['custodianReservedEventDigest']) is not str
953
+ or not _HEX.fullmatch(payload['custodianReservedEventDigest'])
954
+ or payload['reservationDigest'] != _digest(reservation)
955
+ or payload['creationRequestDigest']
956
+ != reservation['creationRequestDigest']
957
+ or payload['creationApprovalDigest']
958
+ != reservation['creationApprovalDigest']
959
+ or payload['nativeAuthorityEvidenceDigest']
960
+ != reservation['nativeAuthorityEvidenceDigest']
961
+ or type(reservation['reservationId']) is not str
962
+ or not _UUID.fullmatch(reservation['reservationId'])
963
+ or any(type(reservation[name]) is not str or not _HEX.fullmatch(
964
+ reservation[name]) for name in ('creationRequestDigest',
965
+ 'creationApprovalDigest', 'nativeAuthorityEvidenceDigest',
966
+ 'configurationDigest'))
967
+ or type(reservation['providerId']) is not str
968
+ or not _UUID.fullmatch(reservation['providerId'])
969
+ or reservation['installationId'] != creation['installationId']
970
+ or type(reservation['targetCustody']) is not dict
971
+ or set(reservation['targetCustody']) != {
972
+ 'profile', 'custodianId', 'registrationId', 'resourceId',
973
+ 'incarnation', 'registrationDigest'}
974
+ or reservation['targetCustody'].get('profile')
975
+ != 'umf.native-target-custody/0.1'
976
+ or type(reservation['store']) is not dict
977
+ or set(reservation['store']) != {'profile', 'storeId', 'schemaName'}
978
+ or type(reservation['custodySequence']) is not int
979
+ or reservation['custodySequence'] < 1):
980
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
981
+ registration = (registration_request['intent'].get('registration')
982
+ if registration_request is not None else None)
983
+ origin = registration.get('origin') if type(registration) is dict else None
984
+ custody = reservation['targetCustody']
985
+ store = reservation['store']
986
+ schema_prefixes = {
987
+ 'umf.native-row-originals-store/0.1': 'umf_originals_',
988
+ }
989
+ if (type(registration) is not dict or type(origin) is not dict
990
+ or custody.get('custodianId') != registration.get('custodianId')
991
+ or custody.get('registrationId') != registration.get('registrationId')
992
+ or custody.get('resourceId') != origin.get('clusterId')
993
+ or custody.get('incarnation') != origin.get('incarnationId')
994
+ or custody.get('registrationDigest') != _digest(registration)
995
+ or reservation['providerId'] != registration.get('providerId')
996
+ or reservation['installationId'] != registration.get('installationId')
997
+ or any(type(custody.get(name)) is not str
998
+ or not _UUID.fullmatch(custody[name])
999
+ for name in ('custodianId', 'registrationId',
1000
+ 'resourceId', 'incarnation'))
1001
+ or type(custody.get('registrationDigest')) is not str
1002
+ or not _HEX.fullmatch(custody['registrationDigest'])
1003
+ or custody.get('profile') != 'umf.native-target-custody/0.1'
1004
+ or store.get('profile') not in schema_prefixes
1005
+ or store.get('storeId') != reservation['providerId']
1006
+ or store.get('schemaName') != schema_prefixes.get(store.get('profile'), '')
1007
+ + reservation['providerId'].replace('-', '')):
1008
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1009
+ custody = reservation['targetCustody']
1010
+ store_key = (custody['registrationId'], reservation['providerId'],
1011
+ reservation['installationId'], store['profile'],
1012
+ store['storeId'], store['schemaName'])
1013
+ reservation_id = reservation['reservationId']
1014
+ if (store_key in original_stores
1015
+ or reservation_id in original_stores_by_reservation):
1016
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1017
+ original_store = {
1018
+ 'purpose': payload['purpose'], 'reservation': reservation,
1019
+ 'reservationDigest': payload['reservationDigest'],
1020
+ 'custodianReservedEventDigest': payload['custodianReservedEventDigest'],
1021
+ 'creationRequestDigest': payload['creationRequestDigest'],
1022
+ 'creationApprovalDigest': payload['creationApprovalDigest'],
1023
+ 'nativeAuthorityEvidenceDigest': payload['nativeAuthorityEvidenceDigest'],
1024
+ 'creationIntentDigest': event['recordDigest'],
1025
+ 'supervisorIntentDigest': None, 'confirmed': False,
1026
+ }
1027
+ original_stores[store_key] = original_store
1028
+ original_stores_by_reservation[reservation_id] = original_store
1029
+ pending_original_store_effect = payload['reservationDigest']
1030
+ pending_original_store_intent_digest = event['recordDigest']
1031
+ elif kind == 'originals-store-creation-confirmed':
1032
+ keys = {'purpose', 'reservationDigest', 'supervisorIntentDigest',
1033
+ 'custodianConfirmationDigest', 'nativeReceiptDigest', 'schemaOid'}
1034
+ original_store = next((item for item in original_stores.values()
1035
+ if item['reservationDigest']
1036
+ == payload.get('reservationDigest')), None)
1037
+ if (self.profile != JOURNAL_PROFILE_02 or not running
1038
+ or original_store is None or original_store['confirmed']
1039
+ or set(payload) != keys
1040
+ or payload['purpose'] != original_store['purpose']
1041
+ or payload['supervisorIntentDigest'] != original_store['supervisorIntentDigest']
1042
+ or type(payload['custodianConfirmationDigest']) is not str
1043
+ or not _HEX.fullmatch(payload['custodianConfirmationDigest'])
1044
+ or type(payload['nativeReceiptDigest']) is not str
1045
+ or not _HEX.fullmatch(payload['nativeReceiptDigest'])
1046
+ or type(payload['schemaOid']) is not int
1047
+ or not 1 <= payload['schemaOid'] <= 4_294_967_295):
1048
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1049
+ original_store.update({'custodianConfirmationDigest': payload['custodianConfirmationDigest'],
1050
+ 'nativeReceiptDigest': payload['nativeReceiptDigest'],
1051
+ 'schemaOid': payload['schemaOid'], 'confirmed': True})
1052
+ elif kind == 'native-effect-intent':
1053
+ required = {'reservationId', 'scope', 'effectKey', 'purpose',
1054
+ 'requestId', 'requestDigest', 'approvalId',
1055
+ 'approvalDigest', 'stage', 'payloadDigest'}
1056
+ if ((not running and payload['scope'] != 'local-target-creation')
1057
+ or set(payload) != required
1058
+ or type(payload['reservationId']) is not str
1059
+ or not _HEX.fullmatch(payload['requestDigest'])
1060
+ or not _HEX.fullmatch(payload['approvalDigest'])
1061
+ or not _HEX.fullmatch(payload['payloadDigest'])
1062
+ or type(payload['effectKey']) is not list
1063
+ or not payload['effectKey']
1064
+ or any(type(part) is not str or not part for part in payload['effectKey'])
1065
+ or payload['purpose'] not in ('production', 'native-acceptance')
1066
+ or payload['scope'] not in {
1067
+ 'local-target-creation', 'native-principal-preparation',
1068
+ 'local-target-registration', 'native-store-creation',
1069
+ 'disabled-epoch-provision', 'generation-ingress-transition'}
1070
+ or payload['reservationId'] in native_effects):
1071
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1072
+ if self.profile == JOURNAL_PROFILE_02 and pending_original_store_effect is not None:
1073
+ store_state = next((item for item in original_stores.values()
1074
+ if item['reservationDigest']
1075
+ == pending_original_store_effect), None)
1076
+ if (store_state is None
1077
+ or payload['scope'] != 'native-store-creation'
1078
+ or event['previousDigest'] != pending_original_store_intent_digest
1079
+ or payload['purpose'] != store_state['purpose']
1080
+ or payload['effectKey'] != [
1081
+ 'native-store-creation',
1082
+ store_state['reservation']['providerId'],
1083
+ store_state['reservation']['store']['profile'],
1084
+ store_state['reservation']['store']['storeId']]
1085
+ or payload['requestDigest'] != store_state['reservation']['creationRequestDigest']
1086
+ or payload['approvalDigest'] != store_state['reservation']['creationApprovalDigest']):
1087
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1088
+ store_state['supervisorIntentDigest'] = event['recordDigest']
1089
+ store_state['nativeEffectReservationId'] = payload['reservationId']
1090
+ store_effects_by_reservation[payload['reservationId']] = store_state
1091
+ pending_original_store_effect = None
1092
+ pending_original_store_intent_digest = None
1093
+ elif (self.profile == JOURNAL_PROFILE_02
1094
+ and payload['scope'] == 'native-store-creation'):
1095
+ # Journal 0.2 has no ingress event family; a generic store
1096
+ # effect must have its exact typed ORIGINALS parent.
1097
+ raise SupervisorJournalCodecError(
1098
+ 'supervisor-journal-origin-mismatch')
1099
+ elif (self.profile == JOURNAL_PROFILE_02
1100
+ and any(not item['confirmed'] for item in original_stores.values())):
1101
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1102
+ if (payload['scope'] == 'native-principal-preparation'
1103
+ and (principal_request is None
1104
+ or principal_request['requestDigest'] != payload['requestDigest'])):
1105
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1106
+ if (self.profile == JOURNAL_PROFILE_02
1107
+ and payload['scope'] == 'native-principal-preparation'
1108
+ and (principal_request['approvalId'] != payload['requestId']
1109
+ or principal_request['approvalId'] != payload['approvalId']
1110
+ or payload['purpose'] != creation['purpose']
1111
+ or payload['stage'] != 'native-principal-preparation'
1112
+ or payload['effectKey'] != [
1113
+ 'native-principal-preparation', self.supervisor_id,
1114
+ principal_request['intent']['preparationId']])):
1115
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1116
+ if (payload['scope'] == 'local-target-registration'
1117
+ and (registration_request is None
1118
+ or not registration_signature_verified
1119
+ or registration_request['requestDigest'] != payload['requestDigest'])):
1120
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1121
+ native_effects[payload['reservationId']] = {
1122
+ 'intent': payload, 'outcome': None,
1123
+ }
1124
+ if payload['scope'] == 'native-principal-preparation':
1125
+ principal_stages[payload['reservationId']] = {
1126
+ 'roles': None, 'database': None,
1127
+ }
1128
+ elif kind == 'principal-roles-intent':
1129
+ reservation_id = payload.get('reservationId') if type(payload) is dict else None
1130
+ stages = principal_stages.get(reservation_id)
1131
+ if (not running or stages is None or stages['roles'] is not None
1132
+ or set(payload) != {'reservationId', 'preparationId'}
1133
+ or type(payload['preparationId']) is not str):
1134
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1135
+ stages['roles'] = 'pending:' + payload['preparationId']
1136
+ elif kind == 'principal-roles-confirmed':
1137
+ reservation_id = payload.get('reservationId') if type(payload) is dict else None
1138
+ stages = principal_stages.get(reservation_id)
1139
+ if (not running or stages is None or stages['roles'] is None
1140
+ or stages['roles'].startswith('confirmed:')
1141
+ or set(payload) != {'reservationId', 'observationDigest'}
1142
+ or not _HEX.fullmatch(payload['observationDigest'])):
1143
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1144
+ stages['roles'] = 'confirmed:' + payload['observationDigest']
1145
+ elif kind == 'principal-database-intent':
1146
+ reservation_id = payload.get('reservationId') if type(payload) is dict else None
1147
+ stages = principal_stages.get(reservation_id)
1148
+ if (not running or stages is None or stages['roles'] is None
1149
+ or not stages['roles'].startswith('confirmed:')
1150
+ or stages['database'] is not None
1151
+ or set(payload) != {'reservationId', 'databaseName'}
1152
+ or type(payload['databaseName']) is not str):
1153
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1154
+ stages['database'] = 'pending:' + payload['databaseName']
1155
+ elif kind == 'principal-database-confirmed':
1156
+ reservation_id = payload.get('reservationId') if type(payload) is dict else None
1157
+ stages = principal_stages.get(reservation_id)
1158
+ if (not running or stages is None or stages['database'] is None
1159
+ or stages['database'].startswith('confirmed:')
1160
+ or set(payload) != {'reservationId', 'databaseOid',
1161
+ 'systemIdentifier'}
1162
+ or type(payload['databaseOid']) is not int
1163
+ or payload['databaseOid'] <= 0
1164
+ or type(payload['systemIdentifier']) is not str):
1165
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1166
+ stages['database'] = ('confirmed:' + str(payload['databaseOid']) + ':'
1167
+ + payload['systemIdentifier'])
1168
+ elif kind in ('native-effect-confirmed', 'native-effect-aborted'):
1169
+ reservation_id = payload.get('reservationId')
1170
+ scope = (native_effects.get(reservation_id, {})
1171
+ .get('intent', {}).get('scope'))
1172
+ if ((not running and scope != 'local-target-creation')
1173
+ or set(payload) != {'reservationId', 'receiptDigest'}
1174
+ or payload['reservationId'] not in native_effects
1175
+ or native_effects[payload['reservationId']]['outcome'] is not None
1176
+ or not _HEX.fullmatch(payload['receiptDigest'])):
1177
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1178
+ if scope == 'native-principal-preparation':
1179
+ stages = principal_stages[payload['reservationId']]
1180
+ if (stages['roles'] is None or not stages['roles'].startswith('confirmed:')
1181
+ or stages['database'] is None
1182
+ or not stages['database'].startswith('confirmed:')):
1183
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1184
+ if (self.profile == JOURNAL_PROFILE_02
1185
+ and scope == 'native-store-creation'
1186
+ and (kind != 'native-effect-confirmed'
1187
+ or reservation_id not in store_effects_by_reservation
1188
+ or not store_effects_by_reservation[reservation_id]['confirmed']
1189
+ or payload['receiptDigest'] != store_effects_by_reservation[
1190
+ reservation_id]['nativeReceiptDigest'])):
1191
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1192
+ if self.profile == JOURNAL_PROFILE_02 and scope == 'native-store-creation':
1193
+ store_effects_by_reservation[reservation_id][
1194
+ 'nativeEffectOutcome'] = 'confirmed'
1195
+ native_effects[payload['reservationId']]['outcome'] = (
1196
+ 'confirmed' if kind == 'native-effect-confirmed' else 'known-aborted',
1197
+ payload['receiptDigest'])
1198
+ elif kind == 'creation-finalized':
1199
+ if (not running or not created or not initdb
1200
+ or (self.profile == JOURNAL_PROFILE_02
1201
+ and creation_finalized is not None)
1202
+ or set(payload) != {'receipt', 'receiptDigest'}
1203
+ or type(payload['receipt']) is not dict
1204
+ or _digest(payload['receipt']) != payload['receiptDigest']
1205
+ or not _HEX.fullmatch(payload['receiptDigest'])):
1206
+ raise SupervisorJournalCodecError('supervisor-journal-order-invalid')
1207
+ receipt = payload['receipt']
1208
+ if (set(receipt) != {'profile', 'supervisorId', 'clusterId',
1209
+ 'incarnationId', 'creationRequestDigest',
1210
+ 'creationApprovalDigest', 'initdbReceiptDigest',
1211
+ 'initialLaunchReceiptDigest',
1212
+ 'principalPreparationRequestDigest',
1213
+ 'principalPreparationApprovalDigest',
1214
+ 'principalPreparationReceiptDigest', 'applicationDatabase'}
1215
+ or receipt['profile'] != 'umf.local-supervisor-creation-receipt/0.1'
1216
+ or receipt['supervisorId'] != self.supervisor_id
1217
+ or not all(_HEX.fullmatch(receipt[key]) for key in (
1218
+ 'creationRequestDigest', 'creationApprovalDigest',
1219
+ 'initdbReceiptDigest', 'initialLaunchReceiptDigest',
1220
+ 'principalPreparationRequestDigest',
1221
+ 'principalPreparationApprovalDigest',
1222
+ 'principalPreparationReceiptDigest'))):
1223
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1224
+ if self.profile == JOURNAL_PROFILE_02:
1225
+ assert creation is not None and initdb_receipt is not None
1226
+ if (receipt['clusterId'] != creation['clusterId']
1227
+ or receipt['incarnationId'] != creation['incarnationId']
1228
+ or receipt['creationRequestDigest'] != creation['requestDigest']
1229
+ or receipt['creationApprovalDigest'] != creation['approvalDigest']
1230
+ or receipt['initdbReceiptDigest'] != initdb_receipt['initdbReceiptDigest']):
1231
+ raise SupervisorJournalCodecError('supervisor-journal-origin-mismatch')
1232
+ principal_effects = [item for item in native_effects.values()
1233
+ if item['intent'].get('scope')
1234
+ == 'native-principal-preparation']
1235
+ principal_outcome = (principal_effects[0].get('outcome')
1236
+ if len(principal_effects) == 1 else None)
1237
+ if (principal_request is None or len(principal_effects) != 1
1238
+ or type(principal_outcome) is not tuple
1239
+ or not principal_outcome
1240
+ or principal_outcome[0] != 'confirmed'
1241
+ or receipt['principalPreparationRequestDigest']
1242
+ != principal_effects[0]['intent']['requestDigest']
1243
+ or receipt['principalPreparationApprovalDigest']
1244
+ != principal_effects[0]['intent']['approvalDigest']):
1245
+ raise SupervisorJournalCodecError(
1246
+ 'supervisor-journal-origin-mismatch')
1247
+ principal_authority_done = True
1248
+ creation_finalized = payload
1249
+ else:
1250
+ raise SupervisorJournalCodecError('supervisor-journal-corrupt')
1251
+