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,1810 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Configured, durable Ed25519 owner approval for G11 host operations.
3
+
4
+ This module verifies a signed, scope-bound decision from an independently
5
+ configured owner authority. It does not create signing keys or authorize
6
+ native effects by itself. The supervisor remains responsible for binding a
7
+ verified approval to its own original native evidence and effect journal.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import fcntl
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import stat
18
+ import threading
19
+ import uuid
20
+ from dataclasses import dataclass
21
+ from functools import wraps
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from ..canonical import canonical_json
26
+ from . import owner_wire as _owner_wire
27
+ from .owner_bootstrap import _CONTEXTS, OwnerAuthorityContext, _require_owner_context
28
+ from .owner_wire import (
29
+ OWNER_PURPOSES,
30
+ OWNER_SCOPES,
31
+ OwnerWireError,
32
+ validate_owner_configuration,
33
+ )
34
+
35
+ OWNER_APPROVAL_PROFILE = 'umf.authenticated-host-owner-approval/0.1'
36
+ OWNER_AUTHORITY_PROFILE = _owner_wire.OWNER_AUTHORITY_PROFILE
37
+ OWNER_LEDGER_PROFILE = 'umf.configured-owner-approval-ledger/0.1'
38
+ OWNER_INTENT_PROFILE = 'umf.pg18.original-store-authority-evidence/0.1'
39
+ _SIGNATURE_DOMAIN = b'umf.host-owner-approval/0.1\x00'
40
+ _SCOPES = OWNER_SCOPES
41
+ _UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
42
+ _HEX = re.compile(r'^[a-f0-9]{64}$')
43
+ _B64URL = re.compile(r'^[A-Za-z0-9_-]+$')
44
+ _NATIVE_NAME = re.compile(r'^[a-z][a-z0-9_]{0,62}$')
45
+ _ROLE_FLAGS = {'canLogin', 'superuser', 'createDatabase', 'createRole',
46
+ 'replication', 'bypassRls', 'inherit'}
47
+ _MAX_INTENT = 65_536
48
+ _MAX_LEDGER = 8 * 1024 * 1024
49
+ _MAX_LEDGER_RECORDS = 4096
50
+ _MAX_REQUESTS = 4096
51
+ _SAFE_INT = 9_007_199_254_740_991
52
+ _REQUEST_KIND = 'umf.owner-approval-request/0.1'
53
+ _VERIFIED_KIND = 'umf.owner-approval-verified/0.1'
54
+ _CAPABILITY_SEAL = object()
55
+ _CONTEXT_SEAL = object()
56
+ _PENDING_EFFECT_SEAL = object()
57
+
58
+
59
+ class OwnerAuthorityError(RuntimeError):
60
+ """Fixed owner-authority refusal without private signed material."""
61
+
62
+ def __init__(self, code: str):
63
+ super().__init__(code)
64
+ self.code = code
65
+
66
+
67
+ def _reject(code: str) -> None:
68
+ raise OwnerAuthorityError(code)
69
+
70
+
71
+ def _closed(value: object, keys: set[str], code: str = 'owner-authority-invalid') -> dict[str, Any]:
72
+ if type(value) is not dict or set(value) != keys or any(type(k) is not str for k in value):
73
+ _reject(code)
74
+ return value
75
+
76
+
77
+ def _text(value: object, maximum: int = 128) -> str:
78
+ if type(value) is not str or not value or '\x00' in value:
79
+ _reject('owner-authority-invalid')
80
+ try:
81
+ encoded = value.encode('utf-8')
82
+ except UnicodeEncodeError:
83
+ _reject('owner-authority-invalid')
84
+ if len(encoded) > maximum:
85
+ _reject('owner-authority-invalid')
86
+ return value
87
+
88
+
89
+ def _uuid(value: object) -> str:
90
+ if type(value) is not str or not _UUID.fullmatch(value):
91
+ _reject('owner-authority-invalid')
92
+ try:
93
+ if str(uuid.UUID(value)) != value:
94
+ _reject('owner-authority-invalid')
95
+ except ValueError:
96
+ _reject('owner-authority-invalid')
97
+ return value
98
+
99
+
100
+ def _digest(value: object) -> str:
101
+ if type(value) is not str or not _HEX.fullmatch(value):
102
+ _reject('owner-authority-invalid')
103
+ return value
104
+
105
+
106
+ def _name(value: object) -> str:
107
+ if type(value) is not str or not _NATIVE_NAME.fullmatch(value):
108
+ _reject('owner-intent-invalid')
109
+ return value
110
+
111
+
112
+ def _uint(value: object, maximum: int) -> int:
113
+ if type(value) is not int or not 0 <= value <= maximum:
114
+ _reject('owner-intent-invalid')
115
+ return value
116
+
117
+
118
+ def _path(value: object) -> str:
119
+ path = _text(value, 4096)
120
+ if not path.startswith('/') or os.path.normpath(path) != path:
121
+ _reject('owner-intent-invalid')
122
+ return path
123
+
124
+
125
+ def _flags(value: object) -> dict[str, Any]:
126
+ flags = _closed(value, _ROLE_FLAGS, 'owner-intent-invalid')
127
+ if any(type(flag) is not bool for flag in flags.values()):
128
+ _reject('owner-intent-invalid')
129
+ return flags
130
+
131
+
132
+ def _principal(value: object, *, operation: str | None = None,
133
+ expected_flags: dict[str, bool] | None = None) -> dict[str, Any]:
134
+ fields = {'name', 'operation', 'flags'} if operation is not None else {'oid', 'name', 'flags'}
135
+ principal = _closed(value, fields, 'owner-intent-invalid')
136
+ _name(principal['name'])
137
+ if operation is not None and principal['operation'] != operation:
138
+ _reject('owner-intent-invalid')
139
+ if operation is None:
140
+ _uint(principal['oid'], 4_294_967_295)
141
+ if principal['oid'] == 0:
142
+ _reject('owner-intent-invalid')
143
+ flags = _flags(principal['flags'])
144
+ if expected_flags is not None and flags != expected_flags:
145
+ _reject('owner-intent-invalid')
146
+ return principal
147
+
148
+
149
+ def _expected_role_flags(role: str) -> dict[str, bool]:
150
+ values = {name: False for name in _ROLE_FLAGS}
151
+ if role == 'maintenance':
152
+ values.update({'canLogin': True, 'superuser': True})
153
+ elif role == 'controller':
154
+ values.update({'superuser': True})
155
+ return values
156
+
157
+
158
+ def _base64url(value: object, size: int) -> bytes:
159
+ if type(value) is not str or not _B64URL.fullmatch(value):
160
+ _reject('owner-authority-invalid')
161
+ try:
162
+ decoded = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
163
+ except (ValueError, TypeError):
164
+ _reject('owner-authority-invalid')
165
+ if len(decoded) != size or base64.urlsafe_b64encode(decoded).decode('ascii').rstrip('=') != value:
166
+ _reject('owner-authority-invalid')
167
+ return decoded
168
+
169
+
170
+ def _base64url_encoded(value: bytes) -> str:
171
+ return base64.urlsafe_b64encode(value).decode('ascii').rstrip('=')
172
+
173
+
174
+ def _plain_json(value: object, *, depth: int = 0, count: list[int] | None = None,
175
+ byte_count: list[int] | None = None,
176
+ byte_limit: int = _MAX_LEDGER) -> object:
177
+ """Copy a strict JSON value and reject subclasses, floats, and cycles."""
178
+ if count is None:
179
+ count = [0]
180
+ if byte_count is None:
181
+ byte_count = [0]
182
+ count[0] += 1
183
+ if count[0] > 100_000 or depth > 48:
184
+ _reject('owner-authority-capacity')
185
+ if value is None or type(value) is bool:
186
+ return value
187
+ if type(value) is int:
188
+ if abs(value) > _SAFE_INT:
189
+ _reject('owner-authority-invalid')
190
+ return value
191
+ if type(value) is str:
192
+ if '\x00' in value:
193
+ _reject('owner-authority-invalid')
194
+ try:
195
+ byte_count[0] += len(value.encode('utf-8'))
196
+ except UnicodeEncodeError:
197
+ _reject('owner-authority-invalid')
198
+ if byte_count[0] > byte_limit:
199
+ _reject('owner-authority-capacity')
200
+ return value
201
+ if type(value) is list:
202
+ if len(value) > 4096:
203
+ _reject('owner-authority-capacity')
204
+ return [_plain_json(item, depth=depth + 1, count=count, byte_count=byte_count,
205
+ byte_limit=byte_limit)
206
+ for item in value]
207
+ if type(value) is dict:
208
+ if len(value) > 128 or any(type(key) is not str or not key.isascii() for key in value):
209
+ _reject('owner-authority-invalid')
210
+ byte_count[0] += sum(len(key) for key in value)
211
+ if byte_count[0] > byte_limit:
212
+ _reject('owner-authority-capacity')
213
+ return {key: _plain_json(item, depth=depth + 1, count=count, byte_count=byte_count,
214
+ byte_limit=byte_limit)
215
+ for key, item in value.items()}
216
+ _reject('owner-authority-invalid')
217
+
218
+
219
+ def _parse_canonical_intent(data: bytes) -> dict[str, Any]:
220
+ if type(data) is not bytes or not 1 <= len(data) <= _MAX_INTENT:
221
+ _reject('owner-intent-capacity')
222
+
223
+ def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
224
+ result: dict[str, Any] = {}
225
+ for key, value in items:
226
+ if key in result:
227
+ _reject('owner-intent-invalid')
228
+ result[key] = value
229
+ return result
230
+
231
+ def bad_constant(_value: str) -> None:
232
+ _reject('owner-intent-invalid')
233
+
234
+ try:
235
+ parsed = json.loads(data.decode('utf-8'), object_pairs_hook=pairs,
236
+ parse_float=lambda _value: _reject('owner-intent-invalid'),
237
+ parse_constant=bad_constant)
238
+ except OwnerAuthorityError:
239
+ raise
240
+ except (UnicodeError, ValueError, RecursionError):
241
+ _reject('owner-intent-invalid')
242
+ copied = _plain_json(parsed)
243
+ if type(copied) is not dict:
244
+ _reject('owner-intent-invalid')
245
+ try:
246
+ encoded = canonical_json(copied).encode('utf-8')
247
+ except (TypeError, ValueError, UnicodeError, RecursionError):
248
+ _reject('owner-intent-invalid')
249
+ if encoded != data:
250
+ _reject('owner-intent-noncanonical')
251
+ return copied
252
+
253
+
254
+ def _decode_canonical_object(data: bytes) -> dict[str, Any]:
255
+ try:
256
+ parsed = json.loads(data.decode('utf-8'), object_pairs_hook=_no_duplicates,
257
+ parse_float=lambda _value: _reject('owner-authority-invalid'),
258
+ parse_constant=lambda _value: _reject('owner-authority-invalid'))
259
+ except OwnerAuthorityError:
260
+ raise
261
+ except (UnicodeError, ValueError, RecursionError):
262
+ _reject('owner-authority-invalid')
263
+ copied = _plain_json(parsed)
264
+ if type(copied) is not dict or _canonical_bytes(copied) != data:
265
+ _reject('owner-authority-invalid')
266
+ return copied
267
+
268
+
269
+ def _validate_native_store_evidence(intent: dict[str, Any], authority_id: str,
270
+ policy_revision: str) -> dict[str, str]:
271
+ expected = {'profile', 'supervisorId', 'custodianId', 'providerId', 'installationId',
272
+ 'ownerAuthorityId', 'ownerPolicyRevision', 'registrationDigest',
273
+ 'targetCustodyDigest', 'authorityPreparationReceiptDigest', 'maintenance',
274
+ 'controller', 'businessOwner', 'requiredMemberships', 'requiredSettings',
275
+ 'nativeAuthorityObservationDigest'}
276
+ _closed(intent, expected, 'owner-intent-invalid')
277
+ if (intent['profile'] != OWNER_INTENT_PROFILE
278
+ or _uuid(intent['ownerAuthorityId']) != authority_id
279
+ or _text(intent['ownerPolicyRevision']) != policy_revision):
280
+ _reject('owner-intent-authority-mismatch')
281
+ supervisor = _uuid(intent['supervisorId'])
282
+ custodian = _uuid(intent['custodianId'])
283
+ provider = _uuid(intent['providerId'])
284
+ installation = _text(intent['installationId'])
285
+ for name in ('registrationDigest', 'targetCustodyDigest',
286
+ 'authorityPreparationReceiptDigest', 'nativeAuthorityObservationDigest'):
287
+ _digest(intent[name])
288
+ principal_fields = {'oid', 'name', 'flags'}
289
+ flag_fields = {'canLogin', 'superuser', 'createDatabase', 'createRole',
290
+ 'replication', 'bypassRls', 'inherit'}
291
+ names: set[str] = set()
292
+ oids: set[int] = set()
293
+ expected_flags = {
294
+ 'maintenance': {'canLogin': True, 'superuser': True, 'createDatabase': False,
295
+ 'createRole': False, 'replication': False, 'bypassRls': False,
296
+ 'inherit': False},
297
+ 'controller': {'canLogin': False, 'superuser': True, 'createDatabase': False,
298
+ 'createRole': False, 'replication': False, 'bypassRls': False,
299
+ 'inherit': False},
300
+ 'businessOwner': {'canLogin': False, 'superuser': False, 'createDatabase': False,
301
+ 'createRole': False, 'replication': False, 'bypassRls': False,
302
+ 'inherit': False},
303
+ }
304
+ for key in ('maintenance', 'controller', 'businessOwner'):
305
+ principal = _closed(intent[key], principal_fields, 'owner-intent-invalid')
306
+ oid = principal['oid']
307
+ if type(oid) is not int or not 1 <= oid <= 4_294_967_295:
308
+ _reject('owner-intent-invalid')
309
+ name = _text(principal['name'])
310
+ flags = _closed(principal['flags'], flag_fields, 'owner-intent-invalid')
311
+ if (any(type(flag) is not bool for flag in flags.values())
312
+ or flags != expected_flags[key] or oid in oids or name in names):
313
+ _reject('owner-intent-invalid')
314
+ oids.add(oid)
315
+ names.add(name)
316
+ memberships = intent['requiredMemberships']
317
+ if type(memberships) is not list or len(memberships) > 32:
318
+ _reject('owner-intent-invalid')
319
+ seen_memberships: set[tuple[int, int]] = set()
320
+ for membership in memberships:
321
+ row = _closed(membership, {'memberOid', 'roleOid', 'inherit', 'set', 'admin'},
322
+ 'owner-intent-invalid')
323
+ member, role = row['memberOid'], row['roleOid']
324
+ if (type(member) is not int or type(role) is not int or member <= 0 or role <= 0
325
+ or member > 4_294_967_295 or role > 4_294_967_295
326
+ or any(type(row[k]) is not bool for k in ('inherit', 'set', 'admin'))
327
+ or member not in oids or role not in oids
328
+ or (member, role) in seen_memberships):
329
+ _reject('owner-intent-invalid')
330
+ seen_memberships.add((member, role))
331
+ maintenance_oid = intent['maintenance']['oid']
332
+ controller_oid = intent['controller']['oid']
333
+ owner_oid = intent['businessOwner']['oid']
334
+ if memberships != [
335
+ {'memberOid': maintenance_oid, 'roleOid': controller_oid,
336
+ 'inherit': False, 'set': True, 'admin': False},
337
+ {'memberOid': maintenance_oid, 'roleOid': owner_oid,
338
+ 'inherit': False, 'set': True, 'admin': False}]:
339
+ _reject('owner-intent-invalid')
340
+ settings = _closed(intent['requiredSettings'],
341
+ {'searchPath', 'timeZone', 'rowSecurity', 'sessionReplicationRole',
342
+ 'transactionReadOnly', 'transactionIsolation'}, 'owner-intent-invalid')
343
+ expected_settings = {'searchPath': 'pg_catalog', 'timeZone': 'UTC', 'rowSecurity': 'on',
344
+ 'sessionReplicationRole': 'origin', 'transactionReadOnly': 'off',
345
+ 'transactionIsolation': 'read committed'}
346
+ if settings != expected_settings:
347
+ _reject('owner-intent-invalid')
348
+ return {'supervisorId': supervisor, 'custodianId': custodian,
349
+ 'providerId': provider, 'installationId': installation}
350
+
351
+
352
+ def _target_custody(value: object) -> dict[str, Any]:
353
+ custody = _closed(value, {'profile', 'custodianId', 'registrationId', 'resourceId',
354
+ 'incarnation', 'registrationDigest'}, 'owner-intent-invalid')
355
+ if custody['profile'] != 'umf.native-target-custody/0.1':
356
+ _reject('owner-intent-invalid')
357
+ for name in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
358
+ _uuid(custody[name])
359
+ _digest(custody['registrationDigest'])
360
+ return custody
361
+
362
+
363
+ def _validate_registration_without_approval(registration: object) -> dict[str, str]:
364
+ registration = _closed(registration, {'profile', 'registrationId', 'custodianId',
365
+ 'providerId', 'installationId', 'origin',
366
+ 'endpointControl'}, 'owner-intent-invalid')
367
+ # Reuse the adopted custody shape checker with a local, never-exported marker.
368
+ # This marker is not part of the intent and is not signed or persisted.
369
+ marker = {'authorityId': '00000000-0000-4000-8000-000000000000',
370
+ 'approvalId': '00000000-0000-4000-8000-000000000000',
371
+ 'approvalDigest': '0' * 64,
372
+ 'scope': 'enroll-owned-local-postgresql-target'}
373
+ try:
374
+ from .ingress_custody import CustodyJournalError, _validate_owner_payload
375
+ except ImportError:
376
+ _reject('owner-intent-invalid')
377
+ try:
378
+ _validate_owner_payload({**registration, 'ownerApproval': marker})
379
+ except CustodyJournalError:
380
+ _reject('owner-intent-invalid')
381
+ return {'custodianId': registration['custodianId'],
382
+ 'providerId': registration['providerId'],
383
+ 'installationId': registration['installationId'],
384
+ 'supervisorId': registration['origin']['supervisorId']}
385
+
386
+
387
+ def _validate_scope_intent(scope: str, intent: dict[str, Any], *, authority_id: str,
388
+ policy_revision: str,
389
+ context: OwnerAuthorityContext,
390
+ journal_metadata: dict[str, Any]) -> tuple[dict[str, str], tuple[object, ...]]:
391
+ """Validate one frozen owner intent and derive its stable idempotency key."""
392
+ if scope == 'local-target-creation':
393
+ journal = journal_metadata['supervisorJournal']
394
+ legacy = journal is None
395
+ keys = {'profile', 'supervisorId', 'clusterId', 'incarnationId',
396
+ 'installationId', 'ownerUid', 'databaseName', 'businessOwner',
397
+ 'maintenanceName', 'controllerName', 'controlDirectory',
398
+ 'dataDirectory', 'postgresPath', 'postgresSha256', 'initdbPath',
399
+ 'initdbSha256', 'port', 'configDigest', 'hbaDigest'}
400
+ if not legacy:
401
+ keys |= {'supervisorJournalBirthDigest', 'ownerBootstrapContextDigest'}
402
+ _closed(intent, keys, 'owner-intent-invalid')
403
+ expected_profile = ('umf.local-postgresql-create-request/0.1' if legacy
404
+ else 'umf.local-postgresql-create-request/0.2')
405
+ if intent['profile'] != expected_profile:
406
+ _reject('owner-intent-invalid')
407
+ if (not legacy and (
408
+ intent['supervisorJournalBirthDigest'] != journal['birthDigest']
409
+ or intent['ownerBootstrapContextDigest']
410
+ != journal_metadata['ownerBootstrapContextDigest'])):
411
+ _reject('owner-intent-context-mismatch')
412
+ supervisor = _uuid(intent['supervisorId'])
413
+ cluster = _uuid(intent['clusterId'])
414
+ _uuid(intent['incarnationId'])
415
+ _uint(intent['ownerUid'], 4_294_967_295)
416
+ database = _name(intent['databaseName'])
417
+ business_owner = _name(intent['businessOwner'])
418
+ maintenance = _name(intent['maintenanceName'])
419
+ controller = _name(intent['controllerName'])
420
+ if len({business_owner, maintenance, controller}) != 3:
421
+ _reject('owner-intent-invalid')
422
+ control = _path(intent['controlDirectory'])
423
+ data = _path(intent['dataDirectory'])
424
+ if (control == data or data.startswith(control.rstrip('/') + '/')
425
+ or control.startswith(data.rstrip('/') + '/')):
426
+ _reject('owner-intent-invalid')
427
+ _path(intent['postgresPath']); _path(intent['initdbPath'])
428
+ for name in ('postgresSha256', 'initdbSha256', 'configDigest', 'hbaDigest'):
429
+ _digest(intent[name])
430
+ port = _uint(intent['port'], 65535)
431
+ if port == 0 or supervisor != context._supervisor_id:
432
+ _reject('owner-intent-context-mismatch')
433
+ if _text(intent['installationId']) != context._installation_id:
434
+ _reject('owner-intent-context-mismatch')
435
+ return _context_target(context), (scope, supervisor, cluster)
436
+
437
+ if scope == 'native-principal-preparation':
438
+ _closed(intent, {'profile', 'preparationId', 'supervisorId', 'custodianId',
439
+ 'providerId', 'installationId', 'creationRequestDigest',
440
+ 'creationApprovalDigest', 'bootstrapOriginDigest',
441
+ 'bootstrapDatabase', 'maintenanceBefore', 'maintenanceAfter',
442
+ 'controller', 'businessOwner', 'applicationDatabase',
443
+ 'memberships', 'maximumRoles'}, 'owner-intent-invalid')
444
+ if intent['profile'] != 'umf.local-postgresql-principal-preparation/0.1':
445
+ _reject('owner-intent-invalid')
446
+ preparation = _uuid(intent['preparationId'])
447
+ target = _validate_context_fields(intent, context,
448
+ ('supervisorId', 'custodianId', 'providerId',
449
+ 'installationId'))
450
+ for field in ('creationRequestDigest', 'creationApprovalDigest', 'bootstrapOriginDigest'):
451
+ _digest(intent[field])
452
+ database = _closed(intent['bootstrapDatabase'], {'oid', 'name', 'systemIdentifier'},
453
+ 'owner-intent-invalid')
454
+ if database['name'] != 'postgres' or _uint(database['oid'], 4_294_967_295) == 0:
455
+ _reject('owner-intent-invalid')
456
+ _decimal_text(database['systemIdentifier'])
457
+ maintenance_before = _principal(intent['maintenanceBefore'])
458
+ maintenance_after = _principal(
459
+ intent['maintenanceAfter'], operation='alter-bootstrap',
460
+ expected_flags=_expected_role_flags('maintenance'))
461
+ controller = _principal(intent['controller'], operation='create-absent',
462
+ expected_flags=_expected_role_flags('controller'))
463
+ owner = _principal(intent['businessOwner'], operation='create-absent',
464
+ expected_flags=_expected_role_flags('businessOwner'))
465
+ if (maintenance_after['name'] != maintenance_before['name']
466
+ or len({maintenance_before['name'], controller['name'], owner['name']}) != 3):
467
+ _reject('owner-intent-invalid')
468
+ appdb = _closed(intent['applicationDatabase'],
469
+ {'name', 'ownerName', 'encoding', 'locale', 'operation'},
470
+ 'owner-intent-invalid')
471
+ if (appdb['name'] == 'postgres' or _name(appdb['name']) != appdb['name']
472
+ or appdb['ownerName'] != owner['name'] or appdb['encoding'] != 'UTF8'
473
+ or appdb['locale'] != 'C' or appdb['operation'] != 'create-absent'):
474
+ _reject('owner-intent-invalid')
475
+ memberships = intent['memberships']
476
+ expected_memberships = [
477
+ {'memberName': intent['maintenanceBefore']['name'],
478
+ 'roleName': controller['name'], 'inherit': False, 'set': True, 'admin': False},
479
+ {'memberName': intent['maintenanceBefore']['name'],
480
+ 'roleName': owner['name'], 'inherit': False, 'set': True, 'admin': False},
481
+ ]
482
+ if (type(memberships) is not list or len(memberships) != 2
483
+ or any(type(row) is not dict for row in memberships)
484
+ or any(set(row) != {'memberName', 'roleName', 'inherit', 'set', 'admin'}
485
+ for row in memberships)
486
+ or any(type(row[key]) is not bool for row in memberships
487
+ for key in ('inherit', 'set', 'admin'))
488
+ or memberships != expected_memberships
489
+ or type(intent['maximumRoles']) is not int or intent['maximumRoles'] != 3):
490
+ _reject('owner-intent-invalid')
491
+ return target, (scope, target['supervisorId'], preparation)
492
+
493
+ if scope == 'local-target-registration':
494
+ _closed(intent, {'profile', 'registration'}, 'owner-intent-invalid')
495
+ if intent['profile'] != 'umf.owner-target-registration-intent/0.1':
496
+ _reject('owner-intent-invalid')
497
+ target = _validate_registration_without_approval(intent['registration'])
498
+ _validate_context_fields(target, context,
499
+ ('supervisorId', 'custodianId', 'providerId', 'installationId'))
500
+ return _context_target(context), (scope, target['custodianId'],
501
+ intent['registration']['registrationId'])
502
+
503
+ if scope == 'native-store-creation':
504
+ _closed(intent, {'profile', 'store', 'evidence'}, 'owner-intent-invalid')
505
+ if intent['profile'] != 'umf.owner-store-create-intent/0.1':
506
+ _reject('owner-intent-invalid')
507
+ evidence_target = _validate_native_store_evidence(
508
+ intent['evidence'], authority_id, policy_revision)
509
+ _validate_context_fields(evidence_target, context,
510
+ ('supervisorId', 'custodianId', 'providerId', 'installationId'))
511
+ store = _closed(intent['store'], {'profile', 'storeId', 'schemaName'},
512
+ 'owner-intent-invalid')
513
+ store_profiles = {
514
+ 'umf.pg-generation-ingress-store/0.1': 'umf_ingress_',
515
+ 'umf.native-row-originals-store/0.1': 'umf_originals_',
516
+ }
517
+ prefix = store_profiles.get(store['profile'])
518
+ store_id = _uuid(store['storeId'])
519
+ if (prefix is None or store_id != evidence_target['providerId']
520
+ or store['schemaName'] != prefix + store_id.replace('-', '')):
521
+ _reject('owner-intent-invalid')
522
+ return _context_target(context), (scope, evidence_target['providerId'],
523
+ store['profile'], store_id)
524
+
525
+ if scope == 'disabled-epoch-provision':
526
+ _closed(intent, {'profile', 'request'}, 'owner-intent-invalid')
527
+ if intent['profile'] != 'umf.owner-epoch-provision-intent/0.1':
528
+ _reject('owner-intent-invalid')
529
+ request = _closed(intent['request'], {'profile', 'providerId', 'enrollmentId',
530
+ 'installationId', 'targetCustody', 'planDigest', 'fileDigest',
531
+ 'expectedHead', 'previousSourceDigest', 'nextSourceDigest',
532
+ 'nextBundleDigest', 'newEpoch', 'issuerProfile', 'principals',
533
+ 'maximumRoles'}, 'owner-intent-invalid')
534
+ if request['profile'] != 'umf.ingress-epoch-provision/0.1':
535
+ _reject('owner-intent-invalid')
536
+ custody = _target_custody(request['targetCustody'])
537
+ target = {'supervisorId': context._supervisor_id,
538
+ 'custodianId': custody['custodianId'],
539
+ 'providerId': _uuid(request['providerId']),
540
+ 'installationId': _text(request['installationId'])}
541
+ _validate_context_fields(target, context,
542
+ ('supervisorId', 'custodianId', 'providerId', 'installationId'))
543
+ for field in ('planDigest', 'fileDigest', 'previousSourceDigest',
544
+ 'nextSourceDigest', 'nextBundleDigest'):
545
+ _digest(request[field])
546
+ if request['expectedHead'] is None:
547
+ _reject('owner-intent-invalid')
548
+ _digest(request['expectedHead'])
549
+ _uuid(request['enrollmentId']); epoch = _uuid(request['newEpoch'])
550
+ _text(request['issuerProfile'], 256)
551
+ principals = request['principals']
552
+ maximum = request['maximumRoles']
553
+ if (type(principals) is not list or not 1 <= len(principals) <= 256
554
+ or type(maximum) is not int or maximum != len(principals)):
555
+ _reject('owner-intent-invalid')
556
+ logins: set[str] = set()
557
+ for principal in principals:
558
+ principal = _closed(principal, {'loginName', 'subject', 'audience'},
559
+ 'owner-intent-invalid')
560
+ login = _name(principal['loginName'])
561
+ subject = _closed(principal['subject'], {'oid', 'name'}, 'owner-intent-invalid')
562
+ if (login in logins or _uint(subject['oid'], 4_294_967_295) == 0
563
+ or _name(subject['name']) != subject['name']
564
+ or principal['audience'] not in ('person', 'batch')):
565
+ _reject('owner-intent-invalid')
566
+ logins.add(login)
567
+ return _context_target(context), (scope, target['providerId'], epoch)
568
+
569
+ if scope == 'generation-ingress-transition':
570
+ _closed(intent, {'profile', 'request'}, 'owner-intent-invalid')
571
+ if intent['profile'] != 'umf.owner-ingress-transition-intent/0.1':
572
+ _reject('owner-intent-invalid')
573
+ request = _closed(intent['request'], {'profile', 'providerId', 'enrollmentId',
574
+ 'installationId', 'targetIdentityDigest', 'planDigest', 'fileDigest',
575
+ 'expectedHead', 'previousSourceDigest', 'nextSourceDigest',
576
+ 'previousBundleDigest', 'nextBundleDigest', 'oldEpoch', 'newEpoch',
577
+ 'oldPrincipalsDigest', 'newPrincipalsDigest', 'approvalDigest',
578
+ 'targetCustody', 'executionPolicyDigest'}, 'owner-intent-invalid')
579
+ if request['profile'] != 'umf.table-generation-ingress/0.1':
580
+ _reject('owner-intent-invalid')
581
+ custody = _target_custody(request['targetCustody'])
582
+ target = {'supervisorId': context._supervisor_id,
583
+ 'custodianId': custody['custodianId'],
584
+ 'providerId': _uuid(request['providerId']),
585
+ 'installationId': _text(request['installationId'])}
586
+ _validate_context_fields(target, context,
587
+ ('supervisorId', 'custodianId', 'providerId', 'installationId'))
588
+ for field in ('targetIdentityDigest', 'planDigest', 'fileDigest', 'expectedHead',
589
+ 'previousSourceDigest', 'nextSourceDigest', 'previousBundleDigest',
590
+ 'nextBundleDigest', 'oldPrincipalsDigest', 'newPrincipalsDigest',
591
+ 'approvalDigest', 'executionPolicyDigest'):
592
+ _digest(request[field])
593
+ _uuid(request['enrollmentId'])
594
+ old_epoch, new_epoch = _uuid(request['oldEpoch']), _uuid(request['newEpoch'])
595
+ if old_epoch == new_epoch:
596
+ _reject('owner-intent-invalid')
597
+ return _context_target(context), (scope, target['providerId'], new_epoch)
598
+
599
+ _reject('owner-approval-scope-invalid')
600
+
601
+
602
+ def _decimal_text(value: object) -> str:
603
+ if (type(value) is not str or not value.isascii() or not value.isdigit()
604
+ or len(value) > 20 or (len(value) > 1 and value.startswith('0'))
605
+ or not 1 <= int(value) <= 18_446_744_073_709_551_615):
606
+ _reject('owner-intent-invalid')
607
+ return value
608
+
609
+
610
+ def _context_target(context: OwnerAuthorityContext) -> dict[str, str]:
611
+ return {'supervisorId': context._supervisor_id,
612
+ 'custodianId': context._custodian_id,
613
+ 'providerId': context._provider_id,
614
+ 'installationId': context._installation_id}
615
+
616
+
617
+ def _validate_context_fields(target: dict[str, str], context: OwnerAuthorityContext,
618
+ fields: tuple[str, ...]) -> dict[str, str]:
619
+ expected = _context_target(context)
620
+ for field in fields:
621
+ if target.get(field) != expected[field]:
622
+ _reject('owner-intent-context-mismatch')
623
+ return expected
624
+
625
+
626
+ def _validate_config(value: object) -> tuple[dict[str, Any], tuple[dict[str, Any], ...]]:
627
+ try:
628
+ return validate_owner_configuration(value)
629
+ except OwnerWireError as error:
630
+ _reject(error.code)
631
+
632
+
633
+ def _canonical_bytes(value: object) -> bytes:
634
+ try:
635
+ return canonical_json(value).encode('utf-8')
636
+ except (TypeError, ValueError, UnicodeError, RecursionError):
637
+ _reject('owner-authority-invalid')
638
+
639
+
640
+ def _digest_bytes(value: bytes) -> str:
641
+ return hashlib.sha256(value).hexdigest()
642
+
643
+
644
+ def _ledger_intent_bytes(value: object) -> bytes:
645
+ if type(value) is not str or not _B64URL.fullmatch(value):
646
+ _reject('owner-approval-ledger-corrupt')
647
+ try:
648
+ decoded = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
649
+ except (ValueError, TypeError):
650
+ _reject('owner-approval-ledger-corrupt')
651
+ if (not 1 <= len(decoded) <= _MAX_INTENT
652
+ or base64.urlsafe_b64encode(decoded).decode('ascii').rstrip('=') != value):
653
+ _reject('owner-approval-ledger-corrupt')
654
+ return decoded
655
+
656
+
657
+ def _ledger_parse(data: bytes, journal_metadata: dict[str, Any]) -> list[dict[str, Any]]:
658
+ if len(data) > _MAX_LEDGER or (data and not data.endswith(b'\n')):
659
+ _reject('owner-approval-ledger-corrupt')
660
+ if not data:
661
+ return []
662
+ lines = data.splitlines()
663
+ if len(lines) > _MAX_LEDGER_RECORDS * 4 + 1:
664
+ _reject('owner-approval-ledger-capacity')
665
+ records: list[dict[str, Any]] = []
666
+ previous = '0' * 64
667
+ for index, line in enumerate(lines, start=1):
668
+ try:
669
+ record = json.loads(line.decode('utf-8'), object_pairs_hook=_no_duplicates,
670
+ parse_constant=lambda _v: _reject('owner-approval-ledger-corrupt'))
671
+ except OwnerAuthorityError:
672
+ raise
673
+ except (UnicodeError, ValueError, RecursionError):
674
+ _reject('owner-approval-ledger-corrupt')
675
+ if type(record) is not dict or _canonical_bytes(record) != line:
676
+ _reject('owner-approval-ledger-corrupt')
677
+ if index == 1:
678
+ if (set(record) != {'profile', 'authorityId', 'configurationDigest', 'digest'}
679
+ or record['profile'] != OWNER_LEDGER_PROFILE):
680
+ _reject('owner-approval-ledger-corrupt')
681
+ body = {key: record[key] for key in ('profile', 'authorityId', 'configurationDigest')}
682
+ if record['digest'] != _digest_bytes(_canonical_bytes(body)):
683
+ _reject('owner-approval-ledger-corrupt')
684
+ else:
685
+ if set(record) != {'sequence', 'previousDigest', 'kind', 'payload', 'digest'}:
686
+ _reject('owner-approval-ledger-corrupt')
687
+ body = {key: record[key] for key in ('sequence', 'previousDigest', 'kind', 'payload')}
688
+ if (record['sequence'] != index - 1 or record['previousDigest'] != previous
689
+ or type(record['kind']) is not str
690
+ or type(record['payload']) is not dict
691
+ or record['digest'] != _digest_bytes(_canonical_bytes(body))):
692
+ _reject('owner-approval-ledger-corrupt')
693
+ previous = record['digest']
694
+ records.append(record)
695
+ _validate_ledger_events(records, journal_metadata)
696
+ return records
697
+
698
+
699
+ def _validate_ledger_events(records: list[dict[str, Any]],
700
+ journal_metadata: dict[str, Any]) -> None:
701
+ requests: dict[str, dict[str, Any]] = {}
702
+ approvals: dict[str, dict[str, Any]] = {}
703
+ dispatched: set[str] = set()
704
+ outcomes: dict[str, dict[str, Any]] = {}
705
+ effect_keys: dict[tuple[str, str], str] = {}
706
+ authority_id = records[0]['authorityId']
707
+ configuration_digest = records[0]['configurationDigest']
708
+ for record in records[1:]:
709
+ kind = record['kind']
710
+ payload = record['payload']
711
+ if kind == 'request-prepared':
712
+ if set(payload) != {'approvalId', 'scope', 'purpose', 'intentDigest', 'payloadDigest',
713
+ 'contextDigest', 'effectKey', 'stableKey', 'target', 'intent', 'signedPayload',
714
+ 'intentBytes'}:
715
+ _reject('owner-approval-ledger-corrupt')
716
+ approval_id = payload['approvalId']
717
+ signed = payload['signedPayload']
718
+ if (type(approval_id) is not str or approval_id in requests
719
+ or type(payload['scope']) is not str or payload['scope'] not in _SCOPES
720
+ or payload['purpose'] not in OWNER_PURPOSES
721
+ or type(payload['contextDigest']) is not str
722
+ or not _HEX.fullmatch(payload['contextDigest'])
723
+ or type(payload['effectKey']) is not list
724
+ or not payload['effectKey']
725
+ or type(payload['stableKey']) is not list
726
+ or not payload['stableKey']
727
+ or type(payload['intentDigest']) is not str
728
+ or not _HEX.fullmatch(payload['intentDigest'])
729
+ or type(payload['payloadDigest']) is not str
730
+ or not _HEX.fullmatch(payload['payloadDigest'])
731
+ or type(signed) is not dict
732
+ or set(signed) != {'profile', 'authorityId', 'policyRevision', 'keyId',
733
+ 'principalId', 'approvalId', 'purpose', 'scope', 'custodianId',
734
+ 'supervisorId', 'providerId', 'installationId',
735
+ 'intentDigest'}
736
+ or signed.get('profile') != OWNER_APPROVAL_PROFILE
737
+ or signed.get('authorityId') != authority_id
738
+ or signed.get('approvalId') != approval_id
739
+ or signed.get('purpose') != payload['purpose']
740
+ or signed.get('scope') != payload['scope']
741
+ or signed.get('intentDigest') != payload['intentDigest']
742
+ or payload['payloadDigest'] != _digest_bytes(_canonical_bytes(signed))):
743
+ _reject('owner-approval-ledger-corrupt')
744
+ try:
745
+ _uuid(approval_id)
746
+ intent_bytes = _ledger_intent_bytes(payload['intentBytes'])
747
+ intent = _parse_canonical_intent(intent_bytes)
748
+ except (OwnerAuthorityError, TypeError):
749
+ _reject('owner-approval-ledger-corrupt')
750
+ if (type(payload['target']) is not dict
751
+ or set(payload['target']) != {'supervisorId', 'custodianId', 'providerId',
752
+ 'installationId'}
753
+ or type(payload['intent']) is not dict or intent != payload['intent']
754
+ or _digest_bytes(intent_bytes) != payload['intentDigest']
755
+ or any(signed.get(key) != value for key, value in payload['target'].items())):
756
+ _reject('owner-approval-ledger-corrupt')
757
+ stable = payload['stableKey']
758
+ target = payload['target']
759
+ if (payload['contextDigest'] != configuration_digest
760
+ or len(stable) < 6
761
+ or stable[:5] != [payload['purpose'], target['custodianId'],
762
+ target['supervisorId'], target['providerId'],
763
+ target['installationId']]):
764
+ _reject('owner-approval-ledger-corrupt')
765
+ replay_context = _LedgerReplayContext(
766
+ _purpose=payload['purpose'], _custodian_id=target['custodianId'],
767
+ _supervisor_id=target['supervisorId'], _provider_id=target['providerId'],
768
+ _installation_id=target['installationId'],
769
+ _journal_metadata=journal_metadata)
770
+ try:
771
+ derived_target, derived_effect_key = _validate_scope_intent(
772
+ payload['scope'], intent, authority_id=authority_id,
773
+ policy_revision=signed['policyRevision'], context=replay_context,
774
+ journal_metadata=journal_metadata)
775
+ except (OwnerAuthorityError, KeyError, TypeError):
776
+ _reject('owner-approval-ledger-corrupt')
777
+ expected_stable = [payload['purpose'], target['custodianId'],
778
+ target['supervisorId'], target['providerId'],
779
+ target['installationId'], *derived_effect_key]
780
+ if (derived_target != target or payload['effectKey'] != list(derived_effect_key)
781
+ or stable != expected_stable):
782
+ _reject('owner-approval-ledger-corrupt')
783
+ key = (_canonical_bytes(payload['stableKey']).decode('utf-8'), payload['purpose'])
784
+ previous_request = effect_keys.get(key)
785
+ if previous_request is not None:
786
+ _reject('owner-approval-ledger-corrupt')
787
+ effect_keys[key] = approval_id
788
+ requests[approval_id] = payload
789
+ elif kind == 'approval-reserved':
790
+ if set(payload) != {'approvalId', 'intentDigest', 'envelopeDigest', 'envelope'}:
791
+ _reject('owner-approval-ledger-corrupt')
792
+ approval_id = payload['approvalId']
793
+ request = requests.get(approval_id)
794
+ envelope = payload['envelope']
795
+ if (request is None or approval_id in approvals
796
+ or payload['intentDigest'] != request['intentDigest']
797
+ or type(payload['envelopeDigest']) is not str
798
+ or not _HEX.fullmatch(payload['envelopeDigest'])
799
+ or type(envelope) is not dict or set(envelope) != {'payload', 'signature'}
800
+ or type(envelope['payload']) is not dict
801
+ or envelope['payload'] != request['signedPayload']
802
+ or payload['envelopeDigest'] != _digest_bytes(_canonical_bytes(envelope))):
803
+ _reject('owner-approval-ledger-corrupt')
804
+ try:
805
+ _base64url(envelope['signature'], 64)
806
+ except OwnerAuthorityError:
807
+ _reject('owner-approval-ledger-corrupt')
808
+ approvals[approval_id] = payload
809
+ elif kind == 'effect-dispatch-reserved':
810
+ if set(payload) != {'approvalId', 'envelopeDigest'}:
811
+ _reject('owner-approval-ledger-corrupt')
812
+ approval_id = payload['approvalId']
813
+ approval = approvals.get(approval_id)
814
+ if (approval is None or approval_id in dispatched
815
+ or payload['envelopeDigest'] != approval['envelopeDigest']):
816
+ _reject('owner-approval-ledger-corrupt')
817
+ dispatched.add(approval_id)
818
+ elif kind == 'effect-pending':
819
+ if set(payload) != {'approvalId', 'reservationDigest'}:
820
+ _reject('owner-approval-ledger-corrupt')
821
+ approval_id = payload['approvalId']
822
+ approval = approvals.get(approval_id)
823
+ if (approval is None or approval_id in dispatched
824
+ or type(payload['reservationDigest']) is not str
825
+ or not _HEX.fullmatch(payload['reservationDigest'])):
826
+ _reject('owner-approval-ledger-corrupt')
827
+ dispatched.add(approval_id)
828
+ outcomes[approval_id] = {'reservationDigest': payload['reservationDigest']}
829
+ elif kind == 'effect-outcome':
830
+ if set(payload) != {'approvalId', 'reservationDigest', 'status', 'receiptDigest'}:
831
+ _reject('owner-approval-ledger-corrupt')
832
+ approval_id = payload['approvalId']
833
+ pending = outcomes.get(approval_id)
834
+ if (approval_id not in dispatched or pending is None or 'status' in pending
835
+ or type(payload['reservationDigest']) is not str
836
+ or not _HEX.fullmatch(payload['reservationDigest'])
837
+ or payload['reservationDigest'] != pending['reservationDigest']
838
+ or payload['status'] not in ('confirmed', 'aborted')
839
+ or type(payload['receiptDigest']) is not str
840
+ or not _HEX.fullmatch(payload['receiptDigest'])):
841
+ _reject('owner-approval-ledger-corrupt')
842
+ outcomes[approval_id] = payload
843
+ else:
844
+ _reject('owner-approval-ledger-corrupt')
845
+
846
+
847
+ @dataclass(frozen=True)
848
+ class _LedgerReplayContext:
849
+ """Bound context reconstructed only to validate signed ledger semantics."""
850
+
851
+ _purpose: str
852
+ _custodian_id: str
853
+ _supervisor_id: str
854
+ _provider_id: str
855
+ _installation_id: str
856
+ _journal_metadata: dict[str, Any]
857
+
858
+
859
+ def _no_duplicates(items: list[tuple[str, Any]]) -> dict[str, Any]:
860
+ result: dict[str, Any] = {}
861
+ for key, value in items:
862
+ if key in result:
863
+ _reject('owner-approval-ledger-corrupt')
864
+ result[key] = value
865
+ return result
866
+
867
+
868
+ class _ApprovalLedger:
869
+ """Small append-only fsynced ledger, separate from the PostgreSQL data dir."""
870
+
871
+ __slots__ = ('authority_id', 'configuration_digest', 'journal_metadata',
872
+ 'lock_path', 'path')
873
+
874
+ def __init__(self, path: str | os.PathLike[str], authority_id: str,
875
+ configuration_digest: str, journal_metadata: dict[str, Any]):
876
+ if type(path) is not str and not isinstance(path, Path):
877
+ _reject('owner-approval-ledger-path-invalid')
878
+ target = Path(path)
879
+ if not target.is_absolute() or target.name in ('', '.', '..'):
880
+ _reject('owner-approval-ledger-path-invalid')
881
+ parent = target.parent
882
+ try:
883
+ parent_stat = parent.stat(follow_symlinks=False)
884
+ except OSError:
885
+ _reject('owner-approval-ledger-path-invalid')
886
+ if (not stat.S_ISDIR(parent_stat.st_mode) or parent.is_symlink()
887
+ or parent.resolve(strict=True) != parent
888
+ or parent_stat.st_uid != os.geteuid() or parent_stat.st_mode & 0o077):
889
+ _reject('owner-approval-ledger-path-invalid')
890
+ self.path = target
891
+ self.lock_path = target.with_name(target.name + '.lock')
892
+ self.authority_id = authority_id
893
+ self.configuration_digest = configuration_digest
894
+ self.journal_metadata = journal_metadata
895
+
896
+ def _open_locked(self) -> tuple[int, int, bool]:
897
+ lock_fd = -1
898
+ fd = -1
899
+ flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
900
+ try:
901
+ try:
902
+ lock_fd = os.open(self.lock_path, flags | os.O_CREAT | os.O_EXCL, 0o600)
903
+ new_lock = True
904
+ except FileExistsError:
905
+ lock_fd = os.open(self.lock_path, flags)
906
+ new_lock = False
907
+ lock_stat = os.fstat(lock_fd)
908
+ if (not stat.S_ISREG(lock_stat.st_mode) or lock_stat.st_uid != os.geteuid()
909
+ or lock_stat.st_mode & 0o077 or lock_stat.st_nlink != 1):
910
+ raise OSError('unsafe existing lock')
911
+ if new_lock:
912
+ os.fchmod(lock_fd, 0o600)
913
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
914
+ try:
915
+ fd = os.open(self.path, flags | os.O_CREAT | os.O_EXCL, 0o600)
916
+ is_new = True
917
+ except FileExistsError:
918
+ fd = os.open(self.path, flags)
919
+ is_new = False
920
+ file_stat = os.fstat(fd)
921
+ if (not stat.S_ISREG(file_stat.st_mode) or file_stat.st_uid != os.geteuid()
922
+ or file_stat.st_mode & 0o077 or file_stat.st_nlink != 1):
923
+ raise OSError('unsafe existing ledger')
924
+ if is_new:
925
+ os.fchmod(fd, 0o600)
926
+ return lock_fd, fd, is_new
927
+ except (OSError, ValueError):
928
+ try:
929
+ if fd >= 0:
930
+ os.close(fd)
931
+ if lock_fd >= 0:
932
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
933
+ os.close(lock_fd)
934
+ except OSError:
935
+ pass
936
+ _reject('owner-approval-ledger-unavailable')
937
+
938
+ def _records(self, fd: int, is_new: bool) -> list[dict[str, Any]]:
939
+ os.lseek(fd, 0, os.SEEK_SET)
940
+ chunks: list[bytes] = []
941
+ total = 0
942
+ while True:
943
+ chunk = os.read(fd, 65536)
944
+ if not chunk:
945
+ break
946
+ total += len(chunk)
947
+ if total > _MAX_LEDGER:
948
+ _reject('owner-approval-ledger-capacity')
949
+ chunks.append(chunk)
950
+ records = _ledger_parse(b''.join(chunks), self.journal_metadata)
951
+ if not records and is_new:
952
+ body = {'profile': OWNER_LEDGER_PROFILE, 'authorityId': self.authority_id,
953
+ 'configurationDigest': self.configuration_digest}
954
+ record = {**body, 'digest': _digest_bytes(_canonical_bytes(body))}
955
+ data = _canonical_bytes(record) + b'\n'
956
+ written = 0
957
+ while written < len(data):
958
+ count = os.write(fd, data[written:])
959
+ if count <= 0:
960
+ _reject('owner-approval-ledger-write-failed')
961
+ written += count
962
+ os.fsync(fd)
963
+ os.fchmod(fd, 0o600)
964
+ records = [record]
965
+ _fsync_parent(self.path.parent)
966
+ if (not records or records[0].get('authorityId') != self.authority_id
967
+ or records[0].get('configurationDigest') != self.configuration_digest):
968
+ _reject('owner-approval-ledger-binding-mismatch')
969
+ return records
970
+
971
+ def _append(self, fd: int, record: dict[str, Any]) -> None:
972
+ data = _canonical_bytes(record) + b'\n'
973
+ initial_stat = os.fstat(fd)
974
+ os.lseek(fd, 0, os.SEEK_SET)
975
+ chunks: list[bytes] = []
976
+ total = 0
977
+ while True:
978
+ chunk = os.read(fd, 65536)
979
+ if not chunk:
980
+ break
981
+ total += len(chunk)
982
+ if total + len(data) > _MAX_LEDGER:
983
+ _reject('owner-approval-ledger-capacity')
984
+ chunks.append(chunk)
985
+ original = b''.join(chunks)
986
+ if len(original.splitlines()) + 1 > _MAX_LEDGER_RECORDS * 4 + 1:
987
+ _reject('owner-approval-ledger-capacity')
988
+ complete = original + data
989
+ temporary = self.path.with_name(f'.{self.path.name}.{uuid.uuid4().hex}.tmp')
990
+ temp_fd = -1
991
+ try:
992
+ temp_fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL
993
+ | getattr(os, 'O_NOFOLLOW', 0), 0o600)
994
+ offset = 0
995
+ while offset < len(complete):
996
+ count = os.write(temp_fd, complete[offset:])
997
+ if count <= 0:
998
+ raise OSError('short write')
999
+ offset += count
1000
+ os.fchmod(temp_fd, 0o600)
1001
+ os.fsync(temp_fd)
1002
+ os.close(temp_fd)
1003
+ temp_fd = -1
1004
+ current_stat = self.path.stat(follow_symlinks=False)
1005
+ if (not stat.S_ISREG(current_stat.st_mode) or current_stat.st_nlink != 1
1006
+ or (current_stat.st_dev, current_stat.st_ino)
1007
+ != (initial_stat.st_dev, initial_stat.st_ino)):
1008
+ _reject('owner-approval-ledger-unavailable')
1009
+ os.replace(temporary, self.path)
1010
+ _fsync_parent(self.path.parent)
1011
+ except OSError:
1012
+ _reject('owner-approval-ledger-write-failed')
1013
+ finally:
1014
+ if temp_fd >= 0:
1015
+ os.close(temp_fd)
1016
+ try:
1017
+ temporary.unlink()
1018
+ except FileNotFoundError:
1019
+ pass
1020
+
1021
+ def _with_records(self, operation):
1022
+ lock_fd, fd, is_new = self._open_locked()
1023
+ try:
1024
+ records = self._records(fd, is_new)
1025
+ return operation(fd, records)
1026
+ finally:
1027
+ os.close(fd)
1028
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
1029
+ os.close(lock_fd)
1030
+
1031
+ def _with_existing_records(self, operation):
1032
+ """Read existing history under its lock without creating either file."""
1033
+ lock_fd = -1
1034
+ fd = -1
1035
+ flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
1036
+ try:
1037
+ lock_fd = os.open(self.lock_path, flags)
1038
+ lock_stat = os.fstat(lock_fd)
1039
+ if (not stat.S_ISREG(lock_stat.st_mode) or lock_stat.st_uid != os.geteuid()
1040
+ or lock_stat.st_mode & 0o077 or lock_stat.st_nlink != 1):
1041
+ _reject('owner-approval-ledger-unavailable')
1042
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
1043
+ fd = os.open(self.path, flags)
1044
+ file_stat = os.fstat(fd)
1045
+ if (not stat.S_ISREG(file_stat.st_mode) or file_stat.st_uid != os.geteuid()
1046
+ or file_stat.st_mode & 0o077 or file_stat.st_nlink != 1):
1047
+ _reject('owner-approval-ledger-unavailable')
1048
+ records = self._records(fd, False)
1049
+ return operation(fd, records)
1050
+ except OSError:
1051
+ _reject('owner-approval-ledger-unavailable')
1052
+ finally:
1053
+ if fd >= 0:
1054
+ os.close(fd)
1055
+ if lock_fd >= 0:
1056
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
1057
+ os.close(lock_fd)
1058
+
1059
+ def find_or_reserve_request(self, *, scope: str, intent_digest: str,
1060
+ target: dict[str, str], intent: dict[str, Any],
1061
+ intent_bytes: bytes, effect_key: tuple[object, ...],
1062
+ context: OwnerAuthorityContext, create_payload) -> dict[str, Any]:
1063
+ def apply(fd: int, records: list[dict[str, Any]]) -> dict[str, Any]:
1064
+ full_effect_key = [context._purpose, context._custodian_id,
1065
+ context._supervisor_id, context._provider_id,
1066
+ context._installation_id, *effect_key]
1067
+ for row in reversed(records[1:]):
1068
+ if row['kind'] != 'request-prepared':
1069
+ continue
1070
+ saved = row['payload']
1071
+ if saved['stableKey'] == full_effect_key:
1072
+ if (saved['intent'] != intent or saved['scope'] != scope
1073
+ or saved['contextDigest'] != context._configuration_digest
1074
+ or saved['intentBytes'] != _base64url_encoded(intent_bytes)):
1075
+ _reject('owner-approval-original-request-invalid')
1076
+ return saved
1077
+ request_count = sum(row['kind'] == 'request-prepared' for row in records[1:])
1078
+ if request_count >= _MAX_REQUESTS:
1079
+ _reject('owner-approval-ledger-capacity')
1080
+ payload = create_payload()
1081
+ request = {'approvalId': payload['approvalId'], 'scope': scope,
1082
+ 'purpose': context._purpose,
1083
+ 'intentDigest': intent_digest,
1084
+ 'contextDigest': context._configuration_digest,
1085
+ 'effectKey': list(effect_key), 'stableKey': full_effect_key,
1086
+ 'target': target,
1087
+ 'payloadDigest': _digest_bytes(_canonical_bytes(payload))}
1088
+ body = {'sequence': len(records), 'previousDigest': records[-1]['digest'],
1089
+ 'kind': 'request-prepared',
1090
+ 'payload': {**request, 'intent': intent,
1091
+ 'signedPayload': payload,
1092
+ 'intentBytes': base64.urlsafe_b64encode(intent_bytes).decode('ascii').rstrip('=')
1093
+ }}
1094
+ self._append(fd, {**body, 'digest': _digest_bytes(_canonical_bytes(body))})
1095
+ return body['payload']
1096
+ return self._with_records(apply)
1097
+
1098
+ def find_original_request(self, *, scope: str, intent_digest: str,
1099
+ target: dict[str, str], intent: dict[str, Any],
1100
+ intent_bytes: bytes, effect_key: tuple[object, ...],
1101
+ context: OwnerAuthorityContext) -> dict[str, Any]:
1102
+ """Resolve an exact prior request without initializing or appending history."""
1103
+ full_effect_key = [context._purpose, context._custodian_id,
1104
+ context._supervisor_id, context._provider_id,
1105
+ context._installation_id, *effect_key]
1106
+
1107
+ def apply(_fd: int, records: list[dict[str, Any]]) -> dict[str, Any]:
1108
+ saved = next((row['payload'] for row in reversed(records[1:])
1109
+ if row['kind'] == 'request-prepared'
1110
+ and row['payload'].get('stableKey') == full_effect_key), None)
1111
+ if saved is None:
1112
+ _reject('owner-approval-original-request-unavailable')
1113
+ if (saved['scope'] != scope or saved['intentDigest'] != intent_digest
1114
+ or saved['contextDigest'] != context._configuration_digest
1115
+ or saved['target'] != target or saved['intent'] != intent
1116
+ or saved['intentBytes'] != _base64url_encoded(intent_bytes)
1117
+ or saved['effectKey'] != list(effect_key)):
1118
+ _reject('owner-approval-original-request-invalid')
1119
+ return saved
1120
+ return self._with_existing_records(apply)
1121
+
1122
+ def reserve_approval(self, request_id: str, envelope: dict[str, Any],
1123
+ envelope_digest: str, intent_digest: str) -> bool:
1124
+ def apply(fd: int, records: list[dict[str, Any]]) -> bool:
1125
+ requests = [row for row in records[1:] if row.get('kind') == 'request-prepared'
1126
+ and row['payload'].get('approvalId') == request_id]
1127
+ if not requests or requests[-1]['payload'].get('intentDigest') != intent_digest:
1128
+ _reject('owner-approval-request-not-original')
1129
+ existing = [row for row in records[1:] if row.get('kind') == 'approval-reserved'
1130
+ and row.get('payload', {}).get('approvalId') == request_id]
1131
+ if existing:
1132
+ if existing[-1]['payload'].get('envelopeDigest') != envelope_digest:
1133
+ _reject('owner-approval-replay-conflict')
1134
+ return False
1135
+ body = {'sequence': len(records), 'previousDigest': records[-1]['digest'],
1136
+ 'kind': 'approval-reserved',
1137
+ 'payload': {'approvalId': request_id, 'intentDigest': intent_digest,
1138
+ 'envelopeDigest': envelope_digest, 'envelope': envelope}}
1139
+ self._append(fd, {**body, 'digest': _digest_bytes(_canonical_bytes(body))})
1140
+ return True
1141
+ return self._with_existing_records(apply)
1142
+
1143
+ def find_original_approval(self, request_id: str,
1144
+ intent_digest: str) -> dict[str, Any]:
1145
+ """Read the exact originally reserved signature for restart recovery."""
1146
+ def apply(_fd: int, records: list[dict[str, Any]]) -> dict[str, Any]:
1147
+ request = next((row['payload'] for row in records[1:]
1148
+ if row['kind'] == 'request-prepared'
1149
+ and row['payload'].get('approvalId') == request_id), None)
1150
+ approval = next((row['payload'] for row in reversed(records[1:])
1151
+ if row['kind'] == 'approval-reserved'
1152
+ and row['payload'].get('approvalId') == request_id), None)
1153
+ if (request is None or request['intentDigest'] != intent_digest
1154
+ or approval is None or approval['intentDigest'] != intent_digest):
1155
+ _reject('owner-approval-original-approval-unavailable')
1156
+ return approval['envelope']
1157
+ return self._with_existing_records(apply)
1158
+
1159
+ def observe(self, request_id: str) -> tuple[dict[str, Any] | None,
1160
+ dict[str, Any] | None, bool]:
1161
+ def apply(_fd: int, records: list[dict[str, Any]]):
1162
+ request = next((row['payload'] for row in records[1:]
1163
+ if row.get('kind') == 'request-prepared'
1164
+ and row.get('payload', {}).get('approvalId') == request_id), None)
1165
+ approval = next((row['payload'] for row in reversed(records[1:])
1166
+ if row.get('kind') == 'approval-reserved'
1167
+ and row.get('payload', {}).get('approvalId') == request_id), None)
1168
+ dispatched = any(row.get('kind') == 'effect-dispatch-reserved'
1169
+ and row.get('payload', {}).get('approvalId') == request_id
1170
+ for row in records[1:])
1171
+ return request, approval, dispatched
1172
+ return self._with_existing_records(apply)
1173
+
1174
+ def reserve_effect_dispatch(self, request_id: str, envelope_digest: str) -> None:
1175
+ def apply(fd: int, records: list[dict[str, Any]]) -> None:
1176
+ approvals = [row['payload'] for row in records[1:]
1177
+ if row.get('kind') == 'approval-reserved'
1178
+ and row.get('payload', {}).get('approvalId') == request_id]
1179
+ if not approvals or approvals[-1].get('envelopeDigest') != envelope_digest:
1180
+ _reject('owner-approval-not-reserved')
1181
+ if any(row.get('kind') == 'effect-dispatch-reserved'
1182
+ and row.get('payload', {}).get('approvalId') == request_id
1183
+ for row in records[1:]):
1184
+ _reject('owner-approval-already-consumed')
1185
+ body = {'sequence': len(records), 'previousDigest': records[-1]['digest'],
1186
+ 'kind': 'effect-dispatch-reserved',
1187
+ 'payload': {'approvalId': request_id, 'envelopeDigest': envelope_digest}}
1188
+ self._append(fd, {**body, 'digest': _digest_bytes(_canonical_bytes(body))})
1189
+ self._with_existing_records(apply)
1190
+
1191
+ def bind_effect(self, request_id: str, reservation_digest: str) -> bool:
1192
+ def apply(fd: int, records: list[dict[str, Any]]) -> bool:
1193
+ approvals = [row['payload'] for row in records[1:]
1194
+ if row.get('kind') == 'approval-reserved'
1195
+ and row.get('payload', {}).get('approvalId') == request_id]
1196
+ if not approvals:
1197
+ _reject('owner-approval-not-reserved')
1198
+ prior = [row['payload'] for row in records[1:]
1199
+ if row.get('kind') == 'effect-pending'
1200
+ and row.get('payload', {}).get('approvalId') == request_id]
1201
+ if prior:
1202
+ if prior[-1]['reservationDigest'] != reservation_digest:
1203
+ _reject('owner-approval-replay-conflict')
1204
+ return False
1205
+ if any(row.get('kind') == 'effect-dispatch-reserved'
1206
+ and row.get('payload', {}).get('approvalId') == request_id
1207
+ for row in records[1:]):
1208
+ _reject('owner-approval-already-consumed')
1209
+ body = {'sequence': len(records), 'previousDigest': records[-1]['digest'],
1210
+ 'kind': 'effect-pending',
1211
+ 'payload': {'approvalId': request_id,
1212
+ 'reservationDigest': reservation_digest}}
1213
+ self._append(fd, {**body, 'digest': _digest_bytes(_canonical_bytes(body))})
1214
+ return True
1215
+ return self._with_existing_records(apply)
1216
+
1217
+ def finish_effect(self, request_id: str, reservation_digest: str, *,
1218
+ status: str, receipt_digest: str) -> None:
1219
+ def apply(fd: int, records: list[dict[str, Any]]) -> None:
1220
+ pending = [row['payload'] for row in records[1:]
1221
+ if row.get('kind') == 'effect-pending'
1222
+ and row.get('payload', {}).get('approvalId') == request_id]
1223
+ finished = next((row['payload'] for row in records[1:]
1224
+ if row.get('kind') == 'effect-outcome'
1225
+ and row.get('payload', {}).get('approvalId') == request_id), None)
1226
+ if (not pending or pending[-1]['reservationDigest'] != reservation_digest
1227
+ or status not in ('confirmed', 'aborted')):
1228
+ _reject('owner-approval-effect-state-invalid')
1229
+ if finished is not None:
1230
+ if (finished['reservationDigest'] == reservation_digest
1231
+ and finished['status'] == status
1232
+ and finished['receiptDigest'] == receipt_digest):
1233
+ return False
1234
+ _reject('owner-approval-effect-state-invalid')
1235
+ body = {'sequence': len(records), 'previousDigest': records[-1]['digest'],
1236
+ 'kind': 'effect-outcome',
1237
+ 'payload': {'approvalId': request_id,
1238
+ 'reservationDigest': reservation_digest,
1239
+ 'status': status, 'receiptDigest': _digest(receipt_digest)}}
1240
+ self._append(fd, {**body, 'digest': _digest_bytes(_canonical_bytes(body))})
1241
+ return True
1242
+ return self._with_existing_records(apply)
1243
+
1244
+ def observe_effect(self, request_id: str) -> tuple[dict[str, Any] | None,
1245
+ dict[str, Any] | None]:
1246
+ def apply(_fd: int, records: list[dict[str, Any]]):
1247
+ pending = next((row['payload'] for row in reversed(records[1:])
1248
+ if row.get('kind') == 'effect-pending'
1249
+ and row['payload'].get('approvalId') == request_id), None)
1250
+ outcome = next((row['payload'] for row in reversed(records[1:])
1251
+ if row.get('kind') == 'effect-outcome'
1252
+ and row['payload'].get('approvalId') == request_id), None)
1253
+ return pending, outcome
1254
+ return self._with_existing_records(apply)
1255
+
1256
+ def find_effect(self, effect_key: list[object], purpose: str) -> dict[str, Any] | None:
1257
+ def apply(_fd: int, records: list[dict[str, Any]]):
1258
+ request = next((row['payload'] for row in reversed(records[1:])
1259
+ if row.get('kind') == 'request-prepared'
1260
+ and row['payload'].get('stableKey') == effect_key
1261
+ and row['payload'].get('purpose') == purpose), None)
1262
+ return request
1263
+ return self._with_existing_records(apply)
1264
+
1265
+
1266
+ def _fsync_parent(parent: Path) -> None:
1267
+ fd = os.open(parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
1268
+ try:
1269
+ os.fsync(fd)
1270
+ finally:
1271
+ os.close(fd)
1272
+
1273
+
1274
+ class OwnerApprovalRequest:
1275
+ """Opaque immutable request bound to exact configured authority and bytes."""
1276
+
1277
+ __slots__ = ('_approval_id', '_context', '_effect_key', '_intent_bytes',
1278
+ '_intent_digest', '_issuer', '_kind', '_payload_bytes', '_scope')
1279
+
1280
+ def __init__(self, seal: object, issuer: object, *, approval_id: str, scope: str,
1281
+ intent_bytes: bytes, intent_digest: str,
1282
+ payload_bytes: bytes, effect_key: tuple[object, ...],
1283
+ context: OwnerAuthorityContext):
1284
+ if seal is not _CAPABILITY_SEAL:
1285
+ raise TypeError('owner approval requests are authority-issued')
1286
+ object.__setattr__(self, '_issuer', issuer)
1287
+ object.__setattr__(self, '_kind', _REQUEST_KIND)
1288
+ object.__setattr__(self, '_approval_id', approval_id)
1289
+ object.__setattr__(self, '_scope', scope)
1290
+ object.__setattr__(self, '_intent_bytes', intent_bytes)
1291
+ object.__setattr__(self, '_intent_digest', intent_digest)
1292
+ object.__setattr__(self, '_payload_bytes', payload_bytes)
1293
+ object.__setattr__(self, '_effect_key', effect_key)
1294
+ object.__setattr__(self, '_context', context)
1295
+
1296
+ def __setattr__(self, _name: str, _value: object) -> None:
1297
+ raise AttributeError('owner approval request is immutable')
1298
+
1299
+ def __reduce_ex__(self, _protocol: int):
1300
+ raise TypeError('owner approval requests cannot be serialized')
1301
+
1302
+ def __repr__(self) -> str:
1303
+ return '<OwnerApprovalRequest opaque>'
1304
+
1305
+ @property
1306
+ def scope(self) -> str:
1307
+ return self._scope
1308
+
1309
+ @property
1310
+ def effect_key(self) -> tuple[object, ...]:
1311
+ return self._effect_key
1312
+
1313
+
1314
+ class VerifiedOwnerApproval:
1315
+ """Opaque verified decision. It is not an effect receipt or native outcome."""
1316
+
1317
+ __slots__ = ('_approval_digest', '_envelope_bytes', '_issuer', '_kind',
1318
+ '_payload_bytes', '_request')
1319
+
1320
+ def __init__(self, seal: object, issuer: object, request: OwnerApprovalRequest,
1321
+ payload: dict[str, Any], approval_digest: str, envelope_bytes: bytes):
1322
+ if seal is not _CAPABILITY_SEAL:
1323
+ raise TypeError('verified owner approval is authority-issued')
1324
+ object.__setattr__(self, '_issuer', issuer)
1325
+ object.__setattr__(self, '_kind', _VERIFIED_KIND)
1326
+ object.__setattr__(self, '_request', request)
1327
+ object.__setattr__(self, '_payload_bytes', _canonical_bytes(payload))
1328
+ object.__setattr__(self, '_approval_digest', approval_digest)
1329
+ object.__setattr__(self, '_envelope_bytes', envelope_bytes)
1330
+
1331
+ def __setattr__(self, _name: str, _value: object) -> None:
1332
+ raise AttributeError('verified owner approval is immutable')
1333
+
1334
+ def __reduce_ex__(self, _protocol: int):
1335
+ raise TypeError('verified owner approval cannot be serialized')
1336
+
1337
+ def __repr__(self) -> str:
1338
+ return '<VerifiedOwnerApproval opaque>'
1339
+
1340
+ @property
1341
+ def authority_id(self) -> str:
1342
+ return _decode_canonical_object(self._payload_bytes)['authorityId']
1343
+
1344
+ @property
1345
+ def policy_revision(self) -> str:
1346
+ return _decode_canonical_object(self._payload_bytes)['policyRevision']
1347
+
1348
+ @property
1349
+ def approval_id(self) -> str:
1350
+ return _decode_canonical_object(self._payload_bytes)['approvalId']
1351
+
1352
+ @property
1353
+ def scope(self) -> str:
1354
+ return _decode_canonical_object(self._payload_bytes)['scope']
1355
+
1356
+ @property
1357
+ def principal_id(self) -> str:
1358
+ return _decode_canonical_object(self._payload_bytes)['principalId']
1359
+
1360
+ @property
1361
+ def purpose(self) -> str:
1362
+ return _decode_canonical_object(self._payload_bytes)['purpose']
1363
+
1364
+ @property
1365
+ def intent_digest(self) -> str:
1366
+ return _decode_canonical_object(self._payload_bytes)['intentDigest']
1367
+
1368
+ @property
1369
+ def approval_digest(self) -> str:
1370
+ return self._approval_digest
1371
+
1372
+
1373
+ class _BoundPendingEffect:
1374
+ """Core-issued proof that one exact reservation digest is durably bound."""
1375
+
1376
+ __slots__ = ('_core', '_kind', '_request', '_reservation_digest')
1377
+
1378
+ def __init__(self, seal: object, core: object, request: OwnerApprovalRequest,
1379
+ reservation_digest: str):
1380
+ if seal is not _PENDING_EFFECT_SEAL:
1381
+ raise TypeError('pending effect handles are core-issued')
1382
+ object.__setattr__(self, '_core', core)
1383
+ object.__setattr__(self, '_kind', 'umf.owner-approval-pending-effect/0.1')
1384
+ object.__setattr__(self, '_request', request)
1385
+ object.__setattr__(self, '_reservation_digest', _digest(reservation_digest))
1386
+
1387
+ def __setattr__(self, _name: str, _value: object) -> None:
1388
+ raise AttributeError('pending effect handles are immutable')
1389
+
1390
+ def __reduce_ex__(self, _protocol: int):
1391
+ raise TypeError('pending effect handles cannot be serialized')
1392
+
1393
+ def __repr__(self) -> str:
1394
+ return '<BoundPendingEffect opaque>'
1395
+
1396
+
1397
+ @dataclass(frozen=True, slots=True)
1398
+ class OriginalApprovalOutcome:
1399
+ """Read-only durable approval state; never asserts that a native effect committed."""
1400
+
1401
+ approval_id: str
1402
+ scope: str
1403
+ intent_digest: str
1404
+ approval_status: str
1405
+ approval_digest: str | None
1406
+ effect_status: str
1407
+ effect_digest: str | None = None
1408
+ effect_receipt_digest: str | None = None
1409
+
1410
+
1411
+ def _serialize_registry_access(method):
1412
+ @wraps(method)
1413
+ def serialized(self, *args, **kwargs):
1414
+ with self._registry_lock:
1415
+ return method(self, *args, **kwargs)
1416
+ return serialized
1417
+
1418
+
1419
+ class OwnerApprovalCore:
1420
+ """Configured Ed25519 signature verifier with an independent fsynced ledger."""
1421
+
1422
+ __slots__ = (
1423
+ '_authority_id',
1424
+ '_config',
1425
+ '_config_digest',
1426
+ '_context',
1427
+ '_journal_metadata',
1428
+ '_keys',
1429
+ '_ledger',
1430
+ '_pending_effects',
1431
+ '_policy_revision',
1432
+ '_registry_lock',
1433
+ '_requests',
1434
+ '_requests_by_approval',
1435
+ '_verified',
1436
+ '_verified_by_request',
1437
+ )
1438
+
1439
+ def __init__(self, configuration: object, *, ledger_path: str | os.PathLike[str],
1440
+ context: OwnerAuthorityContext):
1441
+ config, keys = _validate_config(configuration)
1442
+ config_bytes = _canonical_bytes(config)
1443
+ self._config = config
1444
+ self._keys = keys
1445
+ self._authority_id = config['authorityId']
1446
+ self._policy_revision = config['policyRevision']
1447
+ self._config_digest = _digest_bytes(config_bytes)
1448
+ self._context = _require_owner_context(
1449
+ context, configuration_digest=self._config_digest)
1450
+ from .owner_bootstrap import _owner_context_journal_metadata
1451
+ self._journal_metadata = _owner_context_journal_metadata(self._context)
1452
+ self._ledger = _ApprovalLedger(ledger_path, self._authority_id, self._config_digest,
1453
+ self._journal_metadata)
1454
+ self._requests: dict[int, OwnerApprovalRequest] = {}
1455
+ self._requests_by_approval: dict[str, OwnerApprovalRequest] = {}
1456
+ self._verified: dict[int, VerifiedOwnerApproval] = {}
1457
+ self._verified_by_request: dict[str, VerifiedOwnerApproval] = {}
1458
+ self._pending_effects: dict[int, _BoundPendingEffect] = {}
1459
+ self._registry_lock = threading.RLock()
1460
+
1461
+ @property
1462
+ def authority_id(self) -> str:
1463
+ return self._authority_id
1464
+
1465
+ @property
1466
+ def policy_revision(self) -> str:
1467
+ return self._policy_revision
1468
+
1469
+ @property
1470
+ def configuration_digest(self) -> str:
1471
+ return self._config_digest
1472
+
1473
+ @property
1474
+ def authority_context(self) -> OwnerAuthorityContext:
1475
+ return self._context
1476
+
1477
+ def _ensure_ledger_initialized(self) -> None:
1478
+ """Durably write the original ledger header before native binding."""
1479
+ self._ledger._with_records(lambda _fd, _records: None)
1480
+
1481
+ @_serialize_registry_access
1482
+ def prepare_request(self, scope: str, exact_intent_bytes: bytes, *,
1483
+ context: OwnerAuthorityContext) -> OwnerApprovalRequest:
1484
+ if (type(context) is not OwnerAuthorityContext or context is not self._context
1485
+ or _CONTEXTS.get(id(context)) is not context
1486
+ or context._issuer_registry is not context._issuer
1487
+ or context._configuration_digest != self._config_digest
1488
+ or context._purpose != self._config['purpose']):
1489
+ _reject('owner-authority-context-mismatch')
1490
+ if type(scope) is not str or scope not in _SCOPES:
1491
+ _reject('owner-approval-scope-invalid')
1492
+ intent = _parse_canonical_intent(exact_intent_bytes)
1493
+ target, effect_key = _validate_scope_intent(
1494
+ scope, intent, authority_id=self._authority_id,
1495
+ policy_revision=self._policy_revision, context=context,
1496
+ journal_metadata=self._journal_metadata)
1497
+ key = next((entry for entry in self._keys if scope in entry['scopes']
1498
+ and target['supervisorId'] in entry['supervisorIds']
1499
+ and target['providerId'] in entry['providerIds']
1500
+ and target['installationId'] in entry['installationIds']), None)
1501
+ if key is None:
1502
+ _reject('owner-approval-target-not-authorized')
1503
+ intent_digest = _digest_bytes(exact_intent_bytes)
1504
+ def create_payload() -> dict[str, Any]:
1505
+ approval_id = str(uuid.uuid4())
1506
+ return {'profile': OWNER_APPROVAL_PROFILE, 'authorityId': self._authority_id,
1507
+ 'policyRevision': self._policy_revision, 'keyId': key['keyId'],
1508
+ 'principalId': key['principalId'], 'approvalId': approval_id,
1509
+ 'purpose': context._purpose,
1510
+ 'scope': scope, 'custodianId': target['custodianId'],
1511
+ 'supervisorId': target['supervisorId'], 'providerId': target['providerId'],
1512
+ 'installationId': target['installationId'], 'intentDigest': intent_digest}
1513
+ prior = self._ledger.find_or_reserve_request(
1514
+ scope=scope, intent_digest=intent_digest, target=target, intent=intent,
1515
+ intent_bytes=exact_intent_bytes, effect_key=effect_key,
1516
+ context=context, create_payload=create_payload)
1517
+ payload = prior['signedPayload']
1518
+ if (payload.get('keyId') != key['keyId']
1519
+ or payload.get('principalId') != key['principalId']):
1520
+ _reject('owner-approval-original-request-invalid')
1521
+ approval_id = _uuid(payload.get('approvalId'))
1522
+ payload_bytes = _canonical_bytes(payload)
1523
+ if len(payload_bytes) > 16_384:
1524
+ _reject('owner-approval-payload-capacity')
1525
+ existing_request = self._requests_by_approval.get(approval_id)
1526
+ if existing_request is not None:
1527
+ if (existing_request._payload_bytes != payload_bytes
1528
+ or existing_request._intent_bytes != exact_intent_bytes):
1529
+ _reject('owner-approval-original-request-invalid')
1530
+ return existing_request
1531
+ request = self._make_request(approval_id, scope, exact_intent_bytes,
1532
+ intent_digest, payload_bytes,
1533
+ effect_key, context)
1534
+ self._requests[id(request)] = request
1535
+ self._requests_by_approval[approval_id] = request
1536
+ return request
1537
+
1538
+ @_serialize_registry_access
1539
+ def _recover_original_request(self, scope: str, exact_intent_bytes: bytes, *,
1540
+ context: OwnerAuthorityContext,
1541
+ expected_approval_id: str) -> OwnerApprovalRequest:
1542
+ """Recreate a request capability only from its exact existing ledger row.
1543
+
1544
+ This path is for recovery after process restart. It never creates a ledger,
1545
+ reserves a request, or substitutes a newly allocated approval identifier.
1546
+ """
1547
+ if (type(context) is not OwnerAuthorityContext or context is not self._context
1548
+ or _CONTEXTS.get(id(context)) is not context
1549
+ or context._issuer_registry is not context._issuer
1550
+ or context._configuration_digest != self._config_digest
1551
+ or context._purpose != self._config['purpose']):
1552
+ _reject('owner-authority-context-mismatch')
1553
+ if type(scope) is not str or scope not in _SCOPES:
1554
+ _reject('owner-approval-scope-invalid')
1555
+ expected_id = _uuid(expected_approval_id)
1556
+ intent = _parse_canonical_intent(exact_intent_bytes)
1557
+ target, effect_key = _validate_scope_intent(
1558
+ scope, intent, authority_id=self._authority_id,
1559
+ policy_revision=self._policy_revision, context=context,
1560
+ journal_metadata=self._journal_metadata)
1561
+ key = next((entry for entry in self._keys if scope in entry['scopes']
1562
+ and target['supervisorId'] in entry['supervisorIds']
1563
+ and target['providerId'] in entry['providerIds']
1564
+ and target['installationId'] in entry['installationIds']), None)
1565
+ if key is None:
1566
+ _reject('owner-approval-target-not-authorized')
1567
+ intent_digest = _digest_bytes(exact_intent_bytes)
1568
+ prior = self._ledger.find_original_request(
1569
+ scope=scope, intent_digest=intent_digest, target=target, intent=intent,
1570
+ intent_bytes=exact_intent_bytes, effect_key=effect_key, context=context)
1571
+ payload = prior['signedPayload']
1572
+ if (payload['approvalId'] != expected_id or payload['keyId'] != key['keyId']
1573
+ or payload['principalId'] != key['principalId']):
1574
+ _reject('owner-approval-original-request-invalid')
1575
+ approval_id = _uuid(payload['approvalId'])
1576
+ payload_bytes = _canonical_bytes(payload)
1577
+ if len(payload_bytes) > 16_384:
1578
+ _reject('owner-approval-payload-capacity')
1579
+ existing_request = self._requests_by_approval.get(approval_id)
1580
+ if existing_request is not None:
1581
+ if (existing_request._payload_bytes != payload_bytes
1582
+ or existing_request._intent_bytes != exact_intent_bytes):
1583
+ _reject('owner-approval-original-request-invalid')
1584
+ return existing_request
1585
+ request = self._make_request(approval_id, scope, exact_intent_bytes,
1586
+ intent_digest, payload_bytes, effect_key, context)
1587
+ self._requests[id(request)] = request
1588
+ self._requests_by_approval[approval_id] = request
1589
+ return request
1590
+
1591
+ @_serialize_registry_access
1592
+ def _recover_verified_approval(
1593
+ self, original_request: OwnerApprovalRequest) -> VerifiedOwnerApproval:
1594
+ """Re-verify only the original durably stored signature; never allocate."""
1595
+ request = self._require_request(original_request)
1596
+ envelope = self._ledger.find_original_approval(
1597
+ request._approval_id, request._intent_digest)
1598
+ return self.verify_approval(request, envelope)
1599
+
1600
+ def _make_request(self, approval_id: str, scope: str, intent_bytes: bytes,
1601
+ intent_digest: str, payload_bytes: bytes,
1602
+ effect_key: tuple[object, ...],
1603
+ context: OwnerAuthorityContext) -> OwnerApprovalRequest:
1604
+ return OwnerApprovalRequest(_CAPABILITY_SEAL, self, approval_id=approval_id,
1605
+ scope=scope, intent_bytes=bytes(intent_bytes),
1606
+ intent_digest=intent_digest, payload_bytes=payload_bytes,
1607
+ effect_key=effect_key, context=context)
1608
+
1609
+ @_serialize_registry_access
1610
+ def export_signing_request(self, original_request: OwnerApprovalRequest) -> dict[str, Any]:
1611
+ request = self._require_request(original_request)
1612
+ return {'payload': _decode_canonical_object(request._payload_bytes),
1613
+ 'intent': _parse_canonical_intent(request._intent_bytes)}
1614
+
1615
+ @_serialize_registry_access
1616
+ def verify_approval(self, original_request: OwnerApprovalRequest,
1617
+ signed_envelope: object) -> VerifiedOwnerApproval:
1618
+ request = self._require_request(original_request)
1619
+ envelope = _plain_json(signed_envelope, byte_limit=32_768)
1620
+ _closed(envelope, {'payload', 'signature'}, 'owner-approval-envelope-invalid')
1621
+ payload = _plain_json(envelope['payload'])
1622
+ _closed(payload, {'profile', 'authorityId', 'policyRevision', 'keyId', 'principalId',
1623
+ 'approvalId', 'purpose', 'scope', 'custodianId', 'supervisorId', 'providerId',
1624
+ 'installationId', 'intentDigest'}, 'owner-approval-envelope-invalid')
1625
+ payload_bytes = _canonical_bytes(payload)
1626
+ if payload_bytes != request._payload_bytes:
1627
+ _reject('owner-approval-request-mismatch')
1628
+ if payload.get('purpose') != self._context._purpose:
1629
+ _reject('owner-approval-request-mismatch')
1630
+ signature = _base64url(envelope['signature'], 64)
1631
+ key = next((entry for entry in self._keys if entry['keyId'] == payload['keyId']), None)
1632
+ if key is None or key['principalId'] != payload['principalId']:
1633
+ _reject('owner-approval-key-untrusted')
1634
+ try:
1635
+ from cryptography import __version__ as crypto_version
1636
+ from cryptography.exceptions import InvalidSignature
1637
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
1638
+ Ed25519PublicKey,
1639
+ )
1640
+ except ImportError:
1641
+ _reject('owner-approval-crypto-unavailable')
1642
+ if crypto_version != '50.0.2':
1643
+ _reject('owner-approval-crypto-version-unqualified')
1644
+ try:
1645
+ Ed25519PublicKey.from_public_bytes(key['publicKey']).verify(
1646
+ signature, _SIGNATURE_DOMAIN + payload_bytes)
1647
+ except InvalidSignature:
1648
+ _reject('owner-approval-signature-invalid')
1649
+ except (TypeError, ValueError):
1650
+ _reject('owner-approval-key-invalid')
1651
+ envelope_bytes = _canonical_bytes(envelope)
1652
+ envelope_digest = _digest_bytes(envelope_bytes)
1653
+ self._ledger.reserve_approval(request._approval_id, envelope,
1654
+ envelope_digest, request._intent_digest)
1655
+ existing = self._verified_by_request.get(request._approval_id)
1656
+ if existing is not None:
1657
+ if existing._approval_digest != envelope_digest:
1658
+ _reject('owner-approval-replay-conflict')
1659
+ return existing
1660
+ verified = self._make_verified(request, payload, envelope_digest, envelope_bytes)
1661
+ self._verified[id(verified)] = verified
1662
+ self._verified_by_request[request._approval_id] = verified
1663
+ return verified
1664
+
1665
+ def _make_verified(self, request: OwnerApprovalRequest, payload: dict[str, Any],
1666
+ envelope_digest: str, envelope_bytes: bytes) -> VerifiedOwnerApproval:
1667
+ return VerifiedOwnerApproval(_CAPABILITY_SEAL, self, request, payload,
1668
+ envelope_digest, envelope_bytes)
1669
+
1670
+ @_serialize_registry_access
1671
+ def observe_approval(self, original_request: OwnerApprovalRequest) -> OriginalApprovalOutcome:
1672
+ request = self._require_request(original_request)
1673
+ saved_request, approval, dispatched = self._ledger.observe(request._approval_id)
1674
+ if saved_request is None or saved_request['intentDigest'] != request._intent_digest:
1675
+ _reject('owner-approval-original-request-unavailable')
1676
+ pending, effect_outcome = self._ledger.observe_effect(request._approval_id)
1677
+ effect_status = ('prepared' if pending is None else 'effect-pending')
1678
+ receipt_digest = None
1679
+ if effect_outcome is not None:
1680
+ effect_status = effect_outcome['status']
1681
+ receipt_digest = effect_outcome['receiptDigest']
1682
+ elif dispatched and pending is None:
1683
+ effect_status = 'legacy-dispatch-recorded'
1684
+ return OriginalApprovalOutcome(
1685
+ approval_id=request._approval_id, scope=request._scope,
1686
+ intent_digest=request._intent_digest,
1687
+ approval_status='consumed' if approval else 'prepared',
1688
+ approval_digest=approval['envelopeDigest'] if approval else None,
1689
+ effect_status=effect_status,
1690
+ effect_digest=pending['reservationDigest'] if pending else None,
1691
+ effect_receipt_digest=receipt_digest)
1692
+
1693
+ @_serialize_registry_access
1694
+ def _require_request(self, value: object) -> OwnerApprovalRequest:
1695
+ if (type(value) is not OwnerApprovalRequest or value._issuer is not self
1696
+ or value._kind != _REQUEST_KIND or self._requests.get(id(value)) is not value):
1697
+ _reject('owner-approval-original-request-required')
1698
+ return value
1699
+
1700
+ @_serialize_registry_access
1701
+ def _resolve_verified_approval(self, value: object, *,
1702
+ original_request: OwnerApprovalRequest,
1703
+ scope: str, intent_digest: str) -> VerifiedOwnerApproval:
1704
+ request = self._require_request(original_request)
1705
+ if (type(value) is not VerifiedOwnerApproval or value._issuer is not self
1706
+ or value._kind != _VERIFIED_KIND or self._verified.get(id(value)) is not value
1707
+ or value._request is not request or value.scope != scope
1708
+ or value.intent_digest != intent_digest):
1709
+ _reject('owner-approval-capability-mismatch')
1710
+ return value
1711
+
1712
+ @_serialize_registry_access
1713
+ def _consume_verified_approval(self, value: object, *,
1714
+ original_request: OwnerApprovalRequest,
1715
+ scope: str, intent_digest: str) -> VerifiedOwnerApproval:
1716
+ """Refuse legacy dispatch without an original native reservation."""
1717
+ self._resolve_verified_approval(
1718
+ value, original_request=original_request, scope=scope,
1719
+ intent_digest=intent_digest)
1720
+ _reject('owner-native-reservation-required')
1721
+
1722
+ @_serialize_registry_access
1723
+ def _bind_effect_digest(self, verified_approval: VerifiedOwnerApproval,
1724
+ reservation_digest: str) -> _BoundPendingEffect:
1725
+ """Bind a façade-verified reservation and return a native-checkable proof."""
1726
+ request = self._require_request(
1727
+ verified_approval._request if type(verified_approval) is VerifiedOwnerApproval else None)
1728
+ self._resolve_verified_approval(
1729
+ verified_approval, original_request=request, scope=request._scope,
1730
+ intent_digest=request._intent_digest)
1731
+ digest = _digest(reservation_digest)
1732
+ self._ledger.bind_effect(request._approval_id, digest)
1733
+ for handle in self._pending_effects.values():
1734
+ if handle._request is request:
1735
+ if handle._reservation_digest != digest:
1736
+ _reject('owner-approval-replay-conflict')
1737
+ return handle
1738
+ handle = _BoundPendingEffect(_PENDING_EFFECT_SEAL, self, request, digest)
1739
+ self._pending_effects[id(handle)] = handle
1740
+ return handle
1741
+
1742
+ @_serialize_registry_access
1743
+ def _resolve_pending_effect(self, value: object, *,
1744
+ original_request: OwnerApprovalRequest,
1745
+ reservation_digest: str,
1746
+ mode: str = 'execute') -> _BoundPendingEffect:
1747
+ """Verify the exact private core handle against original ledger records."""
1748
+ request = self._require_request(original_request)
1749
+ digest = _digest(reservation_digest)
1750
+ if (type(value) is not _BoundPendingEffect or value._core is not self
1751
+ or value._kind != 'umf.owner-approval-pending-effect/0.1'
1752
+ or self._pending_effects.get(id(value)) is not value
1753
+ or value._request is not request
1754
+ or value._reservation_digest != digest):
1755
+ _reject('owner-native-reservation-required')
1756
+ pending, outcome = self._ledger.observe_effect(request._approval_id)
1757
+ if (pending is None or pending.get('reservationDigest') != digest
1758
+ or (outcome is not None and outcome.get('reservationDigest') != digest)):
1759
+ _reject('owner-native-reservation-required')
1760
+ if mode == 'execute':
1761
+ if outcome is not None:
1762
+ _reject('owner-native-reservation-required')
1763
+ elif mode == 'recover':
1764
+ if outcome is not None and outcome.get('status') not in ('confirmed', 'aborted'):
1765
+ _reject('owner-native-reservation-required')
1766
+ else:
1767
+ _reject('owner-native-reservation-required')
1768
+ return value
1769
+
1770
+ @_serialize_registry_access
1771
+ def _finish_effect_digest(self, original_request: OwnerApprovalRequest,
1772
+ reservation_digest: str, *, status: str,
1773
+ receipt_digest: str) -> OriginalApprovalOutcome:
1774
+ request = self._require_request(original_request)
1775
+ if status not in ('confirmed', 'aborted'):
1776
+ _reject('owner-native-outcome-untrusted')
1777
+ receipt = _digest(receipt_digest)
1778
+ self._ledger.finish_effect(request._approval_id, _digest(reservation_digest),
1779
+ status=status, receipt_digest=receipt)
1780
+ return self.observe_original_request(request._context, request._effect_key)
1781
+
1782
+ @_serialize_registry_access
1783
+ def observe_original_request(self, context: OwnerAuthorityContext,
1784
+ effect_key: tuple[object, ...]) -> OriginalApprovalOutcome:
1785
+ if (type(context) is not OwnerAuthorityContext or context is not self._context
1786
+ or _CONTEXTS.get(id(context)) is not context):
1787
+ _reject('owner-authority-context-mismatch')
1788
+ if type(effect_key) is not tuple or not effect_key:
1789
+ _reject('owner-approval-effect-key-invalid')
1790
+ stable = [context._purpose, context._custodian_id, context._supervisor_id,
1791
+ context._provider_id, context._installation_id, *effect_key]
1792
+ request = self._ledger.find_effect(stable, context._purpose)
1793
+ if request is None:
1794
+ _reject('owner-approval-original-request-unavailable')
1795
+ _saved_request, approval, _dispatched = self._ledger.observe(request['approvalId'])
1796
+ pending, outcome = self._ledger.observe_effect(request['approvalId'])
1797
+ if approval is None:
1798
+ approval_status, approval_digest = 'prepared', None
1799
+ else:
1800
+ approval_status, approval_digest = 'consumed', approval['envelopeDigest']
1801
+ effect_status = ('prepared' if pending is None else 'effect-pending')
1802
+ if outcome is not None:
1803
+ effect_status = outcome['status']
1804
+ return OriginalApprovalOutcome(
1805
+ approval_id=request['approvalId'], scope=request['scope'],
1806
+ intent_digest=request['intentDigest'], approval_status=approval_status,
1807
+ approval_digest=approval_digest,
1808
+ effect_status=effect_status,
1809
+ effect_digest=pending['reservationDigest'] if pending else None,
1810
+ effect_receipt_digest=outcome['receiptDigest'] if outcome else None)