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,750 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Durable external journal primitives for G11 target custody.
3
+
4
+ The journal is deliberately separate from the PostgreSQL ingress store. Its
5
+ append chain is an external source of original intent and sequence; it is not
6
+ by itself proof that a local server, process, data directory, or endpoint is
7
+ owned. Production ``TargetCustodian`` issuance remains fail-closed until the
8
+ bootstrap-enrolled native owner/supervisor adapter is implemented.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import fcntl
13
+ import os
14
+ import stat
15
+ import tempfile
16
+ from collections.abc import Iterator
17
+ from contextlib import contextmanager
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from . import target_custody_codec as _target_custody_codec
22
+
23
+ CustodyJournalError = _target_custody_codec.CustodyJournalError
24
+ JOURNAL_PROFILE = _target_custody_codec.JOURNAL_PROFILE
25
+ JOURNAL_PROFILE_02 = _target_custody_codec.JOURNAL_PROFILE_02
26
+ _HEX = _target_custody_codec._HEX
27
+ _KINDS = _target_custody_codec._KINDS
28
+ _KINDS_02 = _target_custody_codec._KINDS_02
29
+ _MAX_BYTES = _target_custody_codec._MAX_BYTES
30
+ _MAX_EVENTS = _target_custody_codec._MAX_EVENTS
31
+ _MAX_SAFE = _target_custody_codec._MAX_SAFE
32
+ _OWNER_REQUEST_KIND = _target_custody_codec._OWNER_REQUEST_KIND
33
+ _UUID = _target_custody_codec._UUID
34
+ _canonical = _target_custody_codec._canonical
35
+ _canonical_path = _target_custody_codec._canonical_path
36
+ _closed = _target_custody_codec._closed
37
+ _decimal = _target_custody_codec._decimal
38
+ _digest = _target_custody_codec._digest
39
+ _hex = _target_custody_codec._hex
40
+ _pairs_no_duplicates = _target_custody_codec._pairs_no_duplicates
41
+ _read_json = _target_custody_codec._read_json
42
+ _replay = _target_custody_codec._replay
43
+ _safe_uint32 = _target_custody_codec._safe_uint32
44
+ _text = _target_custody_codec._text
45
+ _uuid = _target_custody_codec._uuid
46
+ _validate_event_payload = _target_custody_codec._validate_event_payload
47
+ _validate_observation = _target_custody_codec._validate_observation
48
+ _validate_owner_payload = _target_custody_codec._validate_owner_payload
49
+ validate_original_target_custody_record = _target_custody_codec.validate_original_target_custody_record
50
+
51
+
52
+ _OWNER_RESOLVER_SEAL = object()
53
+ _OWNER_EVIDENCE_SEAL = object()
54
+ _CUSTODY_SEAL = object()
55
+
56
+
57
+ class _OwnerRegistrationEvidence:
58
+ """Private result tied to the exact bootstrap-enrolled resolver object."""
59
+
60
+ __slots__ = ('native_attestation', 'observation', 'payload', 'request', 'resolver')
61
+
62
+ def __init__(self, seal: object, resolver: object, request: object, payload: dict[str, Any],
63
+ observation: dict[str, Any], native_attestation: object):
64
+ if seal is not _OWNER_EVIDENCE_SEAL:
65
+ raise TypeError('owner registration evidence is issuer-created')
66
+ self.resolver = resolver
67
+ self.request = request
68
+ self.payload = payload
69
+ self.observation = observation
70
+ self.native_attestation = native_attestation
71
+
72
+ def __reduce_ex__(self, _protocol: int):
73
+ raise TypeError('owner registration evidence cannot be serialized')
74
+
75
+
76
+ class _OwnerRegistrationResolver:
77
+ """Exact enrolled resolver binding; a structural protocol is not accepted."""
78
+
79
+ __slots__ = ('_context', '_observe', '_resolve', 'adapter', 'issuer')
80
+
81
+ def __init__(self, seal: object, issuer: object, adapter: object,
82
+ control_context: object):
83
+ if seal is not _OWNER_RESOLVER_SEAL or issuer is None or control_context is None:
84
+ raise TypeError('owner resolver binding is trusted-bootstrap-only')
85
+ resolve = getattr(adapter, 'resolve_owner_registration', None)
86
+ observe = getattr(adapter, 'observe_original_registration', None)
87
+ if (getattr(resolve, '__self__', None) is not adapter
88
+ or getattr(observe, '__self__', None) is not adapter):
89
+ raise TypeError('owner resolver must be bound to its enrolled adapter')
90
+ self.issuer = issuer
91
+ self.adapter = adapter
92
+ self._context = control_context
93
+ self._resolve = resolve
94
+ self._observe = observe
95
+
96
+ def require_control_lease(self, value: object, *, operation_kind: str) -> object:
97
+ """Resolve the fixed physical bootstrap lease without an adapter callback."""
98
+ from .owner_bootstrap import _resolve_original_control_lease
99
+
100
+ return _resolve_original_control_lease(
101
+ value, context=self._context, supervisor=self.adapter,
102
+ operation_kind=operation_kind)
103
+
104
+ def resolve(self, request: object, custodian_id: str, provider_id: str) -> _OwnerRegistrationEvidence:
105
+ from .generation_ingress import OwnerEnrollmentRequest
106
+
107
+ if (type(request) is not OwnerEnrollmentRequest
108
+ or not request._issued_by(self.issuer, _OWNER_REQUEST_KIND)):
109
+ raise CustodyJournalError('owner-enrollment-required')
110
+ evidence = self._resolve(request, custodian_id=custodian_id, provider_id=provider_id)
111
+ if (type(evidence) is not _OwnerRegistrationEvidence or evidence.resolver is not self
112
+ or evidence.request is not request):
113
+ raise CustodyJournalError('owner-registration-unverified')
114
+ return evidence
115
+
116
+ def observe_original(self, request: object, original_payload: dict[str, Any],
117
+ custodian_sequence: int) -> _OwnerRegistrationEvidence:
118
+ from .generation_ingress import OwnerEnrollmentRequest
119
+
120
+ if (type(request) is not OwnerEnrollmentRequest
121
+ or not request._issued_by(self.issuer, _OWNER_REQUEST_KIND)):
122
+ raise CustodyJournalError('owner-enrollment-required')
123
+ evidence = self._observe(request, original_payload=original_payload,
124
+ custodian_sequence=custodian_sequence)
125
+ if (type(evidence) is not _OwnerRegistrationEvidence or evidence.resolver is not self
126
+ or evidence.request is not request or evidence.payload != original_payload):
127
+ raise CustodyJournalError('owner-registration-unverified')
128
+ return evidence
129
+
130
+
131
+ def _bind_owner_registration_resolver(issuer: object, adapter: object,
132
+ control_context: object) -> _OwnerRegistrationResolver:
133
+ """Private bootstrap seam; only trusted host bootstrap may call this."""
134
+ return _OwnerRegistrationResolver(_OWNER_RESOLVER_SEAL, issuer, adapter,
135
+ control_context)
136
+
137
+
138
+ def _issue_owner_registration_evidence(resolver: _OwnerRegistrationResolver, request: object,
139
+ payload: dict[str, Any], observation: dict[str, Any],
140
+ native_attestation: object) -> _OwnerRegistrationEvidence:
141
+ """Private issuer seam used by the enrolled native owner adapter."""
142
+ from .generation_ingress import OwnerEnrollmentRequest
143
+
144
+ if (type(resolver) is not _OwnerRegistrationResolver
145
+ or type(request) is not OwnerEnrollmentRequest
146
+ or not request._issued_by(resolver.issuer, _OWNER_REQUEST_KIND)
147
+ or native_attestation is None):
148
+ raise CustodyJournalError('owner-registration-unverified')
149
+ _validate_owner_payload(payload)
150
+ if payload['registrationId'] != getattr(request, '_registration_id', payload['registrationId']):
151
+ raise CustodyJournalError('owner-registration-unverified')
152
+ _validate_observation(observation, payload)
153
+ return _OwnerRegistrationEvidence(_OWNER_EVIDENCE_SEAL, resolver, request,
154
+ payload, observation, native_attestation)
155
+
156
+
157
+
158
+
159
+ class _VerifiedTargetCustody:
160
+ """Nonserializable binding from an issued handle to its retained origin."""
161
+
162
+ __slots__ = ('_seal', 'custodian', 'native_attestation', 'reference', 'registration')
163
+
164
+ def __init__(self, seal: object, custodian: object, registration: dict[str, Any],
165
+ native_attestation: object, reference: dict[str, Any]):
166
+ if seal is not _CUSTODY_SEAL:
167
+ raise TypeError('verified target custody is custodian-issued')
168
+ self.custodian = custodian
169
+ self.registration = registration
170
+ self.native_attestation = native_attestation
171
+ self.reference = reference
172
+ self._seal = seal
173
+
174
+ def __reduce_ex__(self, _protocol: int):
175
+ raise TypeError('verified target custody cannot be serialized')
176
+
177
+
178
+ class ExternalCustodyJournal:
179
+ """Private append journal; it cannot detect replacement by an older copy alone.
180
+
181
+ The enrolled native owner/controller must compare this sequence against its
182
+ independently retained original custody chain before issuing capabilities.
183
+ """
184
+
185
+ __slots__ = ('_birth_bytes', '_birth_handle', '_context', '_custodian_id',
186
+ '_issuer', '_lock_path', '_path', '_profile', '_resolver',
187
+ '_supervisor')
188
+
189
+ def __init__(self, path: str | os.PathLike[str], custodian_id: str):
190
+ self._path = Path(path)
191
+ self._lock_path = self._path.with_name(self._path.name + '.lock')
192
+ self._custodian_id = _text(custodian_id, 256)
193
+ self._profile = JOURNAL_PROFILE
194
+ self._birth_bytes = None
195
+ self._birth_handle = None
196
+ self._context = None
197
+ self._issuer = None
198
+ self._resolver = None
199
+ self._supervisor = None
200
+ parent = self._path.parent
201
+ if not parent.is_absolute() or os.path.normpath(str(parent)) != str(parent):
202
+ raise CustodyJournalError('journal-directory-unsafe')
203
+ try:
204
+ st = os.lstat(parent)
205
+ except OSError:
206
+ raise CustodyJournalError('journal-directory-unavailable') from None
207
+ if (not stat.S_ISDIR(st.st_mode) or stat.S_ISLNK(st.st_mode)
208
+ or st.st_uid != os.geteuid() or stat.S_IMODE(st.st_mode) & 0o077
209
+ or any(part.is_symlink() for part in (parent, *parent.parents))):
210
+ raise CustodyJournalError('journal-directory-unsafe')
211
+
212
+ @classmethod
213
+ def _open_original_02(cls, birth_handle: object, *, resolver: _OwnerRegistrationResolver,
214
+ control_lease: object,
215
+ operation_kind: str) -> ExternalCustodyJournal:
216
+ """Open only the bootstrap-selected original 0.2 journal under its lease."""
217
+ from .owner_bootstrap import _resolve_original_target_custody_journal_birth
218
+ if type(resolver) is not _OwnerRegistrationResolver:
219
+ raise CustodyJournalError('journal-origin-unverified')
220
+ try:
221
+ if operation_kind not in ('registration-apply', 'registration-recover', 'store'):
222
+ raise CustodyJournalError('journal-origin-unverified')
223
+ resolver.require_control_lease(control_lease, operation_kind=operation_kind)
224
+ descriptor = _resolve_original_target_custody_journal_birth(
225
+ birth_handle, issuer=resolver.adapter._bootstrap_issuer,
226
+ context=resolver._context,
227
+ supervisor=resolver.adapter, control_lease=control_lease)
228
+ except Exception: # noqa: BLE001 - redact bootstrap details at journal boundary
229
+ raise CustodyJournalError('journal-origin-unverified') from None
230
+ path = Path(descriptor['path'])
231
+ parent = path.parent
232
+ try:
233
+ st = os.lstat(parent)
234
+ except OSError:
235
+ raise CustodyJournalError('journal-directory-unavailable') from None
236
+ if (not stat.S_ISDIR(st.st_mode) or stat.S_ISLNK(st.st_mode)
237
+ or st.st_uid != os.geteuid() or stat.S_IMODE(st.st_mode) & 0o077
238
+ or any(part.is_symlink() for part in (parent, *parent.parents))):
239
+ raise CustodyJournalError('journal-directory-unsafe')
240
+ journal = object.__new__(cls)
241
+ journal._path = path
242
+ journal._lock_path = Path(descriptor['lockPath'])
243
+ journal._custodian_id = _uuid(descriptor['custodianId'])
244
+ journal._profile = JOURNAL_PROFILE_02
245
+ journal._birth_bytes = _canonical(descriptor)
246
+ journal._birth_handle = birth_handle
247
+ journal._context = resolver._context
248
+ journal._issuer = resolver.adapter._bootstrap_issuer
249
+ journal._resolver = resolver
250
+ journal._supervisor = resolver.adapter
251
+ return journal
252
+
253
+ def _verify_original_birth(self) -> dict[str, Any]:
254
+ if self._profile != JOURNAL_PROFILE_02:
255
+ raise CustodyJournalError('journal-origin-unverified')
256
+ from .owner_bootstrap import _resolve_original_target_custody_journal_birth
257
+ try:
258
+ lease = self._supervisor._require_original_control_lease()
259
+ descriptor = _resolve_original_target_custody_journal_birth(
260
+ self._birth_handle, issuer=self._issuer, context=self._context,
261
+ supervisor=self._supervisor, control_lease=lease)
262
+ except Exception: # noqa: BLE001 - every missing/changed binding refuses
263
+ raise CustodyJournalError('journal-origin-unverified') from None
264
+ if _canonical(descriptor) != self._birth_bytes:
265
+ raise CustodyJournalError('journal-origin-unverified')
266
+ return descriptor
267
+
268
+ def _read(self) -> dict[str, Any]:
269
+ if self._profile == JOURNAL_PROFILE_02:
270
+ self._verify_original_birth()
271
+ try:
272
+ fd = os.open(self._path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
273
+ except FileNotFoundError:
274
+ if self._profile == JOURNAL_PROFILE_02:
275
+ raise CustodyJournalError('journal-unavailable') from None
276
+ return {'profile': JOURNAL_PROFILE, 'custodianId': self._custodian_id,
277
+ 'sequence': 0, 'headDigest': '0' * 64, 'events': []}
278
+ except OSError:
279
+ raise CustodyJournalError('journal-unavailable') from None
280
+ try:
281
+ st = os.fstat(fd)
282
+ if (not stat.S_ISREG(st.st_mode) or st.st_nlink != 1 or st.st_uid != os.geteuid()
283
+ or stat.S_IMODE(st.st_mode) & 0o077 or st.st_size > _MAX_BYTES):
284
+ raise CustodyJournalError('journal-unsafe')
285
+ if self._profile == JOURNAL_PROFILE_02:
286
+ path_st = os.lstat(self._path)
287
+ if (not stat.S_ISREG(path_st.st_mode) or stat.S_ISLNK(path_st.st_mode)
288
+ or path_st.st_uid != os.geteuid() or path_st.st_nlink != 1
289
+ or stat.S_IMODE(path_st.st_mode) != 0o600
290
+ or (path_st.st_dev, path_st.st_ino) != (st.st_dev, st.st_ino)):
291
+ raise CustodyJournalError('journal-unsafe')
292
+ chunks = bytearray()
293
+ while len(chunks) <= _MAX_BYTES:
294
+ chunk = os.read(fd, min(65536, _MAX_BYTES + 1 - len(chunks)))
295
+ if not chunk:
296
+ break
297
+ chunks.extend(chunk)
298
+ if len(chunks) > _MAX_BYTES:
299
+ raise CustodyJournalError('journal-capacity')
300
+ # Re-observation after an interrupted replace fsyncs the visible
301
+ # inode and parent entry before any capability may be reissued.
302
+ os.fsync(fd)
303
+ except OSError:
304
+ raise CustodyJournalError('journal-read-failed') from None
305
+ finally:
306
+ os.close(fd)
307
+ try:
308
+ dirfd = os.open(self._path.parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
309
+ try:
310
+ os.fsync(dirfd)
311
+ finally:
312
+ os.close(dirfd)
313
+ except OSError:
314
+ raise CustodyJournalError('journal-durability-unverified') from None
315
+ doc = _read_json(bytes(chunks))
316
+ _closed(doc, {'profile', 'custodianId', 'sequence', 'headDigest', 'events'})
317
+ if (doc['profile'] != self._profile or doc['custodianId'] != self._custodian_id
318
+ or type(doc['events']) is not list or len(doc['events']) > _MAX_EVENTS):
319
+ raise CustodyJournalError('journal-corrupt')
320
+ allowed_kinds = _KINDS_02 if self._profile == JOURNAL_PROFILE_02 else _KINDS
321
+ previous = '0' * 64
322
+ for index, event in enumerate(doc['events'], 1):
323
+ _closed(event, {'sequence', 'kind', 'payload', 'previousDigest', 'recordDigest'})
324
+ if (type(event['sequence']) is not int or event['sequence'] != index
325
+ or event['previousDigest'] != previous or event['kind'] not in allowed_kinds):
326
+ raise CustodyJournalError('journal-corrupt')
327
+ _validate_event_payload(event['kind'], event['payload'], profile=self._profile)
328
+ unhashed = {key: event[key] for key in ('sequence', 'kind', 'payload', 'previousDigest')}
329
+ if event['recordDigest'] != _digest(unhashed):
330
+ raise CustodyJournalError('journal-corrupt')
331
+ previous = event['recordDigest']
332
+ if (type(doc['sequence']) is not int or doc['sequence'] != len(doc['events'])
333
+ or doc['headDigest'] != previous):
334
+ raise CustodyJournalError('journal-corrupt')
335
+ _replay(doc['events'], profile=self._profile)
336
+ return doc
337
+
338
+ @contextmanager
339
+ def _locked(self) -> Iterator[int]:
340
+ flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
341
+ if self._profile == JOURNAL_PROFILE:
342
+ flags |= os.O_CREAT
343
+ try:
344
+ fd = os.open(self._lock_path, flags, 0o600)
345
+ if self._profile == JOURNAL_PROFILE:
346
+ os.fchmod(fd, 0o600)
347
+ st = os.fstat(fd)
348
+ if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1 or st.st_uid != os.geteuid():
349
+ raise CustodyJournalError('journal-lock-unsafe')
350
+ if self._profile == JOURNAL_PROFILE_02:
351
+ path_st = os.lstat(self._lock_path)
352
+ if (not stat.S_ISREG(path_st.st_mode) or stat.S_ISLNK(path_st.st_mode)
353
+ or path_st.st_uid != os.geteuid() or path_st.st_nlink != 1
354
+ or stat.S_IMODE(path_st.st_mode) != 0o600
355
+ or (path_st.st_dev, path_st.st_ino) != (st.st_dev, st.st_ino)):
356
+ raise CustodyJournalError('journal-lock-unsafe')
357
+ fcntl.flock(fd, fcntl.LOCK_EX)
358
+ except CustodyJournalError:
359
+ if 'fd' in locals():
360
+ os.close(fd)
361
+ raise
362
+ except OSError:
363
+ if 'fd' in locals():
364
+ os.close(fd)
365
+ raise CustodyJournalError('journal-lock-unavailable') from None
366
+ try:
367
+ yield fd
368
+ finally:
369
+ fcntl.flock(fd, fcntl.LOCK_UN)
370
+ os.close(fd)
371
+
372
+ def _append(self, kind: str, payload: dict[str, Any]) -> dict[str, Any]:
373
+ """Internal trusted-adapter seam; never accept a caller authorization here."""
374
+ allowed_kinds = _KINDS_02 if self._profile == JOURNAL_PROFILE_02 else _KINDS
375
+ if kind not in allowed_kinds:
376
+ raise CustodyJournalError('journal-invalid')
377
+ payload = _validate_event_payload(kind, payload, profile=self._profile)
378
+ with self._locked():
379
+ doc = self._read()
380
+ if len(doc['events']) >= _MAX_EVENTS:
381
+ raise CustodyJournalError('journal-capacity')
382
+ if kind == 'originals-store-reserved':
383
+ if (payload['parent'] != {'sequence': doc['sequence'],
384
+ 'headDigest': doc['headDigest']}
385
+ or payload['reservation']['custodySequence'] != doc['sequence'] + 1):
386
+ raise CustodyJournalError('journal-state-mismatch')
387
+ elif (kind == 'originals-store-observation'
388
+ and payload['parent'] != {'sequence': doc['sequence'],
389
+ 'headDigest': doc['headDigest']}):
390
+ raise CustodyJournalError('journal-state-mismatch')
391
+ if kind in ('epoch-provision-reserved', 'transition-reserved'):
392
+ reservation_key = 'reservation'
393
+ reservation = payload[reservation_key]
394
+ if (reservation['sequence'] != doc['sequence'] + 1
395
+ or reservation['parentStateDigest'] != doc['headDigest']):
396
+ raise CustodyJournalError('journal-state-mismatch')
397
+ event = {'sequence': doc['sequence'] + 1, 'kind': kind, 'payload': payload,
398
+ 'previousDigest': doc['headDigest']}
399
+ event['recordDigest'] = _digest(event)
400
+ events = [*doc['events'], event]
401
+ _replay(events, profile=self._profile)
402
+ updated = {'profile': self._profile, 'custodianId': self._custodian_id,
403
+ 'sequence': event['sequence'], 'headDigest': event['recordDigest'],
404
+ 'events': events}
405
+ data = _canonical(updated)
406
+ self._replace(data)
407
+ return {'sequence': event['sequence'], 'recordDigest': event['recordDigest'],
408
+ 'headDigest': event['recordDigest']}
409
+
410
+ def _reserve_originals_store(self, *, purpose: str, request: dict[str, Any],
411
+ approval_digest: str,
412
+ reservation: dict[str, Any]) -> dict[str, Any]:
413
+ if self._profile != JOURNAL_PROFILE_02:
414
+ raise CustodyJournalError('journal-profile-mismatch')
415
+ parent_doc = self._load()
416
+ original = dict(reservation)
417
+ original['custodySequence'] = parent_doc['sequence'] + 1
418
+ payload = {'purpose': purpose, 'request': request,
419
+ 'approvalDigest': approval_digest, 'reservation': original,
420
+ 'reservationDigest': _digest(original),
421
+ 'parent': {'sequence': parent_doc['sequence'],
422
+ 'headDigest': parent_doc['headDigest']}}
423
+ return self._append('originals-store-reserved', payload)
424
+
425
+ def _observe_originals_store(self, *, purpose: str, reservation_id: str,
426
+ reservation_digest: str, supervisor_intent_digest: str,
427
+ outcome: str, native_receipt: dict[str, Any] | None,
428
+ native_receipt_digest: str | None, schema_oid: int | None,
429
+ native_observation_digest: str,
430
+ transaction_outcome_digest: str) -> dict[str, Any]:
431
+ if self._profile != JOURNAL_PROFILE_02:
432
+ raise CustodyJournalError('journal-profile-mismatch')
433
+ parent_doc = self._load()
434
+ payload = {
435
+ 'purpose': purpose, 'reservationId': reservation_id,
436
+ 'reservationDigest': reservation_digest,
437
+ 'supervisorIntentDigest': supervisor_intent_digest,
438
+ 'outcome': outcome, 'nativeReceipt': native_receipt,
439
+ 'nativeReceiptDigest': native_receipt_digest, 'schemaOid': schema_oid,
440
+ 'nativeObservationDigest': native_observation_digest,
441
+ 'transactionOutcomeDigest': transaction_outcome_digest,
442
+ 'parent': {'sequence': parent_doc['sequence'],
443
+ 'headDigest': parent_doc['headDigest']},
444
+ }
445
+ return self._append('originals-store-observation', payload)
446
+
447
+ def _confirm_originals_store(self, *, purpose: str, reservation_id: str,
448
+ reservation_digest: str, supervisor_intent_digest: str,
449
+ observation_event_digest: str,
450
+ native_receipt_digest: str, schema_oid: int) -> dict[str, Any]:
451
+ if self._profile != JOURNAL_PROFILE_02:
452
+ raise CustodyJournalError('journal-profile-mismatch')
453
+ return self._append('originals-store-confirmed', {
454
+ 'purpose': purpose, 'reservationId': reservation_id,
455
+ 'reservationDigest': reservation_digest,
456
+ 'supervisorIntentDigest': supervisor_intent_digest,
457
+ 'observationEventDigest': observation_event_digest,
458
+ 'nativeReceiptDigest': native_receipt_digest, 'schemaOid': schema_oid,
459
+ })
460
+
461
+ def _replace(self, data: bytes) -> None:
462
+ parent = self._path.parent
463
+ fd = -1
464
+ temporary = None
465
+ try:
466
+ fd, temporary = tempfile.mkstemp(prefix='.custody-', dir=parent)
467
+ os.fchmod(fd, 0o600)
468
+ with os.fdopen(fd, 'wb', closefd=True) as stream:
469
+ fd = -1
470
+ stream.write(data)
471
+ stream.flush()
472
+ os.fsync(stream.fileno())
473
+ os.replace(temporary, self._path)
474
+ temporary = None
475
+ dirfd = os.open(parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
476
+ try:
477
+ os.fsync(dirfd)
478
+ finally:
479
+ os.close(dirfd)
480
+ except OSError:
481
+ raise CustodyJournalError('journal-write-failed') from None
482
+ finally:
483
+ if fd >= 0:
484
+ os.close(fd)
485
+ if temporary is not None:
486
+ try:
487
+ os.unlink(temporary)
488
+ except OSError:
489
+ pass
490
+
491
+ def snapshot(self) -> dict[str, Any]:
492
+ """Return only non-secret journal state for diagnostics; payloads stay private."""
493
+ doc = self._load()
494
+ state = _replay(doc['events'], profile=self._profile)
495
+ pending = {key: value['id'] for key, value in state.items()
496
+ if key != 'stores' and value is not None
497
+ and value['status'] != 'confirmed'}
498
+ if self._profile == JOURNAL_PROFILE_02:
499
+ pending['stores'] = sorted(
500
+ value['id'] for value in state['stores'].values()
501
+ if value['status'] != 'confirmed')
502
+ return {'profile': self._profile, 'custodianId': self._custodian_id,
503
+ 'sequence': doc['sequence'], 'headDigest': doc['headDigest'],
504
+ 'pending': pending}
505
+
506
+ def _load(self) -> dict[str, Any]:
507
+ with self._locked():
508
+ return self._read()
509
+
510
+ class LocalTargetCustodian:
511
+ """External journal plus identity-bound custody handle issuance.
512
+
513
+ The constructor is private-bootstrap-only. The enrolled adapter must
514
+ resolve an original owner request and return object-bound native evidence;
515
+ this file journal cannot establish physical target ownership on its own.
516
+ """
517
+
518
+ __slots__ = ('_handles', '_issuer', '_journal', '_resolver', 'custodian_id', 'provider_id')
519
+
520
+ def __init__(self, seal: object, journal: ExternalCustodyJournal,
521
+ custodian_id: str, provider_id: str,
522
+ resolver: _OwnerRegistrationResolver):
523
+ if (seal is not _CUSTODY_SEAL or type(journal) is not ExternalCustodyJournal
524
+ or type(resolver) is not _OwnerRegistrationResolver):
525
+ raise TypeError('local target custodian requires trusted host bootstrap')
526
+ self._journal = journal
527
+ self.custodian_id = _uuid(custodian_id)
528
+ self.provider_id = _uuid(provider_id)
529
+ self._resolver = resolver
530
+ self._issuer = object()
531
+ self._handles: dict[int, tuple[object, _VerifiedTargetCustody]] = {}
532
+
533
+ def register_target(self, owner_enrollment: object, *, control_lease: object) -> object:
534
+ from .generation_ingress import OwnerEnrollmentRequest, TargetCustody
535
+
536
+ self._resolver.require_control_lease(
537
+ control_lease, operation_kind='registration-apply')
538
+ if type(owner_enrollment) is not OwnerEnrollmentRequest:
539
+ raise CustodyJournalError('owner-enrollment-required')
540
+ evidence = self._resolver.resolve(owner_enrollment, self.custodian_id, self.provider_id)
541
+ payload = evidence.payload
542
+ _validate_owner_payload(payload)
543
+ if payload['custodianId'] != self.custodian_id or payload['providerId'] != self.provider_id:
544
+ raise CustodyJournalError('owner-registration-mismatch')
545
+ registration_id = payload['registrationId']
546
+ document = self._journal._load()
547
+ current = _replay(document['events'], profile=self._journal._profile)['registration']
548
+ if current is None:
549
+ # An original durable intent is recorded before any subsequent
550
+ # provider enrollment operation. It is never replaced on restart.
551
+ _validate_observation(evidence.observation, payload)
552
+ approval = payload['ownerApproval']
553
+ expected_intent = {
554
+ 'registrationId': registration_id,
555
+ 'registrationDigest': evidence.observation['registrationDigest'],
556
+ 'ownerPayload': payload,
557
+ 'ownerApproval': {'approvalId': approval['approvalId'],
558
+ 'approvalDigest': approval['approvalDigest']},
559
+ }
560
+ try:
561
+ self._resolver.require_control_lease(
562
+ control_lease, operation_kind='registration-apply')
563
+ self._journal._append('registration-intent', expected_intent)
564
+ except CustodyJournalError:
565
+ # The atomic replace may have completed before its acknowledgement
566
+ # was lost. Reconcile only the same original intent; never retry
567
+ # with a new registration identity.
568
+ observed = self._journal._load()
569
+ intents = [event['payload'] for event in observed['events']
570
+ if event['kind'] == 'registration-intent']
571
+ if intents != [expected_intent]:
572
+ raise
573
+ document = self._journal._load()
574
+ current = _replay(document['events'], profile=self._journal._profile)['registration']
575
+ else:
576
+ original_intent = next(event['payload'] for event in document['events']
577
+ if event['kind'] == 'registration-intent')
578
+ if (current['id'] != registration_id
579
+ or original_intent['ownerPayload'] != payload):
580
+ raise CustodyJournalError('registration-original-outcome-unresolved')
581
+ intent = next(event['payload'] for event in document['events']
582
+ if event['kind'] == 'registration-intent')
583
+ fresh = self._resolver.observe_original(owner_enrollment, intent['ownerPayload'],
584
+ document['sequence'])
585
+ self._check_fresh_observation(fresh, document, payload, intent['registrationDigest'])
586
+
587
+ observation = fresh.observation
588
+ observation_event = {'registrationId': registration_id, 'observation': observation}
589
+ try:
590
+ self._resolver.require_control_lease(
591
+ control_lease, operation_kind='registration-apply')
592
+ self._journal._append('registration-observation', observation_event)
593
+ except CustodyJournalError:
594
+ observed = self._journal._load()
595
+ matching = [event['payload'] for event in observed['events']
596
+ if event['kind'] == 'registration-observation'
597
+ and event['payload'] == observation_event]
598
+ if not matching:
599
+ raise
600
+ latest = _replay(self._journal._load()['events'],
601
+ profile=self._journal._profile)['registration']
602
+ reference = {
603
+ 'profile': 'umf.native-target-custody/0.1',
604
+ 'custodianId': self.custodian_id,
605
+ 'registrationId': registration_id,
606
+ 'resourceId': payload['origin']['clusterId'],
607
+ 'incarnation': payload['origin']['incarnationId'],
608
+ 'registrationDigest': observation['registrationDigest'],
609
+ }
610
+ if latest['status'] != 'confirmed':
611
+ confirmation = {
612
+ 'registrationId': registration_id, 'targetCustody': reference,
613
+ }
614
+ try:
615
+ self._resolver.require_control_lease(
616
+ control_lease, operation_kind='registration-apply')
617
+ self._journal._append('registration-confirmed', confirmation)
618
+ except CustodyJournalError:
619
+ observed = self._journal._load()
620
+ confirmations = [event['payload'] for event in observed['events']
621
+ if event['kind'] == 'registration-confirmed']
622
+ if confirmations != [confirmation]:
623
+ raise
624
+ raise CustodyJournalError('registration-confirmation-outcome-unknown') from None
625
+ handle = TargetCustody(_target_capability_seal(), self._issuer,
626
+ 'umf.native-target-custody/0.1')
627
+ verified = _VerifiedTargetCustody(_CUSTODY_SEAL, self, payload,
628
+ fresh.native_attestation, reference)
629
+ self._handles[id(handle)] = (handle, verified)
630
+ self._resolver.require_control_lease(
631
+ control_lease, operation_kind='registration-apply')
632
+ return handle
633
+
634
+ def reattach_confirmed_target(self, owner_enrollment: object, *,
635
+ control_lease: object) -> object:
636
+ """Reissue volatile custody for the exact already-confirmed registration.
637
+
638
+ This recovery path is deliberately read-only: it requires the original
639
+ intent and confirmation in the journal, re-resolves the exact owner
640
+ request, and obtains a fresh native observation. It never appends an
641
+ observation or confirmation and cannot create a new registration.
642
+ """
643
+ from .generation_ingress import OwnerEnrollmentRequest, TargetCustody
644
+
645
+ self._resolver.require_control_lease(
646
+ control_lease, operation_kind='registration-recover')
647
+ if type(owner_enrollment) is not OwnerEnrollmentRequest:
648
+ raise CustodyJournalError('owner-enrollment-required')
649
+ evidence = self._resolver.resolve(owner_enrollment, self.custodian_id,
650
+ self.provider_id)
651
+ payload = evidence.payload
652
+ _validate_owner_payload(payload)
653
+ if (payload['custodianId'] != self.custodian_id
654
+ or payload['providerId'] != self.provider_id):
655
+ raise CustodyJournalError('owner-registration-mismatch')
656
+
657
+ document = self._journal._load()
658
+ state = _replay(document['events'], profile=self._journal._profile)['registration']
659
+ if state is None or state.get('status') != 'confirmed':
660
+ raise CustodyJournalError('registration-confirmation-required')
661
+ intents = [event['payload'] for event in document['events']
662
+ if event['kind'] == 'registration-intent']
663
+ confirmations = [event['payload'] for event in document['events']
664
+ if event['kind'] == 'registration-confirmed']
665
+ if (len(intents) != 1 or len(confirmations) != 1
666
+ or state.get('id') != payload['registrationId']
667
+ or intents[0]['registrationId'] != payload['registrationId']
668
+ or intents[0]['ownerPayload'] != payload
669
+ or intents[0]['registrationDigest'] != evidence.observation['registrationDigest']
670
+ or confirmations[0] != {'registrationId': payload['registrationId'],
671
+ 'targetCustody': state.get('custody')}):
672
+ raise CustodyJournalError('registration-original-outcome-unresolved')
673
+
674
+ fresh = self._resolver.observe_original(
675
+ owner_enrollment, intents[0]['ownerPayload'], document['sequence'])
676
+ self._check_fresh_observation(
677
+ fresh, document, payload, intents[0]['registrationDigest'])
678
+ observation = fresh.observation
679
+ reference = {
680
+ 'profile': 'umf.native-target-custody/0.1',
681
+ 'custodianId': self.custodian_id,
682
+ 'registrationId': payload['registrationId'],
683
+ 'resourceId': payload['origin']['clusterId'],
684
+ 'incarnation': payload['origin']['incarnationId'],
685
+ 'registrationDigest': observation['registrationDigest'],
686
+ }
687
+ if reference != state.get('custody'):
688
+ raise CustodyJournalError('registration-original-outcome-unresolved')
689
+
690
+ handle = TargetCustody(_target_capability_seal(), self._issuer,
691
+ 'umf.native-target-custody/0.1')
692
+ verified = _VerifiedTargetCustody(_CUSTODY_SEAL, self, payload,
693
+ fresh.native_attestation, reference)
694
+ self._handles[id(handle)] = (handle, verified)
695
+ self._resolver.require_control_lease(
696
+ control_lease, operation_kind='registration-recover')
697
+ return handle
698
+
699
+ @staticmethod
700
+ def _check_fresh_observation(evidence: _OwnerRegistrationEvidence,
701
+ document: dict[str, Any], payload: dict[str, Any],
702
+ original_digest: str | None) -> None:
703
+ _validate_observation(evidence.observation, payload)
704
+ if evidence.observation['custodianSequence'] != document['sequence']:
705
+ raise CustodyJournalError('owner-observation-sequence-mismatch')
706
+ if (original_digest is not None
707
+ and evidence.observation['registrationDigest'] != original_digest):
708
+ raise CustodyJournalError('registration-original-outcome-unresolved')
709
+
710
+ def _resolve_target_custody(self, handle: object) -> _VerifiedTargetCustody:
711
+ from .generation_ingress import TargetCustody
712
+
713
+ if (type(handle) is not TargetCustody
714
+ or not handle._issued_by(self._issuer, 'umf.native-target-custody/0.1')):
715
+ raise CustodyJournalError('target-custody-required')
716
+ entry = self._handles.get(id(handle))
717
+ if (entry is None or entry[0] is not handle
718
+ or type(entry[1]) is not _VerifiedTargetCustody
719
+ or entry[1].custodian is not self):
720
+ raise CustodyJournalError('target-custody-required')
721
+ return entry[1]
722
+
723
+ def _public_reference(self, handle: object) -> dict[str, Any]:
724
+ return dict(self._resolve_target_custody(handle).reference)
725
+
726
+
727
+ def _bootstrap_local_target_custodian(journal: ExternalCustodyJournal,
728
+ custodian_id: str, provider_id: str,
729
+ resolver: _OwnerRegistrationResolver) -> LocalTargetCustodian:
730
+ """Private trusted-bootstrap entry; not a user-selected resolver API."""
731
+ return LocalTargetCustodian(_CUSTODY_SEAL, journal, custodian_id, provider_id, resolver)
732
+
733
+
734
+ def _bootstrap_original_02_target_custodian(
735
+ birth_handle: object, *, custodian_id: str, provider_id: str,
736
+ resolver: _OwnerRegistrationResolver, control_lease: object,
737
+ operation_kind: str) -> LocalTargetCustodian:
738
+ """Select the fresh external 0.2 journal only through original birth custody."""
739
+ journal = ExternalCustodyJournal._open_original_02(
740
+ birth_handle, resolver=resolver, control_lease=control_lease,
741
+ operation_kind=operation_kind)
742
+ return LocalTargetCustodian(_CUSTODY_SEAL, journal, custodian_id,
743
+ provider_id, resolver)
744
+
745
+
746
+ def _target_capability_seal() -> object:
747
+ """Internal access to the opaque-handle seal, never a public issuer API."""
748
+ from . import generation_ingress
749
+
750
+ return generation_ingress._CAPABILITY_SEAL