umf-access 0.1.0.dev8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Pure target-custody journal encoding and validation primitives."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
JOURNAL_PROFILE = 'umf.local-target-custody-journal/0.1'
|
|
12
|
+
JOURNAL_PROFILE_02 = 'umf.local-target-custody-journal/0.2'
|
|
13
|
+
_MAX_BYTES = 8 * 1024 * 1024
|
|
14
|
+
_MAX_EVENTS = 4096
|
|
15
|
+
_MAX_SAFE = 9_007_199_254_740_991
|
|
16
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
17
|
+
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
|
|
18
|
+
_OWNER_REQUEST_KIND = 'umf.local-owner-target-registration/0.1'
|
|
19
|
+
_KINDS = frozenset({
|
|
20
|
+
'registration-intent', 'registration-observation', 'registration-confirmed',
|
|
21
|
+
'epoch-provision-reserved', 'epoch-provision-observation', 'epoch-provision-confirmed',
|
|
22
|
+
'transition-reserved', 'transition-observation', 'transition-confirmed',
|
|
23
|
+
})
|
|
24
|
+
_KINDS_02 = _KINDS | frozenset({
|
|
25
|
+
'originals-store-reserved', 'originals-store-observation',
|
|
26
|
+
'originals-store-confirmed',
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CustodyJournalError(RuntimeError):
|
|
31
|
+
"""Fixed journal failure without leaking private payloads or paths."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, code: str):
|
|
34
|
+
super().__init__(code)
|
|
35
|
+
self.code = code
|
|
36
|
+
|
|
37
|
+
def _validate_observation(observation: dict[str, Any], payload: dict[str, Any]) -> None:
|
|
38
|
+
_closed(observation, {'profile', 'registrationDigest', 'originReceiptDigest',
|
|
39
|
+
'currentLaunchReceiptDigest', 'continuityChainDigest', 'endpointGateReceiptDigest',
|
|
40
|
+
'nativeObservationDigest', 'custodianSequence'})
|
|
41
|
+
if observation['profile'] != 'umf.local-target-registration-observation/0.1':
|
|
42
|
+
raise CustodyJournalError('journal-invalid')
|
|
43
|
+
for key in ('registrationDigest', 'originReceiptDigest', 'currentLaunchReceiptDigest',
|
|
44
|
+
'continuityChainDigest', 'endpointGateReceiptDigest', 'nativeObservationDigest'):
|
|
45
|
+
_hex(observation[key])
|
|
46
|
+
if (type(observation['custodianSequence']) is not int
|
|
47
|
+
or not 1 <= observation['custodianSequence'] <= _MAX_SAFE):
|
|
48
|
+
raise CustodyJournalError('journal-invalid')
|
|
49
|
+
if (observation['originReceiptDigest'] != payload['origin']['creationReceiptDigest']
|
|
50
|
+
or observation['endpointGateReceiptDigest'] != payload['endpointControl']['authorityReceiptDigest']):
|
|
51
|
+
raise CustodyJournalError('owner-observation-mismatch')
|
|
52
|
+
def _canonical(value: Any) -> bytes:
|
|
53
|
+
"""Encode a bounded JSON value, rejecting Python-only and unsafe values."""
|
|
54
|
+
pending = [(value, 0)]
|
|
55
|
+
nodes = 0
|
|
56
|
+
while pending:
|
|
57
|
+
item, depth = pending.pop()
|
|
58
|
+
nodes += 1
|
|
59
|
+
if nodes > 100_000 or depth > 48:
|
|
60
|
+
raise CustodyJournalError('journal-capacity')
|
|
61
|
+
if item is None or type(item) is bool:
|
|
62
|
+
continue
|
|
63
|
+
if type(item) is int:
|
|
64
|
+
if abs(item) > _MAX_SAFE:
|
|
65
|
+
raise CustodyJournalError('journal-invalid')
|
|
66
|
+
elif type(item) is str:
|
|
67
|
+
try:
|
|
68
|
+
item.encode('utf-8')
|
|
69
|
+
except UnicodeEncodeError:
|
|
70
|
+
raise CustodyJournalError('journal-invalid') from None
|
|
71
|
+
if '\x00' in item:
|
|
72
|
+
raise CustodyJournalError('journal-invalid')
|
|
73
|
+
elif type(item) is list:
|
|
74
|
+
if len(item) > _MAX_EVENTS:
|
|
75
|
+
raise CustodyJournalError('journal-capacity')
|
|
76
|
+
pending.extend((child, depth + 1) for child in item)
|
|
77
|
+
elif type(item) is dict:
|
|
78
|
+
if len(item) > 128 or any(type(key) is not str or not key.isascii() for key in item):
|
|
79
|
+
raise CustodyJournalError('journal-invalid')
|
|
80
|
+
pending.extend((child, depth + 1) for child in item.values())
|
|
81
|
+
else:
|
|
82
|
+
raise CustodyJournalError('journal-invalid')
|
|
83
|
+
try:
|
|
84
|
+
data = json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
85
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
86
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
87
|
+
raise CustodyJournalError('journal-invalid') from None
|
|
88
|
+
if len(data) > _MAX_BYTES:
|
|
89
|
+
raise CustodyJournalError('journal-capacity')
|
|
90
|
+
return data
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _digest(value: Any) -> str:
|
|
94
|
+
return hashlib.sha256(_canonical(value)).hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _pairs_no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
98
|
+
result: dict[str, Any] = {}
|
|
99
|
+
for key, value in pairs:
|
|
100
|
+
if key in result:
|
|
101
|
+
raise CustodyJournalError('journal-corrupt')
|
|
102
|
+
result[key] = value
|
|
103
|
+
return result
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _read_json(data: bytes) -> Any:
|
|
107
|
+
try:
|
|
108
|
+
value = json.loads(data.decode('utf-8'), object_pairs_hook=_pairs_no_duplicates,
|
|
109
|
+
parse_constant=lambda _value: (_ for _ in ()).throw(
|
|
110
|
+
CustodyJournalError('journal-corrupt')))
|
|
111
|
+
except CustodyJournalError:
|
|
112
|
+
raise
|
|
113
|
+
except (UnicodeError, ValueError, RecursionError):
|
|
114
|
+
raise CustodyJournalError('journal-corrupt') from None
|
|
115
|
+
if _canonical(value) != data:
|
|
116
|
+
raise CustodyJournalError('journal-corrupt')
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _closed(value: Any, keys: set[str]) -> dict[str, Any]:
|
|
121
|
+
if type(value) is not dict or set(value) != keys:
|
|
122
|
+
raise CustodyJournalError('journal-invalid')
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _text(value: Any, maximum: int = 4096) -> str:
|
|
127
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
128
|
+
raise CustodyJournalError('journal-invalid')
|
|
129
|
+
try:
|
|
130
|
+
size = len(value.encode('utf-8'))
|
|
131
|
+
except UnicodeEncodeError:
|
|
132
|
+
raise CustodyJournalError('journal-invalid') from None
|
|
133
|
+
if size > maximum:
|
|
134
|
+
raise CustodyJournalError('journal-invalid')
|
|
135
|
+
return value
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _safe_uint32(value: Any) -> int:
|
|
139
|
+
if type(value) is not int or not 1 <= value <= 2**32 - 1:
|
|
140
|
+
raise CustodyJournalError('journal-invalid')
|
|
141
|
+
return value
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _uuid(value: Any) -> str:
|
|
145
|
+
if type(value) is not str or not _UUID.fullmatch(value):
|
|
146
|
+
raise CustodyJournalError('journal-invalid')
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _hex(value: Any) -> str:
|
|
151
|
+
if type(value) is not str or not _HEX.fullmatch(value):
|
|
152
|
+
raise CustodyJournalError('journal-invalid')
|
|
153
|
+
return value
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _decimal(value: Any, maximum: int) -> str:
|
|
157
|
+
if (type(value) is not str or not value.isascii() or not value.isdecimal()
|
|
158
|
+
or (len(value) > 1 and value[0] == '0') or int(value) > maximum):
|
|
159
|
+
raise CustodyJournalError('journal-invalid')
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _validate_owner_payload(owner: Any) -> None:
|
|
164
|
+
_closed(owner, {'profile', 'registrationId', 'custodianId', 'providerId',
|
|
165
|
+
'installationId', 'ownerApproval', 'origin', 'endpointControl'})
|
|
166
|
+
if owner['profile'] != 'umf.local-owner-target-registration/0.1':
|
|
167
|
+
raise CustodyJournalError('journal-invalid')
|
|
168
|
+
for key in ('registrationId', 'custodianId', 'providerId'):
|
|
169
|
+
_uuid(owner[key])
|
|
170
|
+
_text(owner['installationId'], 128)
|
|
171
|
+
_closed(owner['ownerApproval'], {'authorityId', 'approvalId', 'approvalDigest', 'scope'})
|
|
172
|
+
approval = owner['ownerApproval']
|
|
173
|
+
_text(approval['authorityId'], 256); _uuid(approval['approvalId']); _hex(approval['approvalDigest'])
|
|
174
|
+
if approval['scope'] != 'enroll-owned-local-postgresql-target':
|
|
175
|
+
raise CustodyJournalError('journal-invalid')
|
|
176
|
+
origin = owner['origin']
|
|
177
|
+
_closed(origin, {'profile', 'supervisorId', 'clusterId', 'incarnationId',
|
|
178
|
+
'creationReceiptDigest', 'nativeBinary', 'dataDirectory', 'initialPostmaster',
|
|
179
|
+
'database', 'endpoint'})
|
|
180
|
+
if origin['profile'] != 'postgresql18-local-supervised-origin/0.1':
|
|
181
|
+
raise CustodyJournalError('journal-invalid')
|
|
182
|
+
for key in ('supervisorId', 'clusterId', 'incarnationId'):
|
|
183
|
+
_uuid(origin[key])
|
|
184
|
+
_hex(origin['creationReceiptDigest'])
|
|
185
|
+
binary = origin['nativeBinary']
|
|
186
|
+
_closed(binary, {'path', 'sha256', 'version'})
|
|
187
|
+
_canonical_path(binary['path']); _hex(binary['sha256'])
|
|
188
|
+
if binary['version'] != '18.6':
|
|
189
|
+
raise CustodyJournalError('journal-invalid')
|
|
190
|
+
directory = origin['dataDirectory']
|
|
191
|
+
_closed(directory, {'path', 'device', 'inode', 'ownerUid'})
|
|
192
|
+
_canonical_path(directory['path'])
|
|
193
|
+
_decimal(directory['device'], 18_446_744_073_709_551_615)
|
|
194
|
+
_decimal(directory['inode'], 18_446_744_073_709_551_615)
|
|
195
|
+
if type(directory['ownerUid']) is not int or not 0 <= directory['ownerUid'] <= 4_294_967_295:
|
|
196
|
+
raise CustodyJournalError('journal-invalid')
|
|
197
|
+
postmaster = origin['initialPostmaster']
|
|
198
|
+
_closed(postmaster, {'pid', 'startToken', 'launchReceiptDigest'})
|
|
199
|
+
if type(postmaster['pid']) is not int or not 1 <= postmaster['pid'] <= 2_147_483_647:
|
|
200
|
+
raise CustodyJournalError('journal-invalid')
|
|
201
|
+
token = postmaster['startToken']
|
|
202
|
+
if type(token) is not str or not token.isascii() or not 1 <= len(token) <= 128:
|
|
203
|
+
raise CustodyJournalError('journal-invalid')
|
|
204
|
+
_hex(postmaster['launchReceiptDigest'])
|
|
205
|
+
database = origin['database']
|
|
206
|
+
_closed(database, {'name', 'oid', 'systemIdentifier'})
|
|
207
|
+
_text(database['name'], 63)
|
|
208
|
+
if type(database['oid']) is not int or not 1 <= database['oid'] <= 4_294_967_295:
|
|
209
|
+
raise CustodyJournalError('journal-invalid')
|
|
210
|
+
_decimal(database['systemIdentifier'], 18_446_744_073_709_551_615)
|
|
211
|
+
endpoint = origin['endpoint']
|
|
212
|
+
_closed(endpoint, {'host', 'port'})
|
|
213
|
+
if endpoint['host'] != '127.0.0.1' or type(endpoint['port']) is not int or not 1 <= endpoint['port'] <= 65535:
|
|
214
|
+
raise CustodyJournalError('journal-invalid')
|
|
215
|
+
control = owner['endpointControl']
|
|
216
|
+
_closed(control, {'controllerId', 'profile', 'authorityReceiptDigest'})
|
|
217
|
+
_uuid(control['controllerId']); _hex(control['authorityReceiptDigest'])
|
|
218
|
+
if control['profile'] != 'umf.local-postgresql-endpoint-controller/0.1':
|
|
219
|
+
raise CustodyJournalError('journal-invalid')
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _canonical_path(value: Any) -> str:
|
|
223
|
+
path = _text(value, 4096)
|
|
224
|
+
if not os.path.isabs(path) or os.path.normpath(path) != path:
|
|
225
|
+
raise CustodyJournalError('journal-invalid')
|
|
226
|
+
return path
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _validate_event_payload(kind: str, payload: Any, *, profile: str = JOURNAL_PROFILE) -> dict[str, Any]:
|
|
230
|
+
"""Validate the fixed journal event envelopes and their exact references."""
|
|
231
|
+
if kind == 'registration-intent':
|
|
232
|
+
_closed(payload, {'registrationId', 'registrationDigest', 'ownerPayload', 'ownerApproval'})
|
|
233
|
+
_uuid(payload['registrationId']); _hex(payload['registrationDigest'])
|
|
234
|
+
_validate_owner_payload(payload['ownerPayload'])
|
|
235
|
+
owner = payload['ownerPayload']
|
|
236
|
+
if owner['registrationId'] != payload['registrationId']:
|
|
237
|
+
raise CustodyJournalError('journal-invalid')
|
|
238
|
+
approval = owner['ownerApproval']
|
|
239
|
+
_closed(payload['ownerApproval'], {'approvalId', 'approvalDigest'})
|
|
240
|
+
if payload['ownerApproval'] != {'approvalId': approval['approvalId'],
|
|
241
|
+
'approvalDigest': approval['approvalDigest']}:
|
|
242
|
+
raise CustodyJournalError('journal-invalid')
|
|
243
|
+
elif kind == 'registration-observation':
|
|
244
|
+
_closed(payload, {'registrationId', 'observation'})
|
|
245
|
+
_uuid(payload['registrationId'])
|
|
246
|
+
observation = payload['observation']
|
|
247
|
+
_closed(observation, {'profile', 'registrationDigest', 'originReceiptDigest',
|
|
248
|
+
'currentLaunchReceiptDigest', 'continuityChainDigest', 'endpointGateReceiptDigest',
|
|
249
|
+
'nativeObservationDigest', 'custodianSequence'})
|
|
250
|
+
if observation['profile'] != 'umf.local-target-registration-observation/0.1':
|
|
251
|
+
raise CustodyJournalError('journal-invalid')
|
|
252
|
+
for key in ('registrationDigest', 'originReceiptDigest', 'currentLaunchReceiptDigest',
|
|
253
|
+
'continuityChainDigest', 'endpointGateReceiptDigest', 'nativeObservationDigest'):
|
|
254
|
+
_hex(observation[key])
|
|
255
|
+
sequence = observation['custodianSequence']
|
|
256
|
+
if type(sequence) is not int or not 1 <= sequence <= _MAX_SAFE:
|
|
257
|
+
raise CustodyJournalError('journal-invalid')
|
|
258
|
+
elif kind == 'registration-confirmed':
|
|
259
|
+
_closed(payload, {'registrationId', 'targetCustody'})
|
|
260
|
+
_uuid(payload['registrationId'])
|
|
261
|
+
custody = payload['targetCustody']
|
|
262
|
+
_closed(custody, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
263
|
+
'incarnation', 'registrationDigest'})
|
|
264
|
+
if custody['profile'] != 'umf.native-target-custody/0.1' or custody['registrationId'] != payload['registrationId']:
|
|
265
|
+
raise CustodyJournalError('journal-invalid')
|
|
266
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
267
|
+
_text(custody[key], 256)
|
|
268
|
+
_hex(custody['registrationDigest'])
|
|
269
|
+
elif kind == 'epoch-provision-reserved':
|
|
270
|
+
_closed(payload, {'request', 'requestDigest', 'provisioningApprovalDigest', 'reservation'})
|
|
271
|
+
_hex(payload['requestDigest']); _hex(payload['provisioningApprovalDigest'])
|
|
272
|
+
request = payload['request']
|
|
273
|
+
_closed(request, {'profile', 'providerId', 'enrollmentId', 'installationId', 'targetCustody',
|
|
274
|
+
'planDigest', 'fileDigest', 'expectedHead', 'previousSourceDigest', 'nextSourceDigest',
|
|
275
|
+
'nextBundleDigest', 'newEpoch', 'issuerProfile', 'principals', 'maximumRoles'})
|
|
276
|
+
if request['profile'] != 'umf.ingress-epoch-provision/0.1':
|
|
277
|
+
raise CustodyJournalError('journal-invalid')
|
|
278
|
+
if payload['requestDigest'] != _digest(request):
|
|
279
|
+
raise CustodyJournalError('journal-invalid')
|
|
280
|
+
for key in ('providerId', 'enrollmentId', 'newEpoch'):
|
|
281
|
+
_uuid(request[key])
|
|
282
|
+
if request['profile'] != 'umf.ingress-epoch-provision/0.1':
|
|
283
|
+
raise CustodyJournalError('journal-invalid')
|
|
284
|
+
for key in ('planDigest', 'fileDigest', 'expectedHead', 'previousSourceDigest',
|
|
285
|
+
'nextSourceDigest', 'nextBundleDigest'):
|
|
286
|
+
_hex(request[key])
|
|
287
|
+
_text(request['installationId'], 128); _text(request['issuerProfile'], 256)
|
|
288
|
+
custody = request['targetCustody']
|
|
289
|
+
_closed(custody, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
290
|
+
'incarnation', 'registrationDigest'})
|
|
291
|
+
if custody['profile'] != 'umf.native-target-custody/0.1':
|
|
292
|
+
raise CustodyJournalError('journal-invalid')
|
|
293
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
294
|
+
_uuid(custody[key])
|
|
295
|
+
_hex(custody['registrationDigest'])
|
|
296
|
+
if (type(request['principals']) is not list or not request['principals']
|
|
297
|
+
or type(request['maximumRoles']) is not int
|
|
298
|
+
or not 1 <= request['maximumRoles'] <= 256
|
|
299
|
+
or request['maximumRoles'] != len(request['principals'])):
|
|
300
|
+
raise CustodyJournalError('journal-invalid')
|
|
301
|
+
for item in request['principals']:
|
|
302
|
+
_closed(item, {'loginName', 'subject', 'audience'})
|
|
303
|
+
_text(item['loginName'], 63)
|
|
304
|
+
_closed(item['subject'], {'oid', 'name'})
|
|
305
|
+
if type(item['subject']['oid']) is not int or not 1 <= item['subject']['oid'] <= 2**32 - 1:
|
|
306
|
+
raise CustodyJournalError('journal-invalid')
|
|
307
|
+
_text(item['subject']['name'], 63)
|
|
308
|
+
if item['audience'] not in ('person', 'batch'):
|
|
309
|
+
raise CustodyJournalError('journal-invalid')
|
|
310
|
+
reservation = payload['reservation']
|
|
311
|
+
_closed(reservation, {'profile', 'id', 'custodianId', 'registrationId', 'incarnation',
|
|
312
|
+
'sequence', 'requestDigest', 'provisioningApprovalDigest', 'parentStateDigest'})
|
|
313
|
+
if reservation['profile'] != 'umf.native-epoch-provision-reservation/0.1':
|
|
314
|
+
raise CustodyJournalError('journal-invalid')
|
|
315
|
+
for key in ('id', 'custodianId', 'registrationId', 'incarnation'):
|
|
316
|
+
_uuid(reservation[key])
|
|
317
|
+
if (type(reservation['sequence']) is not int
|
|
318
|
+
or not 1 <= reservation['sequence'] <= _MAX_SAFE):
|
|
319
|
+
raise CustodyJournalError('journal-invalid')
|
|
320
|
+
for key in ('requestDigest', 'provisioningApprovalDigest', 'parentStateDigest'):
|
|
321
|
+
_hex(reservation[key])
|
|
322
|
+
if (reservation['requestDigest'] != payload['requestDigest']
|
|
323
|
+
or reservation['provisioningApprovalDigest'] != payload['provisioningApprovalDigest']):
|
|
324
|
+
raise CustodyJournalError('journal-invalid')
|
|
325
|
+
elif kind == 'epoch-provision-observation':
|
|
326
|
+
_closed(payload, {'reservationId', 'outcome', 'nativeReceiptDigest'})
|
|
327
|
+
_uuid(payload['reservationId'])
|
|
328
|
+
if payload['outcome'] not in ('pending', 'prepared', 'not-committed'):
|
|
329
|
+
raise CustodyJournalError('journal-invalid')
|
|
330
|
+
_hex(payload['nativeReceiptDigest']) if payload['nativeReceiptDigest'] is not None else None
|
|
331
|
+
elif kind == 'epoch-provision-confirmed':
|
|
332
|
+
_closed(payload, {'reservationId', 'nativeReceiptDigest'})
|
|
333
|
+
_uuid(payload['reservationId']); _hex(payload['nativeReceiptDigest'])
|
|
334
|
+
elif kind == 'transition-reserved':
|
|
335
|
+
_closed(payload, {'reservationId', 'request', 'requestDigest', 'ingressApprovalDigest', 'reservation'})
|
|
336
|
+
_uuid(payload['reservationId']); _hex(payload['requestDigest']); _hex(payload['ingressApprovalDigest'])
|
|
337
|
+
request = payload['request']
|
|
338
|
+
_closed(request, {'profile', 'providerId', 'enrollmentId', 'installationId',
|
|
339
|
+
'targetCustody',
|
|
340
|
+
'targetIdentityDigest', 'planDigest', 'fileDigest', 'expectedHead',
|
|
341
|
+
'previousSourceDigest', 'nextSourceDigest', 'previousBundleDigest',
|
|
342
|
+
'nextBundleDigest', 'oldEpoch', 'newEpoch', 'oldPrincipalsDigest',
|
|
343
|
+
'newPrincipalsDigest', 'approvalDigest', 'executionPolicyDigest'})
|
|
344
|
+
_uuid(request['providerId']); _uuid(request['enrollmentId'])
|
|
345
|
+
if request['profile'] != 'umf.table-generation-ingress/0.1':
|
|
346
|
+
raise CustodyJournalError('journal-invalid')
|
|
347
|
+
if payload['requestDigest'] != _digest(request) or request['oldEpoch'] == request['newEpoch']:
|
|
348
|
+
raise CustodyJournalError('journal-invalid')
|
|
349
|
+
_text(request['installationId'], 128)
|
|
350
|
+
custody = request['targetCustody']
|
|
351
|
+
_closed(custody, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
352
|
+
'incarnation', 'registrationDigest'})
|
|
353
|
+
if custody['profile'] != 'umf.native-target-custody/0.1':
|
|
354
|
+
raise CustodyJournalError('journal-invalid')
|
|
355
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
356
|
+
_uuid(custody[key])
|
|
357
|
+
_hex(custody['registrationDigest'])
|
|
358
|
+
for key in ('targetIdentityDigest', 'planDigest', 'fileDigest',
|
|
359
|
+
'previousSourceDigest', 'nextSourceDigest', 'previousBundleDigest',
|
|
360
|
+
'nextBundleDigest', 'oldPrincipalsDigest', 'newPrincipalsDigest', 'approvalDigest'):
|
|
361
|
+
_hex(request[key])
|
|
362
|
+
if request['expectedHead'] is not None:
|
|
363
|
+
_hex(request['expectedHead'])
|
|
364
|
+
_hex(request['executionPolicyDigest'])
|
|
365
|
+
_uuid(request['oldEpoch']); _uuid(request['newEpoch'])
|
|
366
|
+
reservation = payload['reservation']
|
|
367
|
+
_closed(reservation, {'profile', 'id', 'custodianId', 'registrationId', 'incarnation',
|
|
368
|
+
'sequence', 'requestDigest', 'ingressApprovalDigest', 'parentStateDigest'})
|
|
369
|
+
if reservation['profile'] != 'umf.native-target-reservation/0.1':
|
|
370
|
+
raise CustodyJournalError('journal-invalid')
|
|
371
|
+
for key in ('id', 'custodianId', 'registrationId', 'incarnation'):
|
|
372
|
+
_uuid(reservation[key])
|
|
373
|
+
sequence = reservation['sequence']
|
|
374
|
+
if type(sequence) is not int or not 1 <= sequence <= _MAX_SAFE:
|
|
375
|
+
raise CustodyJournalError('journal-invalid')
|
|
376
|
+
if (reservation['requestDigest'] != payload['requestDigest']
|
|
377
|
+
or reservation['ingressApprovalDigest'] != payload['ingressApprovalDigest']):
|
|
378
|
+
raise CustodyJournalError('journal-invalid')
|
|
379
|
+
_hex(reservation['requestDigest']); _hex(reservation['ingressApprovalDigest'])
|
|
380
|
+
_hex(reservation['parentStateDigest'])
|
|
381
|
+
elif kind == 'transition-observation':
|
|
382
|
+
_closed(payload, {'reservationId', 'nativeState', 'nativeReceiptDigest'})
|
|
383
|
+
_uuid(payload['reservationId'])
|
|
384
|
+
if payload['nativeState'] not in ('unresolved', 'prepared', 'fenced', 'cutover', 'published'):
|
|
385
|
+
raise CustodyJournalError('journal-invalid')
|
|
386
|
+
_hex(payload['nativeReceiptDigest']) if payload['nativeReceiptDigest'] is not None else None
|
|
387
|
+
elif kind == 'transition-confirmed':
|
|
388
|
+
_closed(payload, {'reservationId', 'nativeReceiptDigest'})
|
|
389
|
+
_uuid(payload['reservationId']); _hex(payload['nativeReceiptDigest'])
|
|
390
|
+
elif profile == JOURNAL_PROFILE_02 and kind == 'originals-store-reserved':
|
|
391
|
+
_closed(payload, {'purpose', 'request', 'approvalDigest', 'reservation',
|
|
392
|
+
'reservationDigest', 'parent'})
|
|
393
|
+
if payload['purpose'] not in ('production', 'native-acceptance'):
|
|
394
|
+
raise CustodyJournalError('journal-invalid')
|
|
395
|
+
request = payload['request']
|
|
396
|
+
_closed(request, {'profile', 'store', 'evidence'})
|
|
397
|
+
if request['profile'] != 'umf.owner-store-create-intent/0.1':
|
|
398
|
+
raise CustodyJournalError('journal-invalid')
|
|
399
|
+
store = request['store']
|
|
400
|
+
_closed(store, {'profile', 'storeId', 'schemaName'})
|
|
401
|
+
if (store['profile'] != 'umf.native-row-originals-store/0.1'
|
|
402
|
+
or store['schemaName'] != 'umf_originals_' + _uuid(store['storeId']).replace('-', '')):
|
|
403
|
+
raise CustodyJournalError('journal-invalid')
|
|
404
|
+
evidence = request['evidence']
|
|
405
|
+
_closed(evidence, {'profile', 'supervisorId', 'custodianId', 'providerId',
|
|
406
|
+
'installationId', 'ownerAuthorityId', 'ownerPolicyRevision',
|
|
407
|
+
'registrationDigest', 'targetCustodyDigest',
|
|
408
|
+
'authorityPreparationReceiptDigest', 'maintenance',
|
|
409
|
+
'controller', 'businessOwner', 'requiredMemberships',
|
|
410
|
+
'requiredSettings', 'nativeAuthorityObservationDigest'})
|
|
411
|
+
if evidence['profile'] != 'umf.pg18.original-store-authority-evidence/0.1':
|
|
412
|
+
raise CustodyJournalError('journal-invalid')
|
|
413
|
+
for key in ('supervisorId', 'custodianId', 'providerId', 'ownerAuthorityId'):
|
|
414
|
+
_uuid(evidence[key])
|
|
415
|
+
for key in ('registrationDigest', 'targetCustodyDigest',
|
|
416
|
+
'authorityPreparationReceiptDigest', 'nativeAuthorityObservationDigest'):
|
|
417
|
+
_hex(evidence[key])
|
|
418
|
+
_text(evidence['installationId'], 256)
|
|
419
|
+
_text(evidence['ownerPolicyRevision'], 128)
|
|
420
|
+
role_names: list[str] = []
|
|
421
|
+
role_oids: list[int] = []
|
|
422
|
+
role_flags: list[dict[str, bool]] = []
|
|
423
|
+
for role_name in ('maintenance', 'controller', 'businessOwner'):
|
|
424
|
+
role = evidence[role_name]
|
|
425
|
+
_closed(role, {'oid', 'name', 'flags'})
|
|
426
|
+
role_names.append(_text(role['name'], 63))
|
|
427
|
+
role_oids.append(_safe_uint32(role['oid']))
|
|
428
|
+
flags = role['flags']
|
|
429
|
+
_closed(flags, {'canLogin', 'superuser', 'createDatabase',
|
|
430
|
+
'createRole', 'replication', 'bypassRls', 'inherit'})
|
|
431
|
+
if any(type(flag) is not bool for flag in flags.values()):
|
|
432
|
+
raise CustodyJournalError('journal-invalid')
|
|
433
|
+
role_flags.append(flags)
|
|
434
|
+
if len(set(role_names)) != 3 or len(set(role_oids)) != 3:
|
|
435
|
+
raise CustodyJournalError('journal-invalid')
|
|
436
|
+
expected_flags = [
|
|
437
|
+
{'canLogin': True, 'superuser': True, 'createDatabase': False,
|
|
438
|
+
'createRole': False, 'replication': False, 'bypassRls': False,
|
|
439
|
+
'inherit': False},
|
|
440
|
+
{'canLogin': False, 'superuser': True, 'createDatabase': False,
|
|
441
|
+
'createRole': False, 'replication': False, 'bypassRls': False,
|
|
442
|
+
'inherit': False},
|
|
443
|
+
{'canLogin': False, 'superuser': False, 'createDatabase': False,
|
|
444
|
+
'createRole': False, 'replication': False, 'bypassRls': False,
|
|
445
|
+
'inherit': False},
|
|
446
|
+
]
|
|
447
|
+
if role_flags != expected_flags:
|
|
448
|
+
raise CustodyJournalError('journal-invalid')
|
|
449
|
+
memberships = evidence['requiredMemberships']
|
|
450
|
+
if type(memberships) is not list or len(memberships) != 2:
|
|
451
|
+
raise CustodyJournalError('journal-invalid')
|
|
452
|
+
expected_memberships = [
|
|
453
|
+
{'memberOid': role_oids[0], 'roleOid': role_oids[1],
|
|
454
|
+
'inherit': False, 'set': True, 'admin': False},
|
|
455
|
+
{'memberOid': role_oids[0], 'roleOid': role_oids[2],
|
|
456
|
+
'inherit': False, 'set': True, 'admin': False},
|
|
457
|
+
]
|
|
458
|
+
for membership in memberships:
|
|
459
|
+
_closed(membership, {'memberOid', 'roleOid', 'inherit', 'set', 'admin'})
|
|
460
|
+
if memberships != expected_memberships:
|
|
461
|
+
raise CustodyJournalError('journal-invalid')
|
|
462
|
+
settings = evidence['requiredSettings']
|
|
463
|
+
_closed(settings, {'searchPath', 'timeZone', 'rowSecurity',
|
|
464
|
+
'sessionReplicationRole', 'transactionReadOnly',
|
|
465
|
+
'transactionIsolation'})
|
|
466
|
+
if settings != {'searchPath': 'pg_catalog', 'timeZone': 'UTC',
|
|
467
|
+
'rowSecurity': 'on', 'sessionReplicationRole': 'origin',
|
|
468
|
+
'transactionReadOnly': 'off',
|
|
469
|
+
'transactionIsolation': 'read committed'}:
|
|
470
|
+
raise CustodyJournalError('journal-invalid')
|
|
471
|
+
reservation = payload['reservation']
|
|
472
|
+
_closed(reservation, {'profile', 'reservationId', 'providerId', 'installationId',
|
|
473
|
+
'targetCustody', 'store', 'creationRequestDigest',
|
|
474
|
+
'creationApprovalDigest', 'nativeAuthorityEvidenceDigest',
|
|
475
|
+
'configurationDigest', 'custodySequence'})
|
|
476
|
+
if reservation['profile'] != 'umf.row-originals-store-reservation/0.1':
|
|
477
|
+
raise CustodyJournalError('journal-invalid')
|
|
478
|
+
_uuid(reservation['reservationId']); _uuid(reservation['providerId'])
|
|
479
|
+
_text(reservation['installationId'], 256)
|
|
480
|
+
custody = reservation['targetCustody']
|
|
481
|
+
_closed(custody, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
482
|
+
'incarnation', 'registrationDigest'})
|
|
483
|
+
if custody['profile'] != 'umf.native-target-custody/0.1':
|
|
484
|
+
raise CustodyJournalError('journal-invalid')
|
|
485
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
486
|
+
_text(custody[key], 256)
|
|
487
|
+
_hex(custody['registrationDigest'])
|
|
488
|
+
_closed(reservation['store'], {'profile', 'storeId', 'schemaName'})
|
|
489
|
+
for key in ('creationRequestDigest', 'creationApprovalDigest',
|
|
490
|
+
'nativeAuthorityEvidenceDigest', 'configurationDigest'):
|
|
491
|
+
_hex(reservation[key])
|
|
492
|
+
if (type(reservation['custodySequence']) is not int
|
|
493
|
+
or not 1 <= reservation['custodySequence'] <= _MAX_SAFE
|
|
494
|
+
or reservation['providerId'] != store['storeId']
|
|
495
|
+
or reservation['store'] != store
|
|
496
|
+
or reservation['creationRequestDigest'] != _digest(request)
|
|
497
|
+
or reservation['creationApprovalDigest'] != payload['approvalDigest']
|
|
498
|
+
or reservation['nativeAuthorityEvidenceDigest'] != evidence['nativeAuthorityObservationDigest']
|
|
499
|
+
or reservation['installationId'] != evidence['installationId']
|
|
500
|
+
or reservation['providerId'] != evidence['providerId']
|
|
501
|
+
or custody['custodianId'] != evidence['custodianId']
|
|
502
|
+
or reservation['targetCustody'] != custody
|
|
503
|
+
or evidence['targetCustodyDigest'] != _digest(custody)):
|
|
504
|
+
raise CustodyJournalError('journal-invalid')
|
|
505
|
+
_hex(payload['approvalDigest']); _hex(payload['reservationDigest'])
|
|
506
|
+
if payload['reservationDigest'] != _digest(reservation):
|
|
507
|
+
raise CustodyJournalError('journal-invalid')
|
|
508
|
+
parent = payload['parent']
|
|
509
|
+
_closed(parent, {'sequence', 'headDigest'})
|
|
510
|
+
if (type(parent['sequence']) is not int or parent['sequence'] < 0
|
|
511
|
+
or parent['sequence'] > _MAX_SAFE):
|
|
512
|
+
raise CustodyJournalError('journal-invalid')
|
|
513
|
+
_hex(parent['headDigest'])
|
|
514
|
+
elif profile == JOURNAL_PROFILE_02 and kind == 'originals-store-observation':
|
|
515
|
+
_closed(payload, {'purpose', 'reservationId', 'reservationDigest',
|
|
516
|
+
'supervisorIntentDigest', 'outcome', 'nativeReceipt',
|
|
517
|
+
'nativeReceiptDigest', 'schemaOid', 'nativeObservationDigest',
|
|
518
|
+
'transactionOutcomeDigest', 'parent'})
|
|
519
|
+
if payload['purpose'] not in ('production', 'native-acceptance'):
|
|
520
|
+
raise CustodyJournalError('journal-invalid')
|
|
521
|
+
_uuid(payload['reservationId'])
|
|
522
|
+
for key in ('reservationDigest', 'supervisorIntentDigest',
|
|
523
|
+
'nativeObservationDigest', 'transactionOutcomeDigest'):
|
|
524
|
+
_hex(payload[key])
|
|
525
|
+
if payload['outcome'] not in ('committed', 'known-aborted', 'unknown'):
|
|
526
|
+
raise CustodyJournalError('journal-invalid')
|
|
527
|
+
if payload['outcome'] == 'committed':
|
|
528
|
+
if (type(payload['nativeReceipt']) is not dict
|
|
529
|
+
or type(payload['nativeReceiptDigest']) is not str
|
|
530
|
+
or type(payload['schemaOid']) is not int
|
|
531
|
+
or not 1 <= payload['schemaOid'] <= 2**32 - 1):
|
|
532
|
+
raise CustodyJournalError('journal-invalid')
|
|
533
|
+
from .row_originals_receipt import canonical_bytes, validate_receipt
|
|
534
|
+
receipt = validate_receipt(payload['nativeReceipt'])
|
|
535
|
+
if (canonical_bytes(receipt) != canonical_bytes(payload['nativeReceipt'])
|
|
536
|
+
or payload['nativeReceiptDigest'] != _digest(receipt)
|
|
537
|
+
or receipt['schemaOid'] != payload['schemaOid']):
|
|
538
|
+
raise CustodyJournalError('journal-invalid')
|
|
539
|
+
elif any(payload[key] is not None for key in
|
|
540
|
+
('nativeReceipt', 'nativeReceiptDigest', 'schemaOid')):
|
|
541
|
+
raise CustodyJournalError('journal-invalid')
|
|
542
|
+
parent = payload['parent']
|
|
543
|
+
_closed(parent, {'sequence', 'headDigest'})
|
|
544
|
+
if type(parent['sequence']) is not int or parent['sequence'] < 0:
|
|
545
|
+
raise CustodyJournalError('journal-invalid')
|
|
546
|
+
_hex(parent['headDigest'])
|
|
547
|
+
elif profile == JOURNAL_PROFILE_02 and kind == 'originals-store-confirmed':
|
|
548
|
+
_closed(payload, {'purpose', 'reservationId', 'reservationDigest',
|
|
549
|
+
'supervisorIntentDigest', 'observationEventDigest',
|
|
550
|
+
'nativeReceiptDigest', 'schemaOid'})
|
|
551
|
+
if payload['purpose'] not in ('production', 'native-acceptance'):
|
|
552
|
+
raise CustodyJournalError('journal-invalid')
|
|
553
|
+
_uuid(payload['reservationId'])
|
|
554
|
+
for key in ('reservationDigest', 'supervisorIntentDigest',
|
|
555
|
+
'observationEventDigest', 'nativeReceiptDigest'):
|
|
556
|
+
_hex(payload[key])
|
|
557
|
+
if type(payload['schemaOid']) is not int or not 1 <= payload['schemaOid'] <= 2**32 - 1:
|
|
558
|
+
raise CustodyJournalError('journal-invalid')
|
|
559
|
+
else:
|
|
560
|
+
raise CustodyJournalError('journal-invalid')
|
|
561
|
+
_canonical(payload)
|
|
562
|
+
return payload
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _replay(events: list[dict[str, Any]], *, profile: str = JOURNAL_PROFILE) -> dict[str, Any]:
|
|
566
|
+
"""Validate append ordering and return state; pending intents are retained."""
|
|
567
|
+
state: dict[str, Any] = {'registration': None, 'provision': None, 'transition': None}
|
|
568
|
+
if profile == JOURNAL_PROFILE_02:
|
|
569
|
+
state['stores'] = {}
|
|
570
|
+
operation_ids: set[tuple[str, str]] = set()
|
|
571
|
+
for event in events:
|
|
572
|
+
kind, payload = event['kind'], event['payload']
|
|
573
|
+
category = ('registration' if kind.startswith('registration-') else
|
|
574
|
+
'provision' if kind.startswith('epoch-provision-') else
|
|
575
|
+
'store' if kind.startswith('originals-store-') else 'transition')
|
|
576
|
+
if category == 'store' and profile != JOURNAL_PROFILE_02:
|
|
577
|
+
raise CustodyJournalError('journal-invalid')
|
|
578
|
+
operation_id = payload.get('registrationId' if category == 'registration' else
|
|
579
|
+
'reservationId')
|
|
580
|
+
if category == 'provision' and kind == 'epoch-provision-reserved':
|
|
581
|
+
operation_id = payload['reservation']['id']
|
|
582
|
+
if category == 'store' and kind == 'originals-store-reserved':
|
|
583
|
+
operation_id = payload['reservation']['reservationId']
|
|
584
|
+
if kind.endswith(('intent', 'reserved')):
|
|
585
|
+
marker = (category, operation_id)
|
|
586
|
+
if marker in operation_ids:
|
|
587
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
588
|
+
operation_ids.add(marker)
|
|
589
|
+
if category == 'store':
|
|
590
|
+
parent = payload.get('parent')
|
|
591
|
+
if (parent is not None
|
|
592
|
+
and (parent.get('sequence') != event['sequence'] - 1
|
|
593
|
+
or parent.get('headDigest') != event['previousDigest'])):
|
|
594
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
595
|
+
if kind == 'originals-store-reserved':
|
|
596
|
+
if (state['registration'] is None
|
|
597
|
+
or state['registration']['status'] != 'confirmed'
|
|
598
|
+
or state['provision'] is not None
|
|
599
|
+
and state['provision']['status'] != 'confirmed'
|
|
600
|
+
or state['transition'] is not None
|
|
601
|
+
and state['transition']['status'] != 'confirmed'):
|
|
602
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
603
|
+
key = tuple(payload['reservation']['targetCustody'][field]
|
|
604
|
+
for field in ('registrationId',)) + (
|
|
605
|
+
payload['reservation']['providerId'],
|
|
606
|
+
payload['reservation']['installationId'],
|
|
607
|
+
payload['reservation']['store']['profile'],
|
|
608
|
+
payload['reservation']['store']['storeId'],
|
|
609
|
+
payload['reservation']['store']['schemaName'])
|
|
610
|
+
if (payload['reservation']['targetCustody'] != state['registration']['custody']
|
|
611
|
+
or key in state['stores'] or len(state['stores']) >= 256
|
|
612
|
+
or any(item['status'] != 'confirmed'
|
|
613
|
+
for item in state['stores'].values())):
|
|
614
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
615
|
+
state['stores'][key] = {
|
|
616
|
+
'id': payload['reservation']['reservationId'], 'key': key,
|
|
617
|
+
'status': 'reserved', 'purpose': payload['purpose'],
|
|
618
|
+
'request': payload['request'], 'reservation': payload['reservation'],
|
|
619
|
+
'reservationDigest': payload['reservationDigest'],
|
|
620
|
+
'approvalDigest': payload['approvalDigest'], 'observations': [],
|
|
621
|
+
}
|
|
622
|
+
elif kind == 'originals-store-observation':
|
|
623
|
+
current = next((item for item in state['stores'].values()
|
|
624
|
+
if item['id'] == payload['reservationId']), None)
|
|
625
|
+
prior_intent_digest = (current.get('observedSupervisorIntentDigest')
|
|
626
|
+
if current is not None else None)
|
|
627
|
+
if (current is None or current['status'] not in ('reserved', 'observed-committed')
|
|
628
|
+
or current['purpose'] != payload['purpose']
|
|
629
|
+
or current['reservationDigest'] != payload['reservationDigest']
|
|
630
|
+
or prior_intent_digest is not None
|
|
631
|
+
and prior_intent_digest != payload['supervisorIntentDigest']):
|
|
632
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
633
|
+
if current['status'] == 'observed-committed':
|
|
634
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
635
|
+
current['observedSupervisorIntentDigest'] = payload['supervisorIntentDigest']
|
|
636
|
+
current['observations'].append({
|
|
637
|
+
'eventDigest': event['recordDigest'], 'payload': payload})
|
|
638
|
+
if payload['outcome'] == 'committed':
|
|
639
|
+
receipt = payload['nativeReceipt']
|
|
640
|
+
reservation = current['reservation']
|
|
641
|
+
if (receipt['profile'] != 'umf.originals-creation-receipt/0.1'
|
|
642
|
+
or receipt['providerId'] != reservation['providerId']
|
|
643
|
+
or receipt['installationId'] != reservation['installationId']
|
|
644
|
+
or receipt['storeProfile'] != reservation['store']['profile']
|
|
645
|
+
or receipt['storeId'] != reservation['store']['storeId']
|
|
646
|
+
or receipt['reservationDigest'] != current['reservationDigest']
|
|
647
|
+
or receipt['creationRequestDigest']
|
|
648
|
+
!= reservation['creationRequestDigest']
|
|
649
|
+
or receipt['creationApprovalDigest']
|
|
650
|
+
!= reservation['creationApprovalDigest']
|
|
651
|
+
or receipt['targetCustodyDigest']
|
|
652
|
+
!= _digest(reservation['targetCustody'])
|
|
653
|
+
or receipt['schemaOid'] != payload['schemaOid']
|
|
654
|
+
or receipt['state'] != 'created'):
|
|
655
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
656
|
+
current.update(status='observed-committed',
|
|
657
|
+
observedSupervisorIntentDigest=payload['supervisorIntentDigest'],
|
|
658
|
+
nativeReceiptDigest=payload['nativeReceiptDigest'],
|
|
659
|
+
schemaOid=payload['schemaOid'])
|
|
660
|
+
elif kind == 'originals-store-confirmed':
|
|
661
|
+
current = next((item for item in state['stores'].values()
|
|
662
|
+
if item['id'] == payload['reservationId']), None)
|
|
663
|
+
if (current is None or current['status'] != 'observed-committed'
|
|
664
|
+
or current['purpose'] != payload['purpose']
|
|
665
|
+
or current['reservationDigest'] != payload['reservationDigest']
|
|
666
|
+
or current['observedSupervisorIntentDigest']
|
|
667
|
+
!= payload['supervisorIntentDigest']
|
|
668
|
+
or current['observations'][-1]['eventDigest']
|
|
669
|
+
!= payload['observationEventDigest']
|
|
670
|
+
or current['nativeReceiptDigest'] != payload['nativeReceiptDigest']
|
|
671
|
+
or current['schemaOid'] != payload['schemaOid']):
|
|
672
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
673
|
+
current['status'] = 'confirmed'
|
|
674
|
+
continue
|
|
675
|
+
if kind == 'registration-intent':
|
|
676
|
+
if state['registration'] is not None:
|
|
677
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
678
|
+
state['registration'] = {'id': payload['registrationId'], 'status': 'intent'}
|
|
679
|
+
elif kind == 'registration-observation':
|
|
680
|
+
current = state['registration']
|
|
681
|
+
if (current is None or current['status'] not in ('intent', 'observed', 'confirmed')
|
|
682
|
+
or current['id'] != payload['registrationId']):
|
|
683
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
684
|
+
prior_observation = current.get('observation')
|
|
685
|
+
if (prior_observation is not None
|
|
686
|
+
and payload['observation']['custodianSequence'] < prior_observation['custodianSequence']):
|
|
687
|
+
raise CustodyJournalError('journal-sequence-rewound')
|
|
688
|
+
current['observation'] = payload['observation']
|
|
689
|
+
if current['status'] != 'confirmed':
|
|
690
|
+
current['status'] = 'observed'
|
|
691
|
+
elif kind == 'registration-confirmed':
|
|
692
|
+
current = state['registration']
|
|
693
|
+
if current is None or current['status'] != 'observed' or current['id'] != payload['registrationId']:
|
|
694
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
695
|
+
current.update(status='confirmed', custody=payload['targetCustody'])
|
|
696
|
+
elif kind == 'epoch-provision-reserved':
|
|
697
|
+
current = state['provision']
|
|
698
|
+
if (state['registration'] is None or state['registration']['status'] != 'confirmed'
|
|
699
|
+
or current and current['status'] != 'confirmed'
|
|
700
|
+
or profile == JOURNAL_PROFILE_02
|
|
701
|
+
and any(item['status'] != 'confirmed' for item in state['stores'].values())):
|
|
702
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
703
|
+
if payload['request']['targetCustody'] != state['registration']['custody']:
|
|
704
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
705
|
+
reservation_id = payload['reservation']['id']
|
|
706
|
+
state['provision'] = {'id': reservation_id, 'status': 'reserved', 'request': payload['request'],
|
|
707
|
+
'reservation': payload['reservation']}
|
|
708
|
+
elif kind == 'epoch-provision-observation':
|
|
709
|
+
current = state['provision']
|
|
710
|
+
if (current is None or current['id'] != payload['reservationId']
|
|
711
|
+
or current['status'] not in ('reserved', 'observed')):
|
|
712
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
713
|
+
if current.get('outcome') == 'prepared' and payload['outcome'] != 'prepared':
|
|
714
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
715
|
+
current.update(status='observed', outcome=payload['outcome'], receipt=payload['nativeReceiptDigest'])
|
|
716
|
+
elif kind == 'epoch-provision-confirmed':
|
|
717
|
+
current = state['provision']
|
|
718
|
+
if (current is None or current['id'] != payload['reservationId']
|
|
719
|
+
or current['status'] != 'observed' or current['outcome'] != 'prepared'
|
|
720
|
+
or current['receipt'] != payload['nativeReceiptDigest']):
|
|
721
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
722
|
+
current['status'] = 'confirmed'
|
|
723
|
+
elif kind == 'transition-reserved':
|
|
724
|
+
current = state['transition']
|
|
725
|
+
if (state['provision'] is None or state['provision']['status'] != 'confirmed'
|
|
726
|
+
or current and current['status'] != 'confirmed'
|
|
727
|
+
or profile == JOURNAL_PROFILE_02
|
|
728
|
+
and any(item['status'] != 'confirmed' for item in state['stores'].values())):
|
|
729
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
730
|
+
if payload['request']['targetCustody'] != state['registration']['custody']:
|
|
731
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
732
|
+
state['transition'] = {'id': payload['reservationId'], 'status': 'reserved', 'request': payload['request']}
|
|
733
|
+
elif kind == 'transition-observation':
|
|
734
|
+
current = state['transition']
|
|
735
|
+
if (current is None or current['id'] != payload['reservationId']
|
|
736
|
+
or current['status'] not in ('reserved', 'observed')):
|
|
737
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
738
|
+
order = {'unresolved': 0, 'prepared': 1, 'fenced': 2, 'cutover': 3, 'published': 4}
|
|
739
|
+
if (current.get('nativeState') is not None
|
|
740
|
+
and order[payload['nativeState']] < order[current['nativeState']]):
|
|
741
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
742
|
+
current.update(status='observed', nativeState=payload['nativeState'], receipt=payload['nativeReceiptDigest'])
|
|
743
|
+
elif kind == 'transition-confirmed':
|
|
744
|
+
current = state['transition']
|
|
745
|
+
if (current is None or current['id'] != payload['reservationId']
|
|
746
|
+
or current['status'] != 'observed'
|
|
747
|
+
or current['nativeState'] not in ('fenced', 'cutover', 'published')
|
|
748
|
+
or current['receipt'] != payload['nativeReceiptDigest']):
|
|
749
|
+
raise CustodyJournalError('journal-order-invalid')
|
|
750
|
+
current['status'] = 'confirmed'
|
|
751
|
+
return state
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def validate_original_target_custody_record(raw: bytes,
|
|
755
|
+
birth: dict[str, Any]) -> dict[str, Any]:
|
|
756
|
+
"""Validate a 0.2 chain against an already resolved original birth."""
|
|
757
|
+
if type(raw) is not bytes or not 1 <= len(raw) <= _MAX_BYTES:
|
|
758
|
+
raise CustodyJournalError('journal-corrupt')
|
|
759
|
+
doc = _read_json(raw)
|
|
760
|
+
_closed(doc, {'profile', 'custodianId', 'sequence', 'headDigest', 'events'})
|
|
761
|
+
if (doc['profile'] != JOURNAL_PROFILE_02
|
|
762
|
+
or doc['custodianId'] != birth.get('custodianId')
|
|
763
|
+
or type(doc['events']) is not list or len(doc['events']) > _MAX_EVENTS
|
|
764
|
+
or type(doc['sequence']) is not int
|
|
765
|
+
or doc['sequence'] != len(doc['events'])):
|
|
766
|
+
raise CustodyJournalError('journal-corrupt')
|
|
767
|
+
initial = {'profile': JOURNAL_PROFILE_02,
|
|
768
|
+
'custodianId': birth['custodianId'], 'sequence': 0,
|
|
769
|
+
'headDigest': '0' * 64, 'events': []}
|
|
770
|
+
if hashlib.sha256(_canonical(initial)).hexdigest() != birth.get('initialHeaderDigest'):
|
|
771
|
+
raise CustodyJournalError('journal-origin-unverified')
|
|
772
|
+
previous = '0' * 64
|
|
773
|
+
for index, event in enumerate(doc['events'], 1):
|
|
774
|
+
_closed(event, {'sequence', 'kind', 'payload', 'previousDigest', 'recordDigest'})
|
|
775
|
+
if (type(event['sequence']) is not int or event['sequence'] != index
|
|
776
|
+
or event['previousDigest'] != previous
|
|
777
|
+
or event['kind'] not in _KINDS_02):
|
|
778
|
+
raise CustodyJournalError('journal-corrupt')
|
|
779
|
+
_validate_event_payload(event['kind'], event['payload'], profile=JOURNAL_PROFILE_02)
|
|
780
|
+
unhashed = {key: event[key] for key in
|
|
781
|
+
('sequence', 'kind', 'payload', 'previousDigest')}
|
|
782
|
+
if event['recordDigest'] != _digest(unhashed):
|
|
783
|
+
raise CustodyJournalError('journal-corrupt')
|
|
784
|
+
previous = event['recordDigest']
|
|
785
|
+
if doc['headDigest'] != previous or raw != _canonical(doc):
|
|
786
|
+
raise CustodyJournalError('journal-corrupt')
|
|
787
|
+
_replay(doc['events'], profile=JOURNAL_PROFILE_02)
|
|
788
|
+
return doc
|