umf-access 0.1.0.dev8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
|
@@ -0,0 +1,2077 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Original local-host bootstrap authority and immutable owner context."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import fcntl
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import stat
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from ..canonical import canonical_json
|
|
22
|
+
from .owner_wire import OwnerWireError, validate_owner_configuration
|
|
23
|
+
|
|
24
|
+
_MAX_SAFE = 9_007_199_254_740_991
|
|
25
|
+
_MAX_JOURNAL = 8 * 1024 * 1024
|
|
26
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
27
|
+
_ROLE = re.compile(r'^[a-z][a-z0-9_]{0,62}$')
|
|
28
|
+
_BOOTSTRAP_ISSUER_SEAL = object()
|
|
29
|
+
_BOOTSTRAP_ISSUERS: dict[int, object] = {}
|
|
30
|
+
_CONTEXT_SEAL = object()
|
|
31
|
+
_CONTEXTS: dict[int, object] = {}
|
|
32
|
+
_CONTEXT_JOURNAL_METADATA: dict[int, tuple[object, object, bytes]] = {}
|
|
33
|
+
_SUPERVISOR_JOURNAL_BIRTH_SEAL = object()
|
|
34
|
+
_SUPERVISOR_JOURNAL_BIRTHS: dict[int, tuple[object, object, object, bytes]] = {}
|
|
35
|
+
_TARGET_CUSTODY_JOURNAL_BIRTH_SEAL = object()
|
|
36
|
+
_TARGET_CUSTODY_JOURNAL_BIRTHS: dict[int, tuple[object, object, bytes]] = {}
|
|
37
|
+
_CONTROL_LEASE_SEAL = object()
|
|
38
|
+
_CONTROL_LEASES: dict[int, tuple[object, object, object, object, str]] = {}
|
|
39
|
+
_CONTROL_LEASES_GUARD = threading.Lock()
|
|
40
|
+
_CONTROL_LEASE_KINDS = frozenset({
|
|
41
|
+
'target-prepare', 'target-apply', 'target-recover',
|
|
42
|
+
'principals-prepare', 'principals-apply', 'principals-recover',
|
|
43
|
+
'registration-prepare', 'registration-apply', 'registration-recover',
|
|
44
|
+
'process-recover', 'target-registered', 'store', 'epoch', 'transition', 'root',
|
|
45
|
+
})
|
|
46
|
+
_OWNER_PURPOSES = ('production', 'native-acceptance')
|
|
47
|
+
_OWNER_CONTEXT_PROFILE = 'umf.local-owner-bootstrap-context/0.3'
|
|
48
|
+
_OWNER_SETUP_LOCK = 'owner-bootstrap-setup.lock'
|
|
49
|
+
_OWNER_LEDGER_PROFILE = 'umf.configured-owner-approval-ledger/0.1'
|
|
50
|
+
_OWNER_SETUP_LOCKS: dict[str, threading.Lock] = {}
|
|
51
|
+
_OWNER_SETUP_LOCKS_GUARD = threading.Lock()
|
|
52
|
+
_NATIVE_PROFILE_KEYS = {
|
|
53
|
+
'controlHome', 'dataHome', 'postgresBinary', 'initdbBinary',
|
|
54
|
+
'processObserver', 'processObserverSha256', 'port', 'databaseName',
|
|
55
|
+
'businessOwner', 'custodianId', 'supervisorId', 'providerId',
|
|
56
|
+
'installationId', 'purpose',
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
class LocalPostgresError(RuntimeError):
|
|
60
|
+
"""Sanitized failure from the concrete local owner profile."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, code: str):
|
|
63
|
+
super().__init__(code)
|
|
64
|
+
self.code = code
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _canonical(value: Any) -> bytes:
|
|
68
|
+
stack = [(value, 0)]
|
|
69
|
+
nodes = 0
|
|
70
|
+
while stack:
|
|
71
|
+
item, depth = stack.pop()
|
|
72
|
+
nodes += 1
|
|
73
|
+
if nodes > 100_000 or depth > 64:
|
|
74
|
+
raise LocalPostgresError('supervisor-record-capacity')
|
|
75
|
+
if item is None or type(item) is bool:
|
|
76
|
+
continue
|
|
77
|
+
if type(item) is int:
|
|
78
|
+
if abs(item) > _MAX_SAFE:
|
|
79
|
+
raise LocalPostgresError('supervisor-record-invalid')
|
|
80
|
+
elif type(item) is str:
|
|
81
|
+
try:
|
|
82
|
+
item.encode('utf-8')
|
|
83
|
+
except UnicodeEncodeError:
|
|
84
|
+
raise LocalPostgresError('supervisor-record-invalid') from None
|
|
85
|
+
if '\x00' in item:
|
|
86
|
+
raise LocalPostgresError('supervisor-record-invalid')
|
|
87
|
+
elif type(item) is list:
|
|
88
|
+
stack.extend((x, depth + 1) for x in item)
|
|
89
|
+
elif type(item) is dict:
|
|
90
|
+
for key, child in item.items():
|
|
91
|
+
if type(key) is not str or not key.isascii():
|
|
92
|
+
raise LocalPostgresError('supervisor-record-invalid')
|
|
93
|
+
stack.extend(((key, depth + 1), (child, depth + 1)))
|
|
94
|
+
else:
|
|
95
|
+
raise LocalPostgresError('supervisor-record-invalid')
|
|
96
|
+
try:
|
|
97
|
+
raw = json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
98
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
99
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
100
|
+
raise LocalPostgresError('supervisor-record-invalid') from None
|
|
101
|
+
if len(raw) > _MAX_JOURNAL:
|
|
102
|
+
raise LocalPostgresError('supervisor-record-capacity')
|
|
103
|
+
return raw
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _digest(value: Any) -> str:
|
|
107
|
+
return hashlib.sha256(_canonical(value)).hexdigest()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _uuid(value: str) -> str:
|
|
111
|
+
try:
|
|
112
|
+
parsed = uuid.UUID(value)
|
|
113
|
+
except (ValueError, TypeError, AttributeError):
|
|
114
|
+
raise LocalPostgresError('supervisor-identity-invalid') from None
|
|
115
|
+
if str(parsed) != value:
|
|
116
|
+
raise LocalPostgresError('supervisor-identity-invalid')
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _role(value: str) -> str:
|
|
121
|
+
if (type(value) is not str or not _ROLE.fullmatch(value)
|
|
122
|
+
or value == 'postgres' or value.startswith('pg_')):
|
|
123
|
+
raise LocalPostgresError('supervisor-role-name-invalid')
|
|
124
|
+
return value
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _private_directory(path: Path, *, create: bool = False) -> Path:
|
|
128
|
+
if not path.is_absolute() or os.path.normpath(str(path)) != str(path):
|
|
129
|
+
raise LocalPostgresError('supervisor-path-invalid')
|
|
130
|
+
if create:
|
|
131
|
+
try:
|
|
132
|
+
path.mkdir(mode=0o700)
|
|
133
|
+
except FileExistsError:
|
|
134
|
+
raise LocalPostgresError('supervisor-path-already-exists') from None
|
|
135
|
+
except OSError:
|
|
136
|
+
raise LocalPostgresError('supervisor-path-create-failed') from None
|
|
137
|
+
try:
|
|
138
|
+
st = os.lstat(path)
|
|
139
|
+
except OSError:
|
|
140
|
+
raise LocalPostgresError('supervisor-path-unavailable') from None
|
|
141
|
+
if (not stat.S_ISDIR(st.st_mode) or stat.S_ISLNK(st.st_mode)
|
|
142
|
+
or st.st_uid != os.geteuid() or stat.S_IMODE(st.st_mode) != 0o700):
|
|
143
|
+
raise LocalPostgresError('supervisor-path-unsafe')
|
|
144
|
+
if path.resolve(strict=True) != path:
|
|
145
|
+
raise LocalPostgresError('supervisor-path-unsafe')
|
|
146
|
+
return path
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _write_private(path: Path, data: bytes, *, exclusive: bool = True) -> None:
|
|
150
|
+
flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0)
|
|
151
|
+
flags |= os.O_EXCL if exclusive else os.O_TRUNC
|
|
152
|
+
try:
|
|
153
|
+
fd = os.open(path, flags, 0o600)
|
|
154
|
+
except OSError:
|
|
155
|
+
raise LocalPostgresError('supervisor-private-file-create-failed') from None
|
|
156
|
+
try:
|
|
157
|
+
os.fchmod(fd, 0o600)
|
|
158
|
+
st = os.fstat(fd)
|
|
159
|
+
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid() or st.st_nlink != 1:
|
|
160
|
+
raise LocalPostgresError('supervisor-private-file-unsafe')
|
|
161
|
+
view = memoryview(data)
|
|
162
|
+
while view:
|
|
163
|
+
written = os.write(fd, view)
|
|
164
|
+
if written <= 0:
|
|
165
|
+
raise LocalPostgresError('supervisor-private-file-write-failed')
|
|
166
|
+
view = view[written:]
|
|
167
|
+
os.fsync(fd)
|
|
168
|
+
except OSError:
|
|
169
|
+
raise LocalPostgresError('supervisor-private-file-write-failed') from None
|
|
170
|
+
finally:
|
|
171
|
+
os.close(fd)
|
|
172
|
+
_fsync_directory(path.parent)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _fsync_directory(path: Path) -> None:
|
|
176
|
+
try:
|
|
177
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
|
|
178
|
+
try:
|
|
179
|
+
os.fsync(fd)
|
|
180
|
+
finally:
|
|
181
|
+
os.close(fd)
|
|
182
|
+
except OSError:
|
|
183
|
+
raise LocalPostgresError('supervisor-directory-durability-unverified') from None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _read_private(path: Path) -> bytes:
|
|
187
|
+
try:
|
|
188
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
|
189
|
+
except OSError:
|
|
190
|
+
raise LocalPostgresError('supervisor-private-file-unavailable') from None
|
|
191
|
+
try:
|
|
192
|
+
st = os.fstat(fd)
|
|
193
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
194
|
+
or st.st_nlink != 1 or stat.S_IMODE(st.st_mode) != 0o600
|
|
195
|
+
or st.st_size > _MAX_JOURNAL):
|
|
196
|
+
raise LocalPostgresError('supervisor-private-file-unsafe')
|
|
197
|
+
raw = bytearray()
|
|
198
|
+
while len(raw) <= _MAX_JOURNAL:
|
|
199
|
+
chunk = os.read(fd, min(65_536, _MAX_JOURNAL + 1 - len(raw)))
|
|
200
|
+
if not chunk:
|
|
201
|
+
break
|
|
202
|
+
raw.extend(chunk)
|
|
203
|
+
if len(raw) > _MAX_JOURNAL:
|
|
204
|
+
raise LocalPostgresError('supervisor-record-capacity')
|
|
205
|
+
os.fsync(fd)
|
|
206
|
+
except OSError:
|
|
207
|
+
raise LocalPostgresError('supervisor-private-file-read-failed') from None
|
|
208
|
+
finally:
|
|
209
|
+
os.close(fd)
|
|
210
|
+
_fsync_directory(path.parent)
|
|
211
|
+
return bytes(raw)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
215
|
+
result = {}
|
|
216
|
+
for key, value in pairs:
|
|
217
|
+
if key in result:
|
|
218
|
+
raise LocalPostgresError('supervisor-journal-corrupt')
|
|
219
|
+
result[key] = value
|
|
220
|
+
return result
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@dataclass(frozen=True, slots=True)
|
|
224
|
+
class LocalPostgresProfile:
|
|
225
|
+
"""Trusted installed host profile, never constructed from migration input."""
|
|
226
|
+
|
|
227
|
+
control_home: Path
|
|
228
|
+
data_home: Path
|
|
229
|
+
postgres_binary: Path
|
|
230
|
+
initdb_binary: Path
|
|
231
|
+
process_observer: Path
|
|
232
|
+
process_observer_sha256: str
|
|
233
|
+
port: int
|
|
234
|
+
database_name: str
|
|
235
|
+
business_owner: str
|
|
236
|
+
custodian_id: str
|
|
237
|
+
supervisor_id: str
|
|
238
|
+
provider_id: str
|
|
239
|
+
installation_id: str
|
|
240
|
+
purpose: str
|
|
241
|
+
|
|
242
|
+
def __post_init__(self) -> None:
|
|
243
|
+
if os.name != 'posix' or not sys_platform_darwin():
|
|
244
|
+
raise LocalPostgresError('local-postgresql-profile-unsupported-platform')
|
|
245
|
+
if type(self.port) is not int or not 1 <= self.port <= 65535:
|
|
246
|
+
raise LocalPostgresError('local-postgresql-port-invalid')
|
|
247
|
+
_role(self.database_name)
|
|
248
|
+
_role(self.business_owner)
|
|
249
|
+
_uuid(self.custodian_id)
|
|
250
|
+
_uuid(self.supervisor_id)
|
|
251
|
+
_uuid(self.provider_id)
|
|
252
|
+
if (type(self.installation_id) is not str
|
|
253
|
+
or not 1 <= len(self.installation_id.encode('utf-8')) <= 128
|
|
254
|
+
or '\x00' in self.installation_id
|
|
255
|
+
or self.purpose not in ('production', 'native-acceptance')):
|
|
256
|
+
raise LocalPostgresError('local-postgresql-profile-invalid')
|
|
257
|
+
if self.supervisor_id == self.provider_id:
|
|
258
|
+
raise LocalPostgresError('local-postgresql-profile-invalid')
|
|
259
|
+
if type(self.process_observer_sha256) is not str or not _HEX.fullmatch(self.process_observer_sha256):
|
|
260
|
+
raise LocalPostgresError('local-postgresql-observer-pin-invalid')
|
|
261
|
+
for name in ('control_home', 'data_home'):
|
|
262
|
+
path = getattr(self, name)
|
|
263
|
+
if not isinstance(path, Path):
|
|
264
|
+
raise LocalPostgresError('local-postgresql-profile-invalid')
|
|
265
|
+
_private_directory(path)
|
|
266
|
+
if (self.control_home == self.data_home
|
|
267
|
+
or self.control_home in self.data_home.parents
|
|
268
|
+
or self.data_home in self.control_home.parents):
|
|
269
|
+
raise LocalPostgresError('local-postgresql-roots-overlap')
|
|
270
|
+
for name in ('postgres_binary', 'initdb_binary', 'process_observer'):
|
|
271
|
+
if not isinstance(getattr(self, name), Path):
|
|
272
|
+
raise LocalPostgresError('local-postgresql-profile-invalid')
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class _LocalOwnerBootstrapIssuer:
|
|
276
|
+
"""Original private host enrollment used to bind the immutable authority context.
|
|
277
|
+
|
|
278
|
+
This is created by the trusted installation factory, before a target exists.
|
|
279
|
+
It is deliberately not derived from a UID, public registration, or journal
|
|
280
|
+
dictionary and is never serialized as an authority.
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
__slots__ = (
|
|
284
|
+
'_configuration_bytes',
|
|
285
|
+
'_configuration_digest',
|
|
286
|
+
'_context_bytes',
|
|
287
|
+
'_context_material',
|
|
288
|
+
'_enrollment_digest',
|
|
289
|
+
'_enrollment_id',
|
|
290
|
+
'_enrollment_path',
|
|
291
|
+
'_installation_id',
|
|
292
|
+
'_issuer_id',
|
|
293
|
+
'_profile',
|
|
294
|
+
'_purpose',
|
|
295
|
+
'_supervisor',
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
def __init__(self, seal: object, profile: LocalPostgresProfile,
|
|
299
|
+
configuration_digest: str, *, enrollment_id: str,
|
|
300
|
+
enrollment_path: Path, enrollment_digest: str,
|
|
301
|
+
configuration_bytes: bytes, context_material: tuple[str, ...],
|
|
302
|
+
context_bytes: bytes):
|
|
303
|
+
if seal is not _BOOTSTRAP_ISSUER_SEAL or type(profile) is not LocalPostgresProfile:
|
|
304
|
+
raise TypeError('local bootstrap issuer is trusted-host issued')
|
|
305
|
+
if type(configuration_digest) is not str or not _HEX.fullmatch(configuration_digest):
|
|
306
|
+
raise LocalPostgresError('local-postgresql-owner-configuration-invalid')
|
|
307
|
+
self._profile = profile
|
|
308
|
+
self._supervisor = None
|
|
309
|
+
self._purpose = profile.purpose
|
|
310
|
+
self._installation_id = profile.installation_id
|
|
311
|
+
self._configuration_digest = configuration_digest
|
|
312
|
+
# The public identifier is stable across a process restart for the
|
|
313
|
+
# exact enrolled bytes. The issuer object itself remains process-local
|
|
314
|
+
# and registry-bound, so this identifier is not a capability.
|
|
315
|
+
self._issuer_id = str(uuid.uuid5(
|
|
316
|
+
uuid.NAMESPACE_URL,
|
|
317
|
+
'umf.local-owner-bootstrap-issuer/0.1:' + enrollment_digest))
|
|
318
|
+
self._enrollment_id = _uuid(enrollment_id)
|
|
319
|
+
self._enrollment_path = enrollment_path
|
|
320
|
+
self._enrollment_digest = enrollment_digest
|
|
321
|
+
self._configuration_bytes = bytes(configuration_bytes)
|
|
322
|
+
self._context_material = context_material
|
|
323
|
+
self._context_bytes = bytes(context_bytes)
|
|
324
|
+
_BOOTSTRAP_ISSUERS[id(self)] = self
|
|
325
|
+
|
|
326
|
+
def _owner_authority_context_material(self) -> tuple[str, str, str, str, str, str]:
|
|
327
|
+
if _BOOTSTRAP_ISSUERS.get(id(self)) is not self:
|
|
328
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
329
|
+
_verify_bootstrap_enrollment(self._enrollment_path, self._enrollment_digest)
|
|
330
|
+
try:
|
|
331
|
+
if _read_private(self._profile.control_home / 'owner-bootstrap-context.json') != self._context_bytes:
|
|
332
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-changed')
|
|
333
|
+
except LocalPostgresError:
|
|
334
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unavailable') from None
|
|
335
|
+
return self._context_material
|
|
336
|
+
|
|
337
|
+
@property
|
|
338
|
+
def owner_configuration(self) -> dict[str, Any]:
|
|
339
|
+
_verify_bootstrap_enrollment(self._enrollment_path, self._enrollment_digest)
|
|
340
|
+
value = json.loads(self._configuration_bytes, object_pairs_hook=_no_duplicates)
|
|
341
|
+
if type(value) is not dict:
|
|
342
|
+
raise LocalPostgresError('local-postgresql-owner-configuration-invalid')
|
|
343
|
+
return value
|
|
344
|
+
|
|
345
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
346
|
+
if hasattr(self, name):
|
|
347
|
+
raise AttributeError('local bootstrap issuer is immutable')
|
|
348
|
+
object.__setattr__(self, name, value)
|
|
349
|
+
|
|
350
|
+
def __reduce_ex__(self, _protocol: int):
|
|
351
|
+
raise TypeError('local bootstrap issuer cannot be serialized')
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class _OriginalSupervisorJournalBirth:
|
|
355
|
+
"""Opaque original 0.2 journal selector issued only after setup confirms."""
|
|
356
|
+
|
|
357
|
+
__slots__ = ('_descriptor_bytes', '_issuer', '_kind')
|
|
358
|
+
|
|
359
|
+
def __init__(self, seal: object, issuer: _LocalOwnerBootstrapIssuer,
|
|
360
|
+
descriptor_bytes: bytes):
|
|
361
|
+
if seal is not _SUPERVISOR_JOURNAL_BIRTH_SEAL:
|
|
362
|
+
raise TypeError('supervisor journal birth is bootstrap-issued')
|
|
363
|
+
object.__setattr__(self, '_issuer', issuer)
|
|
364
|
+
object.__setattr__(self, '_descriptor_bytes', bytes(descriptor_bytes))
|
|
365
|
+
object.__setattr__(self, '_kind', 'umf.original-supervisor-journal-birth/0.1')
|
|
366
|
+
|
|
367
|
+
def __setattr__(self, _name: str, _value: object) -> None:
|
|
368
|
+
raise AttributeError('supervisor journal birth is immutable')
|
|
369
|
+
|
|
370
|
+
def __reduce_ex__(self, _protocol: int):
|
|
371
|
+
raise TypeError('supervisor journal birth cannot be serialized')
|
|
372
|
+
|
|
373
|
+
def __repr__(self) -> str:
|
|
374
|
+
return '<OriginalSupervisorJournalBirth opaque>'
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class _OriginalTargetCustodyJournalBirth:
|
|
378
|
+
"""Opaque 0.2 external-journal selector issued by fresh enrollment only."""
|
|
379
|
+
|
|
380
|
+
__slots__ = ('_descriptor_bytes', '_issuer', '_kind')
|
|
381
|
+
|
|
382
|
+
def __init__(self, seal: object, issuer: _LocalOwnerBootstrapIssuer,
|
|
383
|
+
descriptor_bytes: bytes):
|
|
384
|
+
if seal is not _TARGET_CUSTODY_JOURNAL_BIRTH_SEAL:
|
|
385
|
+
raise TypeError('target custody journal birth is bootstrap-issued')
|
|
386
|
+
object.__setattr__(self, '_issuer', issuer)
|
|
387
|
+
object.__setattr__(self, '_descriptor_bytes', bytes(descriptor_bytes))
|
|
388
|
+
object.__setattr__(self, '_kind', 'umf.original-target-custody-journal-birth/0.1')
|
|
389
|
+
|
|
390
|
+
def __setattr__(self, _name: str, _value: object) -> None:
|
|
391
|
+
raise AttributeError('target custody journal birth is immutable')
|
|
392
|
+
|
|
393
|
+
def __reduce_ex__(self, _protocol: int):
|
|
394
|
+
raise TypeError('target custody journal birth cannot be serialized')
|
|
395
|
+
|
|
396
|
+
def __repr__(self) -> str:
|
|
397
|
+
return '<OriginalTargetCustodyJournalBirth opaque>'
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
_NATIVE_PROFILE_KEYS = {
|
|
401
|
+
'controlHome', 'dataHome', 'postgresBinary', 'initdbBinary',
|
|
402
|
+
'processObserver', 'processObserverSha256', 'port', 'databaseName',
|
|
403
|
+
'businessOwner', 'custodianId', 'supervisorId', 'providerId',
|
|
404
|
+
'installationId', 'purpose',
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _profile_to_enrollment(profile: LocalPostgresProfile) -> dict[str, Any]:
|
|
409
|
+
return {'controlHome': str(profile.control_home), 'dataHome': str(profile.data_home),
|
|
410
|
+
'postgresBinary': str(profile.postgres_binary),
|
|
411
|
+
'initdbBinary': str(profile.initdb_binary),
|
|
412
|
+
'processObserver': str(profile.process_observer),
|
|
413
|
+
'processObserverSha256': profile.process_observer_sha256,
|
|
414
|
+
'port': profile.port, 'databaseName': profile.database_name,
|
|
415
|
+
'businessOwner': profile.business_owner,
|
|
416
|
+
'custodianId': profile.custodian_id,
|
|
417
|
+
'supervisorId': profile.supervisor_id, 'providerId': profile.provider_id,
|
|
418
|
+
'installationId': profile.installation_id, 'purpose': profile.purpose}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _read_bootstrap_enrollment(path: Path) -> tuple[dict[str, Any], bytes]:
|
|
422
|
+
if (not isinstance(path, Path) or not path.is_absolute()
|
|
423
|
+
or path.name != 'owner-bootstrap-enrollment.json'):
|
|
424
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-required')
|
|
425
|
+
raw = _read_private(path)
|
|
426
|
+
if len(raw) > 2 * 1024 * 1024:
|
|
427
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
428
|
+
try:
|
|
429
|
+
record = json.loads(raw, object_pairs_hook=_no_duplicates)
|
|
430
|
+
except (json.JSONDecodeError, UnicodeDecodeError, LocalPostgresError):
|
|
431
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid') from None
|
|
432
|
+
if _canonical(record) != raw:
|
|
433
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-noncanonical')
|
|
434
|
+
profile = record.get('profile') if type(record) is dict else None
|
|
435
|
+
expected_keys = {'profile', 'enrollmentId', 'purpose', 'context',
|
|
436
|
+
'ownerConfiguration', 'nativeProfile'}
|
|
437
|
+
if profile in ('umf.local-owner-bootstrap-enrollment/0.2',
|
|
438
|
+
'umf.local-owner-bootstrap-enrollment/0.3',
|
|
439
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
440
|
+
expected_keys.add('generationAuthorityRoots')
|
|
441
|
+
if profile in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
442
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
443
|
+
expected_keys.add('supervisorJournalBirth')
|
|
444
|
+
if profile == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
445
|
+
expected_keys.add('targetCustodyJournalBirth')
|
|
446
|
+
if (type(record) is not dict or set(record) != expected_keys
|
|
447
|
+
or profile not in ('umf.local-owner-bootstrap-enrollment/0.1',
|
|
448
|
+
'umf.local-owner-bootstrap-enrollment/0.2',
|
|
449
|
+
'umf.local-owner-bootstrap-enrollment/0.3',
|
|
450
|
+
'umf.local-owner-bootstrap-enrollment/0.5')
|
|
451
|
+
or record['purpose'] not in ('production', 'native-acceptance')
|
|
452
|
+
or type(record['ownerConfiguration']) is not dict
|
|
453
|
+
or type(record['nativeProfile']) is not dict
|
|
454
|
+
or set(record['nativeProfile']) != _NATIVE_PROFILE_KEYS):
|
|
455
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
456
|
+
_uuid(record['enrollmentId'])
|
|
457
|
+
context = record['context']
|
|
458
|
+
if (type(context) is not dict or set(context) != {
|
|
459
|
+
'custodianId', 'supervisorId', 'providerId', 'installationId'}):
|
|
460
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
461
|
+
for name in ('custodianId', 'supervisorId', 'providerId'):
|
|
462
|
+
_uuid(context[name])
|
|
463
|
+
if type(context['installationId']) is not str or not context['installationId']:
|
|
464
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
465
|
+
if profile in ('umf.local-owner-bootstrap-enrollment/0.2',
|
|
466
|
+
'umf.local-owner-bootstrap-enrollment/0.3',
|
|
467
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
468
|
+
_validate_generation_roots(record['generationAuthorityRoots'])
|
|
469
|
+
if profile in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
470
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
471
|
+
config, _keys = validate_owner_configuration(record['ownerConfiguration'])
|
|
472
|
+
config_digest = hashlib.sha256(canonical_json(config).encode('utf-8')).hexdigest()
|
|
473
|
+
root_digest = hashlib.sha256(_canonical(record['generationAuthorityRoots'])).hexdigest()
|
|
474
|
+
from .supervisor_journal_codec import (
|
|
475
|
+
SupervisorJournalCodecError,
|
|
476
|
+
validate_birth,
|
|
477
|
+
)
|
|
478
|
+
try:
|
|
479
|
+
validate_birth(record['supervisorJournalBirth'], enrollment=record,
|
|
480
|
+
configuration_digest=config_digest,
|
|
481
|
+
generation_root_policy_digest=root_digest)
|
|
482
|
+
except SupervisorJournalCodecError:
|
|
483
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid') from None
|
|
484
|
+
if profile == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
485
|
+
from .supervisor_journal_codec import (
|
|
486
|
+
SupervisorJournalCodecError,
|
|
487
|
+
validate_target_custody_birth,
|
|
488
|
+
)
|
|
489
|
+
try:
|
|
490
|
+
validate_target_custody_birth(
|
|
491
|
+
record['targetCustodyJournalBirth'], enrollment=record)
|
|
492
|
+
except SupervisorJournalCodecError:
|
|
493
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid') from None
|
|
494
|
+
return record, raw
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _validate_generation_roots(value: object) -> None:
|
|
498
|
+
if (type(value) is not dict or set(value) != {
|
|
499
|
+
'profile', 'authorityId', 'policyRevision', 'keys'}
|
|
500
|
+
or value['profile'] != 'umf.generation-authority-root-policy/0.1'):
|
|
501
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
502
|
+
_uuid(value['authorityId'])
|
|
503
|
+
revision = value['policyRevision']
|
|
504
|
+
if (type(revision) is not str or not revision or '\x00' in revision
|
|
505
|
+
or len(revision.encode('utf-8')) > 128):
|
|
506
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
507
|
+
keys = value['keys']
|
|
508
|
+
if type(keys) is not list or not 1 <= len(keys) <= 32:
|
|
509
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
510
|
+
seen: set[str] = set()
|
|
511
|
+
for item in keys:
|
|
512
|
+
if (type(item) is not dict or set(item) != {
|
|
513
|
+
'keyId', 'publicKey', 'principalId', 'logicalAuthorityIds',
|
|
514
|
+
'configurationProfiles'}):
|
|
515
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
516
|
+
for name in ('keyId', 'principalId'):
|
|
517
|
+
text = item[name]
|
|
518
|
+
if (type(text) is not str or not text or '\x00' in text
|
|
519
|
+
or len(text.encode('utf-8')) > 128):
|
|
520
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
521
|
+
if item['keyId'] in seen:
|
|
522
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
523
|
+
seen.add(item['keyId'])
|
|
524
|
+
encoded = item['publicKey']
|
|
525
|
+
if type(encoded) is not str or not re.fullmatch(r'[A-Za-z0-9_-]{43}', encoded):
|
|
526
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
527
|
+
try:
|
|
528
|
+
key = base64.urlsafe_b64decode(encoded + '=')
|
|
529
|
+
except (ValueError, base64.binascii.Error):
|
|
530
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid') from None
|
|
531
|
+
if len(key) != 32 or base64.urlsafe_b64encode(key).decode('ascii').rstrip('=') != encoded:
|
|
532
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
533
|
+
ids = item['logicalAuthorityIds']
|
|
534
|
+
if type(ids) is not list or not 1 <= len(ids) <= 256:
|
|
535
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
536
|
+
normalized = [_uuid(identity) for identity in ids]
|
|
537
|
+
if len(set(normalized)) != len(normalized):
|
|
538
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
539
|
+
profiles = item['configurationProfiles']
|
|
540
|
+
if (type(profiles) is not list or not profiles
|
|
541
|
+
or len(set(profiles)) != len(profiles)
|
|
542
|
+
or any(profile != 'umf.configured-generation-enrollment-authority/0.1'
|
|
543
|
+
for profile in profiles)):
|
|
544
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-invalid')
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _verify_bootstrap_enrollment(path: Path, expected_digest: str) -> None:
|
|
548
|
+
_record, raw = _read_bootstrap_enrollment(path)
|
|
549
|
+
if hashlib.sha256(raw).hexdigest() != expected_digest:
|
|
550
|
+
raise LocalPostgresError('local-postgresql-bootstrap-enrollment-changed')
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _validate_bootstrap_context_journal(control_home: Path, record: dict[str, Any],
|
|
554
|
+
raw: bytes, configuration_digest: str) -> bytes:
|
|
555
|
+
path = control_home / 'owner-bootstrap-context.json'
|
|
556
|
+
try:
|
|
557
|
+
current = _read_private(path)
|
|
558
|
+
except LocalPostgresError:
|
|
559
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unavailable') from None
|
|
560
|
+
value = _parse_owner_setup(current, record, raw, configuration_digest, control_home)
|
|
561
|
+
if value['state'] != 'confirmed':
|
|
562
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unconfirmed')
|
|
563
|
+
if current != _canonical(value):
|
|
564
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
565
|
+
return current
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _parse_owner_setup(raw: bytes, enrollment: dict[str, Any], enrollment_raw: bytes,
|
|
569
|
+
configuration_digest: str, control_home: Path) -> dict[str, Any]:
|
|
570
|
+
try:
|
|
571
|
+
value = json.loads(raw, object_pairs_hook=_no_duplicates)
|
|
572
|
+
except (json.JSONDecodeError, UnicodeDecodeError, LocalPostgresError):
|
|
573
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-invalid') from None
|
|
574
|
+
keys = {'profile', 'enrollmentId', 'enrollmentRecordDigest',
|
|
575
|
+
'authorityConfigurationDigest', 'purpose', 'context', 'setupId',
|
|
576
|
+
'state', 'ownerLedger', 'generationAuthority'}
|
|
577
|
+
if (type(value) is not dict or set(value) != keys or _canonical(value) != raw
|
|
578
|
+
or value['profile'] != _OWNER_CONTEXT_PROFILE
|
|
579
|
+
or value['enrollmentId'] != enrollment['enrollmentId']
|
|
580
|
+
or value['enrollmentRecordDigest'] != hashlib.sha256(enrollment_raw).hexdigest()
|
|
581
|
+
or value['authorityConfigurationDigest'] != configuration_digest
|
|
582
|
+
or value['purpose'] != enrollment['purpose']
|
|
583
|
+
or value['context'] != enrollment['context']
|
|
584
|
+
or value['state'] not in ('pending', 'confirmed')):
|
|
585
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
586
|
+
_uuid(value['setupId'])
|
|
587
|
+
owner = value['ownerLedger']
|
|
588
|
+
if (type(owner) is not dict or set(owner) != {
|
|
589
|
+
'ledgerId', 'ledgerPath', 'lockPath', 'initialHeaderDigest'}):
|
|
590
|
+
raise LocalPostgresError('owner-approval-ledger-binding-invalid')
|
|
591
|
+
_uuid(owner['ledgerId'])
|
|
592
|
+
ledger_path = _canonical_private_path(owner['ledgerPath'])
|
|
593
|
+
lock_path = _canonical_private_path(owner['lockPath'])
|
|
594
|
+
if lock_path != ledger_path.with_name(ledger_path.name + '.lock'):
|
|
595
|
+
raise LocalPostgresError('owner-approval-ledger-binding-invalid')
|
|
596
|
+
configuration = enrollment['ownerConfiguration']
|
|
597
|
+
header_body = {'profile': _OWNER_LEDGER_PROFILE,
|
|
598
|
+
'authorityId': configuration['authorityId'],
|
|
599
|
+
'configurationDigest': configuration_digest}
|
|
600
|
+
header = {**header_body, 'digest': hashlib.sha256(_canonical(header_body)).hexdigest()}
|
|
601
|
+
expected_header = _canonical(header) + b'\n'
|
|
602
|
+
if owner['initialHeaderDigest'] != hashlib.sha256(expected_header).hexdigest():
|
|
603
|
+
raise LocalPostgresError('owner-approval-ledger-binding-invalid')
|
|
604
|
+
if any(type(owner[key]) is not str or not _HEX.fullmatch(owner[key])
|
|
605
|
+
for key in ('initialHeaderDigest',)):
|
|
606
|
+
raise LocalPostgresError('owner-approval-ledger-binding-invalid')
|
|
607
|
+
generation = value['generationAuthority']
|
|
608
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.1':
|
|
609
|
+
if generation is not None:
|
|
610
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
611
|
+
else:
|
|
612
|
+
if (type(generation) is not dict or set(generation) != {
|
|
613
|
+
'rootPolicyDigest', 'registryBirth'}):
|
|
614
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
615
|
+
roots = enrollment.get('generationAuthorityRoots')
|
|
616
|
+
roots_bytes = _canonical(roots)
|
|
617
|
+
if generation['rootPolicyDigest'] != hashlib.sha256(roots_bytes).hexdigest():
|
|
618
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
619
|
+
birth = generation['registryBirth']
|
|
620
|
+
if (type(birth) is not dict or set(birth) != {
|
|
621
|
+
'registryId', 'anchorDigest', 'registryPath', 'lockPath',
|
|
622
|
+
'initialRegistryDigest'}):
|
|
623
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
624
|
+
_uuid(birth['registryId'])
|
|
625
|
+
for field in ('anchorDigest', 'initialRegistryDigest'):
|
|
626
|
+
if type(birth[field]) is not str or not _HEX.fullmatch(birth[field]):
|
|
627
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
628
|
+
registry_path = control_home / 'generation-authority-registry.json'
|
|
629
|
+
registry_lock = registry_path.with_name(registry_path.name + '.lock')
|
|
630
|
+
anchor = {
|
|
631
|
+
'enrollmentRecordDigest': hashlib.sha256(enrollment_raw).hexdigest(),
|
|
632
|
+
'authorityConfigurationDigest': configuration_digest,
|
|
633
|
+
'generationRootPolicyDigest': generation['rootPolicyDigest'],
|
|
634
|
+
'purpose': enrollment['purpose'], 'context': enrollment['context'],
|
|
635
|
+
}
|
|
636
|
+
if (birth['registryPath'] != str(registry_path)
|
|
637
|
+
or birth['lockPath'] != str(registry_lock)
|
|
638
|
+
or birth['initialRegistryDigest'] != hashlib.sha256(
|
|
639
|
+
_initial_generation_registry(birth['registryId'],
|
|
640
|
+
birth['anchorDigest'])).hexdigest()
|
|
641
|
+
or birth['anchorDigest'] != hashlib.sha256(_canonical(anchor)).hexdigest()):
|
|
642
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-mismatch')
|
|
643
|
+
reserved = {
|
|
644
|
+
control_home / 'owner-bootstrap-enrollment.json',
|
|
645
|
+
control_home / 'owner-bootstrap-context.json',
|
|
646
|
+
control_home / _OWNER_SETUP_LOCK,
|
|
647
|
+
control_home / 'generation-authority-registry.json',
|
|
648
|
+
control_home / 'generation-authority-registry.json.lock',
|
|
649
|
+
}
|
|
650
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
651
|
+
reserved.update({control_home / 'target-custody.json',
|
|
652
|
+
control_home / 'target-custody.json.lock'})
|
|
653
|
+
if ledger_path in reserved or lock_path in reserved:
|
|
654
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
655
|
+
return value
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _canonical_private_path(value: object) -> Path:
|
|
659
|
+
if type(value) is not str or '\x00' in value or len(value.encode('utf-8')) > 4096:
|
|
660
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
661
|
+
path = Path(value)
|
|
662
|
+
if not path.is_absolute() or os.path.normpath(value) != value:
|
|
663
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
664
|
+
try:
|
|
665
|
+
if path.parent.resolve(strict=True) != path.parent or path.parent.is_symlink():
|
|
666
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
667
|
+
except OSError:
|
|
668
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid') from None
|
|
669
|
+
return path
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
@dataclass(frozen=True, slots=True)
|
|
673
|
+
class _OwnerSetupLockHandle:
|
|
674
|
+
"""Live descriptor identity for one held original setup lock."""
|
|
675
|
+
|
|
676
|
+
path: Path
|
|
677
|
+
fd: int
|
|
678
|
+
device: int
|
|
679
|
+
inode: int
|
|
680
|
+
process_id: int
|
|
681
|
+
thread_id: int
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
class _OriginalControlLease:
|
|
685
|
+
"""Opaque authority for the existing physical setup-file exclusion only."""
|
|
686
|
+
|
|
687
|
+
__slots__ = (
|
|
688
|
+
'_context',
|
|
689
|
+
'_control_home',
|
|
690
|
+
'_handle',
|
|
691
|
+
'_issuer',
|
|
692
|
+
'_operation_kind',
|
|
693
|
+
'_process_id',
|
|
694
|
+
'_profile',
|
|
695
|
+
'_setup_id',
|
|
696
|
+
'_supervisor',
|
|
697
|
+
'_thread_id',
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
def __init__(self, seal: object, issuer: object, context: object,
|
|
701
|
+
supervisor: object, handle: _OwnerSetupLockHandle,
|
|
702
|
+
operation_kind: str, setup_id: str):
|
|
703
|
+
if seal is not _CONTROL_LEASE_SEAL:
|
|
704
|
+
raise TypeError('original control leases are bootstrap-issued')
|
|
705
|
+
object.__setattr__(self, '_issuer', issuer)
|
|
706
|
+
object.__setattr__(self, '_context', context)
|
|
707
|
+
object.__setattr__(self, '_supervisor', supervisor)
|
|
708
|
+
object.__setattr__(self, '_profile', issuer._profile)
|
|
709
|
+
object.__setattr__(self, '_control_home', issuer._profile.control_home)
|
|
710
|
+
object.__setattr__(self, '_handle', handle)
|
|
711
|
+
object.__setattr__(self, '_operation_kind', operation_kind)
|
|
712
|
+
object.__setattr__(self, '_setup_id', setup_id)
|
|
713
|
+
object.__setattr__(self, '_process_id', os.getpid())
|
|
714
|
+
object.__setattr__(self, '_thread_id', threading.get_ident())
|
|
715
|
+
|
|
716
|
+
def __setattr__(self, _name: str, _value: object) -> None:
|
|
717
|
+
raise AttributeError('original control lease is immutable')
|
|
718
|
+
|
|
719
|
+
def __reduce_ex__(self, _protocol: int):
|
|
720
|
+
raise TypeError('original control lease cannot be serialized')
|
|
721
|
+
|
|
722
|
+
def __repr__(self) -> str:
|
|
723
|
+
return '<OriginalControlLease opaque>'
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def _verify_owner_setup_lock_handle(handle: object) -> _OwnerSetupLockHandle:
|
|
727
|
+
if type(handle) is not _OwnerSetupLockHandle:
|
|
728
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-unverified')
|
|
729
|
+
if (handle.process_id != os.getpid()
|
|
730
|
+
or handle.thread_id != threading.get_ident()):
|
|
731
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-unverified')
|
|
732
|
+
try:
|
|
733
|
+
descriptor_stat = os.fstat(handle.fd)
|
|
734
|
+
path_stat = os.lstat(handle.path)
|
|
735
|
+
except OSError:
|
|
736
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-unavailable') from None
|
|
737
|
+
if (not stat.S_ISREG(descriptor_stat.st_mode)
|
|
738
|
+
or not stat.S_ISREG(path_stat.st_mode)
|
|
739
|
+
or stat.S_ISLNK(path_stat.st_mode)
|
|
740
|
+
or descriptor_stat.st_uid != os.geteuid()
|
|
741
|
+
or path_stat.st_uid != os.geteuid()
|
|
742
|
+
or descriptor_stat.st_nlink != 1 or path_stat.st_nlink != 1
|
|
743
|
+
or stat.S_IMODE(descriptor_stat.st_mode) != 0o600
|
|
744
|
+
or stat.S_IMODE(path_stat.st_mode) != 0o600
|
|
745
|
+
or descriptor_stat.st_dev != handle.device
|
|
746
|
+
or descriptor_stat.st_ino != handle.inode
|
|
747
|
+
or path_stat.st_dev != handle.device or path_stat.st_ino != handle.inode
|
|
748
|
+
or descriptor_stat.st_size != 0 or path_stat.st_size != 0):
|
|
749
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-invalid')
|
|
750
|
+
return handle
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
@contextmanager
|
|
754
|
+
def _owner_setup_lease(control_home: Path, *, timeout_ms: int | None = None):
|
|
755
|
+
"""Hold the original setup lock; bounded callers share the setup mutex.
|
|
756
|
+
|
|
757
|
+
Legacy setup settlement keeps its blocking behavior. Native lease callers
|
|
758
|
+
pass one exact bounded timeout, shared by local-mutex and flock acquisition.
|
|
759
|
+
"""
|
|
760
|
+
if timeout_ms is not None and (type(timeout_ms) is not int
|
|
761
|
+
or not 1 <= timeout_ms <= 30_000):
|
|
762
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-timeout-invalid')
|
|
763
|
+
acquisition_pid = os.getpid()
|
|
764
|
+
try:
|
|
765
|
+
_private_directory(control_home)
|
|
766
|
+
except LocalPostgresError:
|
|
767
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-invalid') from None
|
|
768
|
+
path = control_home / _OWNER_SETUP_LOCK
|
|
769
|
+
deadline = (None if timeout_ms is None
|
|
770
|
+
else time.monotonic() + timeout_ms / 1000)
|
|
771
|
+
with _OWNER_SETUP_LOCKS_GUARD:
|
|
772
|
+
local = _OWNER_SETUP_LOCKS.setdefault(str(path), threading.Lock())
|
|
773
|
+
if deadline is None:
|
|
774
|
+
local_acquired = local.acquire()
|
|
775
|
+
else:
|
|
776
|
+
local_acquired = local.acquire(timeout=max(0.0, deadline - time.monotonic()))
|
|
777
|
+
if not local_acquired:
|
|
778
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-timeout')
|
|
779
|
+
try:
|
|
780
|
+
fd = -1
|
|
781
|
+
locked = False
|
|
782
|
+
try:
|
|
783
|
+
flags = os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
|
|
784
|
+
flags |= getattr(os, 'O_CLOEXEC', 0) | getattr(os, 'O_NONBLOCK', 0)
|
|
785
|
+
fd = os.open(path, flags)
|
|
786
|
+
st = os.fstat(fd)
|
|
787
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
788
|
+
or st.st_nlink != 1 or stat.S_IMODE(st.st_mode) != 0o600
|
|
789
|
+
or st.st_size != 0):
|
|
790
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-invalid')
|
|
791
|
+
path_stat = os.lstat(path)
|
|
792
|
+
if (not stat.S_ISREG(path_stat.st_mode) or stat.S_ISLNK(path_stat.st_mode)
|
|
793
|
+
or (path_stat.st_dev, path_stat.st_ino) != (st.st_dev, st.st_ino)):
|
|
794
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-invalid')
|
|
795
|
+
while True:
|
|
796
|
+
try:
|
|
797
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
798
|
+
break
|
|
799
|
+
except BlockingIOError:
|
|
800
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
801
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-timeout') from None
|
|
802
|
+
time.sleep(0.005 if deadline is None else
|
|
803
|
+
min(0.005, max(0.0, deadline - time.monotonic())))
|
|
804
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
805
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-timeout')
|
|
806
|
+
locked = True
|
|
807
|
+
handle = _OwnerSetupLockHandle(
|
|
808
|
+
path, fd, st.st_dev, st.st_ino, os.getpid(), threading.get_ident())
|
|
809
|
+
_verify_owner_setup_lock_handle(handle)
|
|
810
|
+
except OSError:
|
|
811
|
+
if fd >= 0:
|
|
812
|
+
try:
|
|
813
|
+
os.close(fd)
|
|
814
|
+
finally:
|
|
815
|
+
fd = -1
|
|
816
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-unavailable') from None
|
|
817
|
+
except BaseException:
|
|
818
|
+
if fd >= 0:
|
|
819
|
+
try:
|
|
820
|
+
os.close(fd)
|
|
821
|
+
finally:
|
|
822
|
+
fd = -1
|
|
823
|
+
raise
|
|
824
|
+
try:
|
|
825
|
+
yield handle
|
|
826
|
+
except BaseException:
|
|
827
|
+
if fd >= 0:
|
|
828
|
+
try:
|
|
829
|
+
if locked and os.getpid() == acquisition_pid:
|
|
830
|
+
try:
|
|
831
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
832
|
+
except OSError:
|
|
833
|
+
pass
|
|
834
|
+
finally:
|
|
835
|
+
os.close(fd)
|
|
836
|
+
fd = -1
|
|
837
|
+
raise
|
|
838
|
+
else:
|
|
839
|
+
if fd >= 0:
|
|
840
|
+
try:
|
|
841
|
+
if locked and os.getpid() == acquisition_pid:
|
|
842
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
843
|
+
finally:
|
|
844
|
+
os.close(fd)
|
|
845
|
+
fd = -1
|
|
846
|
+
finally:
|
|
847
|
+
if fd >= 0:
|
|
848
|
+
os.close(fd)
|
|
849
|
+
finally:
|
|
850
|
+
local.release()
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
@contextmanager
|
|
854
|
+
def _owner_resource_lease(path: Path, error_code: str):
|
|
855
|
+
acquisition_pid = os.getpid()
|
|
856
|
+
fd = -1
|
|
857
|
+
locked = False
|
|
858
|
+
try:
|
|
859
|
+
fd = os.open(path, os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0))
|
|
860
|
+
st = os.fstat(fd)
|
|
861
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
862
|
+
or st.st_nlink != 1 or stat.S_IMODE(st.st_mode) != 0o600):
|
|
863
|
+
raise LocalPostgresError(error_code)
|
|
864
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
865
|
+
locked = True
|
|
866
|
+
except OSError:
|
|
867
|
+
if fd >= 0:
|
|
868
|
+
try:
|
|
869
|
+
os.close(fd)
|
|
870
|
+
finally:
|
|
871
|
+
fd = -1
|
|
872
|
+
raise LocalPostgresError(error_code) from None
|
|
873
|
+
except BaseException:
|
|
874
|
+
if fd >= 0:
|
|
875
|
+
try:
|
|
876
|
+
os.close(fd)
|
|
877
|
+
finally:
|
|
878
|
+
fd = -1
|
|
879
|
+
raise
|
|
880
|
+
try:
|
|
881
|
+
yield
|
|
882
|
+
except BaseException:
|
|
883
|
+
if fd >= 0:
|
|
884
|
+
try:
|
|
885
|
+
if locked and os.getpid() == acquisition_pid:
|
|
886
|
+
try:
|
|
887
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
888
|
+
except OSError:
|
|
889
|
+
pass
|
|
890
|
+
finally:
|
|
891
|
+
os.close(fd)
|
|
892
|
+
fd = -1
|
|
893
|
+
raise
|
|
894
|
+
else:
|
|
895
|
+
if fd >= 0:
|
|
896
|
+
try:
|
|
897
|
+
if locked and os.getpid() == acquisition_pid:
|
|
898
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
899
|
+
finally:
|
|
900
|
+
os.close(fd)
|
|
901
|
+
fd = -1
|
|
902
|
+
finally:
|
|
903
|
+
if fd >= 0:
|
|
904
|
+
os.close(fd)
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def _atomic_replace_private(path: Path, data: bytes) -> None:
|
|
908
|
+
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
|
|
909
|
+
fd = -1
|
|
910
|
+
try:
|
|
911
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
912
|
+
| getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
913
|
+
os.fchmod(fd, 0o600)
|
|
914
|
+
view = memoryview(data)
|
|
915
|
+
while view:
|
|
916
|
+
written = os.write(fd, view)
|
|
917
|
+
if written <= 0:
|
|
918
|
+
raise OSError('short setup-state write')
|
|
919
|
+
view = view[written:]
|
|
920
|
+
os.fsync(fd)
|
|
921
|
+
os.close(fd); fd = -1
|
|
922
|
+
os.replace(temporary, path)
|
|
923
|
+
_fsync_directory(path.parent)
|
|
924
|
+
except OSError:
|
|
925
|
+
raise LocalPostgresError('owner-bootstrap-context-confirmation-failed') from None
|
|
926
|
+
finally:
|
|
927
|
+
if fd >= 0:
|
|
928
|
+
os.close(fd)
|
|
929
|
+
try:
|
|
930
|
+
temporary.unlink(missing_ok=True)
|
|
931
|
+
except OSError:
|
|
932
|
+
pass
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _owner_header_bytes(enrollment: dict[str, Any], configuration_digest: str) -> bytes:
|
|
936
|
+
body = {'profile': _OWNER_LEDGER_PROFILE,
|
|
937
|
+
'authorityId': enrollment['ownerConfiguration']['authorityId'],
|
|
938
|
+
'configurationDigest': configuration_digest}
|
|
939
|
+
return _canonical({**body, 'digest': hashlib.sha256(_canonical(body)).hexdigest()}) + b'\n'
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def _initial_generation_registry(registry_id: str, anchor_digest: str) -> bytes:
|
|
943
|
+
from .generation_authority_bootstrap import initial_registry_bytes
|
|
944
|
+
return initial_registry_bytes(registry_id, anchor_digest)
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _create_initial_registry(path: Path, registry_id: str, anchor_digest: str) -> None:
|
|
948
|
+
expected = _initial_generation_registry(registry_id, anchor_digest)
|
|
949
|
+
try:
|
|
950
|
+
current = _read_private(path)
|
|
951
|
+
except LocalPostgresError as exc:
|
|
952
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
953
|
+
raise
|
|
954
|
+
_write_private(path, expected)
|
|
955
|
+
return
|
|
956
|
+
if current != expected:
|
|
957
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def _check_private_parent(path: Path) -> None:
|
|
961
|
+
try:
|
|
962
|
+
st = path.parent.lstat()
|
|
963
|
+
except OSError:
|
|
964
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid') from None
|
|
965
|
+
if (not stat.S_ISDIR(st.st_mode) or stat.S_ISLNK(st.st_mode)
|
|
966
|
+
or st.st_uid != os.geteuid() or st.st_mode & 0o077
|
|
967
|
+
or path.parent.resolve(strict=True) != path.parent):
|
|
968
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
def _create_empty_private(path: Path) -> None:
|
|
972
|
+
fd = -1
|
|
973
|
+
try:
|
|
974
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
975
|
+
| getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
976
|
+
os.fchmod(fd, 0o600)
|
|
977
|
+
os.fsync(fd)
|
|
978
|
+
os.close(fd); fd = -1
|
|
979
|
+
_fsync_directory(path.parent)
|
|
980
|
+
except FileExistsError:
|
|
981
|
+
return
|
|
982
|
+
except OSError:
|
|
983
|
+
raise LocalPostgresError('owner-bootstrap-resource-create-failed') from None
|
|
984
|
+
finally:
|
|
985
|
+
if fd >= 0:
|
|
986
|
+
os.close(fd)
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def _ensure_pending_owner_resources(setup: dict[str, Any], enrollment: dict[str, Any],
|
|
990
|
+
configuration_digest: str, control_home: Path) -> None:
|
|
991
|
+
owner = setup['ownerLedger']
|
|
992
|
+
ledger = Path(owner['ledgerPath'])
|
|
993
|
+
lock = Path(owner['lockPath'])
|
|
994
|
+
_check_private_parent(ledger)
|
|
995
|
+
forbidden = {
|
|
996
|
+
control_home / 'owner-bootstrap-enrollment.json',
|
|
997
|
+
control_home / 'owner-bootstrap-context.json',
|
|
998
|
+
control_home / _OWNER_SETUP_LOCK,
|
|
999
|
+
control_home / 'generation-authority-registry.json',
|
|
1000
|
+
control_home / 'generation-authority-registry.json.lock',
|
|
1001
|
+
}
|
|
1002
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
1003
|
+
forbidden.update({control_home / 'target-custody.json',
|
|
1004
|
+
control_home / 'target-custody.json.lock'})
|
|
1005
|
+
if ledger in forbidden or lock in forbidden or ledger == lock:
|
|
1006
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
1007
|
+
expected = _owner_header_bytes(enrollment, configuration_digest)
|
|
1008
|
+
# The setup lease excludes all ordinary sessions. A pending initial header
|
|
1009
|
+
# is the only prefix that may be completed; it cannot contain a request.
|
|
1010
|
+
_create_empty_private(lock)
|
|
1011
|
+
with _owner_resource_lease(lock, 'owner-approval-ledger-lock-invalid'):
|
|
1012
|
+
try:
|
|
1013
|
+
lock_bytes = _read_private(lock)
|
|
1014
|
+
if lock_bytes != b'':
|
|
1015
|
+
raise LocalPostgresError('owner-approval-ledger-lock-invalid')
|
|
1016
|
+
except LocalPostgresError:
|
|
1017
|
+
raise LocalPostgresError('owner-approval-ledger-lock-invalid') from None
|
|
1018
|
+
try:
|
|
1019
|
+
current = _read_private(ledger)
|
|
1020
|
+
except LocalPostgresError as exc:
|
|
1021
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
1022
|
+
raise
|
|
1023
|
+
_write_private(ledger, expected)
|
|
1024
|
+
current = expected
|
|
1025
|
+
if not expected.startswith(current):
|
|
1026
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete')
|
|
1027
|
+
if current != expected:
|
|
1028
|
+
fd = -1
|
|
1029
|
+
try:
|
|
1030
|
+
fd = os.open(ledger, os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0))
|
|
1031
|
+
st = os.fstat(fd)
|
|
1032
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
1033
|
+
or st.st_nlink != 1 or stat.S_IMODE(st.st_mode) != 0o600):
|
|
1034
|
+
raise OSError('unsafe pending owner ledger')
|
|
1035
|
+
remaining = memoryview(expected[len(current):])
|
|
1036
|
+
while remaining:
|
|
1037
|
+
written = os.write(fd, remaining)
|
|
1038
|
+
if written <= 0:
|
|
1039
|
+
raise OSError('short owner ledger prefix write')
|
|
1040
|
+
remaining = remaining[written:]
|
|
1041
|
+
os.fsync(fd)
|
|
1042
|
+
except OSError:
|
|
1043
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete') from None
|
|
1044
|
+
finally:
|
|
1045
|
+
if fd >= 0:
|
|
1046
|
+
os.close(fd)
|
|
1047
|
+
_fsync_directory(ledger.parent)
|
|
1048
|
+
if hashlib.sha256(expected).hexdigest() != owner['initialHeaderDigest']:
|
|
1049
|
+
raise LocalPostgresError('owner-approval-ledger-binding-invalid')
|
|
1050
|
+
generation = setup['generationAuthority']
|
|
1051
|
+
if generation is not None:
|
|
1052
|
+
birth = generation['registryBirth']
|
|
1053
|
+
registry = Path(birth['registryPath']); registry_lock = Path(birth['lockPath'])
|
|
1054
|
+
_create_empty_private(registry_lock)
|
|
1055
|
+
with _owner_resource_lease(registry_lock,
|
|
1056
|
+
'generation-authority-registry-birth-incomplete'):
|
|
1057
|
+
_create_initial_registry(registry, birth['registryId'], birth['anchorDigest'])
|
|
1058
|
+
if (_read_private(registry_lock) != b''
|
|
1059
|
+
or hashlib.sha256(_initial_generation_registry(
|
|
1060
|
+
birth['registryId'], birth['anchorDigest'])).hexdigest()
|
|
1061
|
+
!= birth['initialRegistryDigest']
|
|
1062
|
+
or _read_private(registry) != _initial_generation_registry(
|
|
1063
|
+
birth['registryId'], birth['anchorDigest'])):
|
|
1064
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1065
|
+
if enrollment['profile'] in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
1066
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
1067
|
+
_ensure_pending_supervisor_journal(enrollment)
|
|
1068
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
1069
|
+
_ensure_pending_target_custody_journal(enrollment)
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _ensure_pending_supervisor_journal(enrollment: dict[str, Any]) -> None:
|
|
1073
|
+
"""Complete only the original fixed zero-journal birth while setup is pending."""
|
|
1074
|
+
from .supervisor_journal_codec import (
|
|
1075
|
+
SupervisorJournalCodecError,
|
|
1076
|
+
initial_record,
|
|
1077
|
+
validate_birth,
|
|
1078
|
+
)
|
|
1079
|
+
|
|
1080
|
+
configuration, _keys = validate_owner_configuration(enrollment['ownerConfiguration'])
|
|
1081
|
+
configuration_digest = hashlib.sha256(
|
|
1082
|
+
canonical_json(configuration).encode('utf-8')).hexdigest()
|
|
1083
|
+
roots = enrollment['generationAuthorityRoots']
|
|
1084
|
+
root_digest = hashlib.sha256(_canonical(roots)).hexdigest()
|
|
1085
|
+
try:
|
|
1086
|
+
birth = validate_birth(
|
|
1087
|
+
enrollment['supervisorJournalBirth'], enrollment=enrollment,
|
|
1088
|
+
configuration_digest=configuration_digest,
|
|
1089
|
+
generation_root_policy_digest=root_digest)
|
|
1090
|
+
record = initial_record(
|
|
1091
|
+
supervisor_id=birth['supervisorId'], journal_id=birth['journalId'],
|
|
1092
|
+
definition_digest=birth['definitionDigest'], anchor_digest=birth['anchorDigest'])
|
|
1093
|
+
except SupervisorJournalCodecError:
|
|
1094
|
+
raise LocalPostgresError('supervisor-journal-birth-invalid') from None
|
|
1095
|
+
if hashlib.sha256(record).hexdigest() != birth['initialHeaderDigest']:
|
|
1096
|
+
raise LocalPostgresError('supervisor-journal-birth-invalid')
|
|
1097
|
+
path = Path(birth['path'])
|
|
1098
|
+
lock = Path(birth['lockPath'])
|
|
1099
|
+
if lock != path.with_name(path.name + '.lock'):
|
|
1100
|
+
raise LocalPostgresError('supervisor-journal-path-invalid')
|
|
1101
|
+
_check_private_parent(path)
|
|
1102
|
+
_create_empty_private(lock)
|
|
1103
|
+
with _owner_resource_lease(lock, 'supervisor-journal-lock-invalid'):
|
|
1104
|
+
try:
|
|
1105
|
+
if _read_private(lock) != b'':
|
|
1106
|
+
raise LocalPostgresError('supervisor-journal-lock-invalid')
|
|
1107
|
+
except LocalPostgresError:
|
|
1108
|
+
raise LocalPostgresError('supervisor-journal-lock-invalid') from None
|
|
1109
|
+
try:
|
|
1110
|
+
current = _read_private(path)
|
|
1111
|
+
except LocalPostgresError as exc:
|
|
1112
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
1113
|
+
raise
|
|
1114
|
+
_write_private(path, record)
|
|
1115
|
+
current = record
|
|
1116
|
+
if not record.startswith(current):
|
|
1117
|
+
raise LocalPostgresError('supervisor-journal-birth-incomplete')
|
|
1118
|
+
if current != record:
|
|
1119
|
+
fd = -1
|
|
1120
|
+
try:
|
|
1121
|
+
fd = os.open(path, os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0))
|
|
1122
|
+
st = os.fstat(fd)
|
|
1123
|
+
if (not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid()
|
|
1124
|
+
or st.st_nlink != 1 or stat.S_IMODE(st.st_mode) != 0o600):
|
|
1125
|
+
raise OSError('unsafe pending supervisor journal')
|
|
1126
|
+
remaining = memoryview(record[len(current):])
|
|
1127
|
+
while remaining:
|
|
1128
|
+
written = os.write(fd, remaining)
|
|
1129
|
+
if written <= 0:
|
|
1130
|
+
raise OSError('short pending supervisor journal')
|
|
1131
|
+
remaining = remaining[written:]
|
|
1132
|
+
os.fsync(fd)
|
|
1133
|
+
except OSError:
|
|
1134
|
+
raise LocalPostgresError('supervisor-journal-birth-incomplete') from None
|
|
1135
|
+
finally:
|
|
1136
|
+
if fd >= 0:
|
|
1137
|
+
os.close(fd)
|
|
1138
|
+
_fsync_directory(path.parent)
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def _target_custody_journal_initial(enrollment: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
|
|
1142
|
+
from .supervisor_journal_codec import (
|
|
1143
|
+
TARGET_CUSTODY_JOURNAL_PROFILE_02,
|
|
1144
|
+
SupervisorJournalCodecError,
|
|
1145
|
+
validate_target_custody_birth,
|
|
1146
|
+
)
|
|
1147
|
+
try:
|
|
1148
|
+
birth = validate_target_custody_birth(
|
|
1149
|
+
enrollment['targetCustodyJournalBirth'], enrollment=enrollment)
|
|
1150
|
+
header = {'profile': TARGET_CUSTODY_JOURNAL_PROFILE_02,
|
|
1151
|
+
'custodianId': birth['custodianId'], 'sequence': 0,
|
|
1152
|
+
'headDigest': '0' * 64, 'events': []}
|
|
1153
|
+
raw = _canonical(header)
|
|
1154
|
+
if (hashlib.sha256(raw).hexdigest() != birth['initialHeaderDigest']
|
|
1155
|
+
or hashlib.sha256(_canonical(birth['definition'])).hexdigest()
|
|
1156
|
+
!= birth['definitionDigest']):
|
|
1157
|
+
raise SupervisorJournalCodecError('target-custody-journal-birth-invalid')
|
|
1158
|
+
return birth, raw
|
|
1159
|
+
except (KeyError, TypeError, SupervisorJournalCodecError):
|
|
1160
|
+
raise LocalPostgresError('target-custody-journal-birth-invalid') from None
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def _ensure_pending_target_custody_journal(enrollment: dict[str, Any]) -> None:
|
|
1164
|
+
"""Create only the exact enrolled 0.2 genesis and empty lock while pending."""
|
|
1165
|
+
birth, expected = _target_custody_journal_initial(enrollment)
|
|
1166
|
+
path, lock = Path(birth['path']), Path(birth['lockPath'])
|
|
1167
|
+
_check_private_parent(path)
|
|
1168
|
+
_create_empty_private(lock)
|
|
1169
|
+
with _owner_resource_lease(lock, 'target-custody-journal-lock-invalid'):
|
|
1170
|
+
try:
|
|
1171
|
+
lock_raw = _read_private(lock)
|
|
1172
|
+
except LocalPostgresError:
|
|
1173
|
+
raise LocalPostgresError('target-custody-journal-lock-invalid') from None
|
|
1174
|
+
if lock_raw != b'':
|
|
1175
|
+
raise LocalPostgresError('target-custody-journal-lock-invalid')
|
|
1176
|
+
try:
|
|
1177
|
+
current = _read_private(path)
|
|
1178
|
+
except LocalPostgresError as exc:
|
|
1179
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
1180
|
+
raise
|
|
1181
|
+
_write_private(path, expected)
|
|
1182
|
+
current = expected
|
|
1183
|
+
if current != expected:
|
|
1184
|
+
raise LocalPostgresError('target-custody-journal-birth-incomplete')
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
def _verify_target_custody_journal_resource(enrollment: dict[str, Any]) -> None:
|
|
1188
|
+
"""Verify the original 0.2 chain against its immutable enrollment birth."""
|
|
1189
|
+
birth, _expected = _target_custody_journal_initial(enrollment)
|
|
1190
|
+
path, lock = Path(birth['path']), Path(birth['lockPath'])
|
|
1191
|
+
_check_private_parent(path)
|
|
1192
|
+
try:
|
|
1193
|
+
raw, lock_raw = _read_private(path), _read_private(lock)
|
|
1194
|
+
except LocalPostgresError:
|
|
1195
|
+
raise LocalPostgresError('target-custody-journal-birth-incomplete') from None
|
|
1196
|
+
if lock_raw != b'':
|
|
1197
|
+
raise LocalPostgresError('target-custody-journal-birth-incomplete')
|
|
1198
|
+
from .target_custody_codec import (
|
|
1199
|
+
CustodyJournalError,
|
|
1200
|
+
validate_original_target_custody_record,
|
|
1201
|
+
)
|
|
1202
|
+
try:
|
|
1203
|
+
validate_original_target_custody_record(raw, birth)
|
|
1204
|
+
except CustodyJournalError:
|
|
1205
|
+
raise LocalPostgresError('target-custody-journal-replay-invalid') from None
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def _settle_original_owner_setup(profile: LocalPostgresProfile,
|
|
1209
|
+
requested_ledger_path: object) -> bytes:
|
|
1210
|
+
"""Settle only the preinstalled original0.3 owner setup before issuing objects."""
|
|
1211
|
+
if type(profile) is not LocalPostgresProfile:
|
|
1212
|
+
raise LocalPostgresError('local-postgresql-profile-invalid')
|
|
1213
|
+
record_path = profile.control_home / 'owner-bootstrap-enrollment.json'
|
|
1214
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(record_path)
|
|
1215
|
+
if (enrollment['nativeProfile'] != _profile_to_enrollment(profile)
|
|
1216
|
+
or enrollment['purpose'] != profile.purpose
|
|
1217
|
+
or enrollment['context']['custodianId'] != profile.custodian_id
|
|
1218
|
+
or enrollment['context']['supervisorId'] != profile.supervisor_id
|
|
1219
|
+
or enrollment['context']['providerId'] != profile.provider_id
|
|
1220
|
+
or enrollment['context']['installationId'] != profile.installation_id):
|
|
1221
|
+
raise LocalPostgresError('local-postgresql-owner-context-mismatch')
|
|
1222
|
+
try:
|
|
1223
|
+
config, _keys = validate_owner_configuration(enrollment['ownerConfiguration'])
|
|
1224
|
+
except OwnerWireError:
|
|
1225
|
+
raise LocalPostgresError('local-postgresql-owner-configuration-invalid') from None
|
|
1226
|
+
config_digest = hashlib.sha256(canonical_json(config).encode('utf-8')).hexdigest()
|
|
1227
|
+
context_path = profile.control_home / 'owner-bootstrap-context.json'
|
|
1228
|
+
try:
|
|
1229
|
+
pending_raw = _read_private(context_path)
|
|
1230
|
+
except LocalPostgresError:
|
|
1231
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unavailable') from None
|
|
1232
|
+
setup = _parse_owner_setup(pending_raw, enrollment, enrollment_raw,
|
|
1233
|
+
config_digest, profile.control_home)
|
|
1234
|
+
path = _canonical_private_path(setup['ownerLedger']['ledgerPath'])
|
|
1235
|
+
if (type(requested_ledger_path) is not str and not isinstance(requested_ledger_path, Path)
|
|
1236
|
+
or Path(requested_ledger_path) != path):
|
|
1237
|
+
raise LocalPostgresError('owner-approval-ledger-path-mismatch')
|
|
1238
|
+
with _owner_setup_lease(profile.control_home):
|
|
1239
|
+
# Re-read the immutable primary after acquiring the setup lease.
|
|
1240
|
+
current_raw = _read_private(context_path)
|
|
1241
|
+
current = _parse_owner_setup(current_raw, enrollment, enrollment_raw,
|
|
1242
|
+
config_digest, profile.control_home)
|
|
1243
|
+
if ({**current, 'state': ''} != {**setup, 'state': ''}
|
|
1244
|
+
or (setup['state'] != current['state']
|
|
1245
|
+
and (setup['state'], current['state']) != ('pending', 'confirmed'))):
|
|
1246
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-changed')
|
|
1247
|
+
_check_private_parent(path)
|
|
1248
|
+
if current['state'] == 'pending':
|
|
1249
|
+
_ensure_pending_owner_resources(current, enrollment, config_digest,
|
|
1250
|
+
profile.control_home)
|
|
1251
|
+
confirmed = dict(current); confirmed['state'] = 'confirmed'
|
|
1252
|
+
_atomic_replace_private(context_path, _canonical(confirmed))
|
|
1253
|
+
current = confirmed
|
|
1254
|
+
else:
|
|
1255
|
+
_verify_primary_owner_resources(current, enrollment, config_digest)
|
|
1256
|
+
reread = _read_private(context_path)
|
|
1257
|
+
verified = _parse_owner_setup(reread, enrollment, enrollment_raw,
|
|
1258
|
+
config_digest, profile.control_home)
|
|
1259
|
+
if verified != current or verified['state'] != 'confirmed':
|
|
1260
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unverified')
|
|
1261
|
+
_verify_primary_owner_resources(verified, enrollment, config_digest)
|
|
1262
|
+
return reread
|
|
1263
|
+
|
|
1264
|
+
|
|
1265
|
+
def _verify_primary_owner_resources(setup: dict[str, Any], enrollment: dict[str, Any],
|
|
1266
|
+
configuration_digest: str) -> None:
|
|
1267
|
+
owner = setup['ownerLedger']; ledger = Path(owner['ledgerPath'])
|
|
1268
|
+
lock = Path(owner['lockPath']); _check_private_parent(ledger)
|
|
1269
|
+
try:
|
|
1270
|
+
ledger_bytes = _read_private(ledger); lock_bytes = _read_private(lock)
|
|
1271
|
+
except LocalPostgresError:
|
|
1272
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete') from None
|
|
1273
|
+
expected = _owner_header_bytes(enrollment, configuration_digest)
|
|
1274
|
+
if not ledger_bytes.startswith(expected) or lock_bytes != b'':
|
|
1275
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete')
|
|
1276
|
+
if setup['generationAuthority'] is not None:
|
|
1277
|
+
birth = setup['generationAuthority']['registryBirth']
|
|
1278
|
+
try:
|
|
1279
|
+
raw = _read_private(Path(birth['registryPath']))
|
|
1280
|
+
_read_private(Path(birth['lockPath']))
|
|
1281
|
+
except LocalPostgresError:
|
|
1282
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete') from None
|
|
1283
|
+
expected_initial = _initial_generation_registry(birth['registryId'], birth['anchorDigest'])
|
|
1284
|
+
if hashlib.sha256(expected_initial).hexdigest() != birth['initialRegistryDigest']:
|
|
1285
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1286
|
+
try:
|
|
1287
|
+
from .generation_authority_bootstrap import (
|
|
1288
|
+
GenerationAuthorityBootstrapError,
|
|
1289
|
+
validate_registry,
|
|
1290
|
+
)
|
|
1291
|
+
registry = validate_registry(
|
|
1292
|
+
raw, registry_id=birth['registryId'],
|
|
1293
|
+
anchor_digest=birth['anchorDigest'],
|
|
1294
|
+
root_policy=enrollment['generationAuthorityRoots'],
|
|
1295
|
+
purpose=enrollment['purpose'],
|
|
1296
|
+
bootstrap_enrollment_id=enrollment['enrollmentId'])
|
|
1297
|
+
_verify_generation_registry_physical_binding(
|
|
1298
|
+
registry, setup, enrollment, configuration_digest,
|
|
1299
|
+
Path(birth['registryPath']).parent / 'owner-bootstrap-context.json')
|
|
1300
|
+
except GenerationAuthorityBootstrapError:
|
|
1301
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete') from None
|
|
1302
|
+
if enrollment['profile'] in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
1303
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
1304
|
+
_verify_supervisor_journal_resource(setup, enrollment, configuration_digest)
|
|
1305
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
1306
|
+
_verify_target_custody_journal_resource(enrollment)
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def _verify_supervisor_journal_resource(setup: dict[str, Any], enrollment: dict[str, Any],
|
|
1310
|
+
configuration_digest: str) -> None:
|
|
1311
|
+
from .supervisor_journal_codec import (
|
|
1312
|
+
SupervisorJournalCodecError,
|
|
1313
|
+
validate_birth,
|
|
1314
|
+
validate_record,
|
|
1315
|
+
)
|
|
1316
|
+
|
|
1317
|
+
try:
|
|
1318
|
+
birth = validate_birth(
|
|
1319
|
+
enrollment['supervisorJournalBirth'], enrollment=enrollment,
|
|
1320
|
+
configuration_digest=configuration_digest,
|
|
1321
|
+
generation_root_policy_digest=setup['generationAuthority']['rootPolicyDigest'])
|
|
1322
|
+
path = Path(birth['path']); lock = Path(birth['lockPath'])
|
|
1323
|
+
raw = _read_private(path); lock_raw = _read_private(lock)
|
|
1324
|
+
root_birth = setup['generationAuthority']['registryBirth']
|
|
1325
|
+
root_context = {
|
|
1326
|
+
'registryId': root_birth['registryId'],
|
|
1327
|
+
'anchorDigest': root_birth['anchorDigest'],
|
|
1328
|
+
'rootPolicy': enrollment['generationAuthorityRoots'],
|
|
1329
|
+
'purpose': enrollment['purpose'],
|
|
1330
|
+
'bootstrapEnrollmentId': enrollment['enrollmentId'],
|
|
1331
|
+
'initialRegistryDigest': root_birth['initialRegistryDigest'],
|
|
1332
|
+
}
|
|
1333
|
+
validate_record(
|
|
1334
|
+
raw, birth=birth,
|
|
1335
|
+
owner_bootstrap_context_digest=hashlib.sha256(_canonical(setup)).hexdigest(),
|
|
1336
|
+
generation_root_policy_digest=setup['generationAuthority']['rootPolicyDigest'],
|
|
1337
|
+
root_replay_context=root_context)
|
|
1338
|
+
if lock_raw != b'':
|
|
1339
|
+
raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
|
|
1340
|
+
except (KeyError, TypeError, SupervisorJournalCodecError):
|
|
1341
|
+
raise LocalPostgresError('supervisor-journal-birth-incomplete') from None
|
|
1342
|
+
except LocalPostgresError:
|
|
1343
|
+
raise LocalPostgresError('supervisor-journal-birth-incomplete') from None
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
def _verify_generation_registry_physical_binding(
|
|
1347
|
+
registry: dict[str, Any], setup: dict[str, Any], enrollment: dict[str, Any],
|
|
1348
|
+
configuration_digest: str, physical_path: Path) -> None:
|
|
1349
|
+
"""Bind every signed root request to the exact original .3 context bytes."""
|
|
1350
|
+
try:
|
|
1351
|
+
physical_raw = _read_private(physical_path)
|
|
1352
|
+
if physical_raw != _canonical(setup):
|
|
1353
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1354
|
+
original_enrollment, original_enrollment_raw = _read_bootstrap_enrollment(
|
|
1355
|
+
physical_path.parent / 'owner-bootstrap-enrollment.json')
|
|
1356
|
+
if (_canonical(original_enrollment) != _canonical(enrollment)
|
|
1357
|
+
or original_enrollment_raw != _canonical(enrollment)):
|
|
1358
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1359
|
+
physical_setup = _parse_owner_setup(
|
|
1360
|
+
physical_raw, original_enrollment, original_enrollment_raw,
|
|
1361
|
+
configuration_digest, physical_path.parent)
|
|
1362
|
+
if physical_setup != setup:
|
|
1363
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1364
|
+
context = enrollment['context']
|
|
1365
|
+
physical_digest = hashlib.sha256(physical_raw).hexdigest()
|
|
1366
|
+
context_fields = ('supervisorId', 'custodianId', 'providerId', 'installationId')
|
|
1367
|
+
expected = {field: context[field] for field in context_fields}
|
|
1368
|
+
for request in registry['requests']:
|
|
1369
|
+
trust = request['intent']['trust']
|
|
1370
|
+
configuration = request['intent']['configuration']
|
|
1371
|
+
payload = request['payload']
|
|
1372
|
+
for projection in (trust, configuration, payload):
|
|
1373
|
+
if any(type(projection.get(field)) is not str
|
|
1374
|
+
or projection[field] != expected[field]
|
|
1375
|
+
for field in context_fields):
|
|
1376
|
+
raise LocalPostgresError(
|
|
1377
|
+
'generation-authority-registry-birth-incomplete')
|
|
1378
|
+
if (type(trust.get('ownerBootstrapContextDigest')) is not str
|
|
1379
|
+
or trust['ownerBootstrapContextDigest'] != physical_digest):
|
|
1380
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete')
|
|
1381
|
+
except (KeyError, TypeError, ValueError, OSError):
|
|
1382
|
+
raise LocalPostgresError('generation-authority-registry-birth-incomplete') from None
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def sys_platform_darwin() -> bool:
|
|
1386
|
+
|
|
1387
|
+
return sys.platform == 'darwin'
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
class OwnerAuthorityContext:
|
|
1391
|
+
"""Opaque immutable identity/purpose binding issued by original bootstrap."""
|
|
1392
|
+
|
|
1393
|
+
__slots__ = ('_configuration_digest', '_custodian_id', '_installation_id',
|
|
1394
|
+
'_issuer', '_issuer_registry', '_kind', '_provider_id', '_purpose',
|
|
1395
|
+
'_supervisor_id')
|
|
1396
|
+
|
|
1397
|
+
def __init__(self, seal: object, issuer: object, *, purpose: str, custodian_id: str,
|
|
1398
|
+
supervisor_id: str, provider_id: str, installation_id: str,
|
|
1399
|
+
configuration_digest: str):
|
|
1400
|
+
if seal is not _CONTEXT_SEAL:
|
|
1401
|
+
raise TypeError('owner authority context is bootstrap-issued')
|
|
1402
|
+
if purpose not in _OWNER_PURPOSES:
|
|
1403
|
+
_context_reject('owner-authority-context-invalid')
|
|
1404
|
+
object.__setattr__(self, '_issuer', issuer)
|
|
1405
|
+
object.__setattr__(self, '_issuer_registry', issuer)
|
|
1406
|
+
object.__setattr__(self, '_kind', 'umf.owner-authority-context/0.1')
|
|
1407
|
+
object.__setattr__(self, '_purpose', purpose)
|
|
1408
|
+
object.__setattr__(self, '_custodian_id', _context_uuid(custodian_id))
|
|
1409
|
+
object.__setattr__(self, '_supervisor_id', _context_uuid(supervisor_id))
|
|
1410
|
+
object.__setattr__(self, '_provider_id', _context_uuid(provider_id))
|
|
1411
|
+
object.__setattr__(self, '_installation_id', _context_text(installation_id))
|
|
1412
|
+
object.__setattr__(self, '_configuration_digest', _context_digest(configuration_digest))
|
|
1413
|
+
|
|
1414
|
+
def __setattr__(self, _name: str, _value: object) -> None:
|
|
1415
|
+
raise AttributeError('owner authority context is immutable')
|
|
1416
|
+
|
|
1417
|
+
def __reduce_ex__(self, _protocol: int):
|
|
1418
|
+
raise TypeError('owner authority context cannot be serialized')
|
|
1419
|
+
|
|
1420
|
+
def __repr__(self) -> str:
|
|
1421
|
+
return '<OwnerAuthorityContext opaque>'
|
|
1422
|
+
|
|
1423
|
+
|
|
1424
|
+
def _context_reject(code: str) -> None:
|
|
1425
|
+
raise LocalPostgresError(code)
|
|
1426
|
+
|
|
1427
|
+
|
|
1428
|
+
def _context_uuid(value: object) -> str:
|
|
1429
|
+
if type(value) is not str:
|
|
1430
|
+
_context_reject('owner-authority-context-invalid')
|
|
1431
|
+
try:
|
|
1432
|
+
if str(uuid.UUID(value)) != value:
|
|
1433
|
+
_context_reject('owner-authority-context-invalid')
|
|
1434
|
+
except ValueError:
|
|
1435
|
+
_context_reject('owner-authority-context-invalid')
|
|
1436
|
+
return value
|
|
1437
|
+
|
|
1438
|
+
|
|
1439
|
+
def _context_text(value: object) -> str:
|
|
1440
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
1441
|
+
_context_reject('owner-authority-context-invalid')
|
|
1442
|
+
try:
|
|
1443
|
+
value.encode('utf-8')
|
|
1444
|
+
except UnicodeEncodeError:
|
|
1445
|
+
_context_reject('owner-authority-context-invalid')
|
|
1446
|
+
return value
|
|
1447
|
+
|
|
1448
|
+
|
|
1449
|
+
def _context_digest(value: object) -> str:
|
|
1450
|
+
if type(value) is not str or not _HEX.fullmatch(value):
|
|
1451
|
+
_context_reject('owner-authority-context-invalid')
|
|
1452
|
+
return value
|
|
1453
|
+
|
|
1454
|
+
|
|
1455
|
+
def _issue_owner_authority_context(issuer: object, configuration_digest: str) -> OwnerAuthorityContext:
|
|
1456
|
+
"""Issue only from the exact registered original-bootstrap issuer."""
|
|
1457
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1458
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1459
|
+
_context_reject('owner-authority-context-issuer-required')
|
|
1460
|
+
material = issuer._owner_authority_context_material()
|
|
1461
|
+
if type(material) is not tuple or len(material) != 6:
|
|
1462
|
+
_context_reject('owner-authority-context-invalid')
|
|
1463
|
+
purpose, custodian_id, supervisor_id, provider_id, installation_id, issuer_digest = material
|
|
1464
|
+
if issuer_digest != configuration_digest:
|
|
1465
|
+
_context_reject('owner-authority-context-binding-mismatch')
|
|
1466
|
+
context = OwnerAuthorityContext(
|
|
1467
|
+
_CONTEXT_SEAL, issuer, purpose=purpose, custodian_id=custodian_id,
|
|
1468
|
+
supervisor_id=supervisor_id, provider_id=provider_id,
|
|
1469
|
+
installation_id=installation_id, configuration_digest=issuer_digest)
|
|
1470
|
+
metadata = _original_owner_context_journal_metadata(issuer)
|
|
1471
|
+
_CONTEXT_JOURNAL_METADATA[id(context)] = (
|
|
1472
|
+
context, issuer, _canonical(metadata))
|
|
1473
|
+
_CONTEXTS[id(context)] = context
|
|
1474
|
+
return context
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def _original_owner_context_journal_metadata(
|
|
1478
|
+
issuer: object) -> dict[str, Any]:
|
|
1479
|
+
"""Capture fixed metadata from the verified original enrollment/context."""
|
|
1480
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1481
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1482
|
+
_context_reject('owner-authority-context-issuer-required')
|
|
1483
|
+
issuer._owner_authority_context_material()
|
|
1484
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(issuer._enrollment_path)
|
|
1485
|
+
context_raw = _read_private(
|
|
1486
|
+
issuer._profile.control_home / 'owner-bootstrap-context.json')
|
|
1487
|
+
if (hashlib.sha256(enrollment_raw).hexdigest() != issuer._enrollment_digest
|
|
1488
|
+
or context_raw != issuer._context_bytes):
|
|
1489
|
+
_context_reject('owner-authority-context-binding-mismatch')
|
|
1490
|
+
setup = _parse_owner_setup(
|
|
1491
|
+
context_raw, enrollment, enrollment_raw, issuer._configuration_digest,
|
|
1492
|
+
issuer._profile.control_home)
|
|
1493
|
+
if setup['state'] != 'confirmed':
|
|
1494
|
+
_context_reject('owner-authority-context-unverified')
|
|
1495
|
+
if enrollment['profile'] in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
1496
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
1497
|
+
_verify_primary_owner_resources(setup, enrollment, issuer._configuration_digest)
|
|
1498
|
+
birth = enrollment['supervisorJournalBirth']
|
|
1499
|
+
supervisor_journal: dict[str, str] | None = {
|
|
1500
|
+
'birthDigest': hashlib.sha256(_canonical(birth)).hexdigest(),
|
|
1501
|
+
'journalProfile': birth['journalProfile'],
|
|
1502
|
+
'journalId': birth['journalId'],
|
|
1503
|
+
'definitionDigest': birth['definitionDigest'],
|
|
1504
|
+
}
|
|
1505
|
+
else:
|
|
1506
|
+
supervisor_journal = None
|
|
1507
|
+
if enrollment['profile'] == 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
1508
|
+
target_birth = enrollment['targetCustodyJournalBirth']
|
|
1509
|
+
target_journal: dict[str, str] | None = {
|
|
1510
|
+
'birthDigest': hashlib.sha256(_canonical(target_birth)).hexdigest(),
|
|
1511
|
+
'journalProfile': target_birth['journalProfile'],
|
|
1512
|
+
'definitionDigest': target_birth['definitionDigest'],
|
|
1513
|
+
}
|
|
1514
|
+
metadata_profile = 'umf.owner-context-journal-metadata/0.2'
|
|
1515
|
+
else:
|
|
1516
|
+
target_journal = None
|
|
1517
|
+
metadata_profile = 'umf.owner-context-journal-metadata/0.1'
|
|
1518
|
+
value = {
|
|
1519
|
+
'profile': metadata_profile,
|
|
1520
|
+
'enrollmentProfile': enrollment['profile'],
|
|
1521
|
+
'ownerContextProfile': _OWNER_CONTEXT_PROFILE,
|
|
1522
|
+
'ownerBootstrapContextDigest': hashlib.sha256(context_raw).hexdigest(),
|
|
1523
|
+
'supervisorJournal': supervisor_journal,
|
|
1524
|
+
}
|
|
1525
|
+
if target_journal is not None:
|
|
1526
|
+
value['targetCustodyJournal'] = target_journal
|
|
1527
|
+
from .supervisor_journal_codec import validate_metadata
|
|
1528
|
+
try:
|
|
1529
|
+
return validate_metadata(value)
|
|
1530
|
+
except Exception as exc:
|
|
1531
|
+
from .supervisor_journal_codec import SupervisorJournalCodecError
|
|
1532
|
+
if isinstance(exc, SupervisorJournalCodecError):
|
|
1533
|
+
_context_reject('owner-authority-context-journal-metadata-invalid')
|
|
1534
|
+
raise
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def _owner_context_journal_metadata(context: object) -> dict[str, Any]:
|
|
1538
|
+
"""Return only the immutable bootstrap-populated metadata for this context."""
|
|
1539
|
+
if type(context) is not OwnerAuthorityContext or _CONTEXTS.get(id(context)) is not context:
|
|
1540
|
+
_context_reject('owner-authority-context-unverified')
|
|
1541
|
+
entry = _CONTEXT_JOURNAL_METADATA.get(id(context))
|
|
1542
|
+
if (entry is None or entry[0] is not context or entry[1] is not context._issuer):
|
|
1543
|
+
_context_reject('owner-authority-context-journal-metadata-invalid')
|
|
1544
|
+
from .supervisor_journal_codec import SupervisorJournalCodecError, validate_metadata
|
|
1545
|
+
try:
|
|
1546
|
+
raw = entry[2]
|
|
1547
|
+
value = json.loads(raw, object_pairs_hook=_no_duplicates)
|
|
1548
|
+
if _canonical(value) != raw:
|
|
1549
|
+
raise SupervisorJournalCodecError('supervisor-journal-context-metadata-invalid')
|
|
1550
|
+
return validate_metadata(value)
|
|
1551
|
+
except (LocalPostgresError, SupervisorJournalCodecError, TypeError, ValueError):
|
|
1552
|
+
_context_reject('owner-authority-context-journal-metadata-invalid')
|
|
1553
|
+
|
|
1554
|
+
|
|
1555
|
+
def _supervisor_journal_birth_for_issuer(issuer: object) -> _OriginalSupervisorJournalBirth | None:
|
|
1556
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1557
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1558
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1559
|
+
entry = _SUPERVISOR_JOURNAL_BIRTHS.get(id(issuer))
|
|
1560
|
+
if entry is None:
|
|
1561
|
+
return None
|
|
1562
|
+
if (entry[0] is not issuer or type(entry[1]) is not _OriginalSupervisorJournalBirth
|
|
1563
|
+
or entry[1]._issuer is not issuer or entry[3] != entry[1]._descriptor_bytes):
|
|
1564
|
+
raise LocalPostgresError('supervisor-journal-birth-unverified')
|
|
1565
|
+
return entry[1]
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
def _issue_original_supervisor_journal_birth(
|
|
1569
|
+
issuer: object) -> _OriginalSupervisorJournalBirth:
|
|
1570
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1571
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1572
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1573
|
+
existing = _supervisor_journal_birth_for_issuer(issuer)
|
|
1574
|
+
if existing is not None:
|
|
1575
|
+
return existing
|
|
1576
|
+
issuer._owner_authority_context_material()
|
|
1577
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(issuer._enrollment_path)
|
|
1578
|
+
if enrollment['profile'] not in ('umf.local-owner-bootstrap-enrollment/0.3',
|
|
1579
|
+
'umf.local-owner-bootstrap-enrollment/0.5'):
|
|
1580
|
+
raise LocalPostgresError('supervisor-journal-birth-unavailable')
|
|
1581
|
+
context_raw = _read_private(issuer._profile.control_home / 'owner-bootstrap-context.json')
|
|
1582
|
+
setup = _parse_owner_setup(
|
|
1583
|
+
context_raw, enrollment, enrollment_raw, issuer._configuration_digest,
|
|
1584
|
+
issuer._profile.control_home)
|
|
1585
|
+
if setup['state'] != 'confirmed':
|
|
1586
|
+
raise LocalPostgresError('supervisor-journal-birth-unconfirmed')
|
|
1587
|
+
_verify_primary_owner_resources(setup, enrollment, issuer._configuration_digest)
|
|
1588
|
+
descriptor = _canonical(enrollment['supervisorJournalBirth'])
|
|
1589
|
+
handle = _OriginalSupervisorJournalBirth(
|
|
1590
|
+
_SUPERVISOR_JOURNAL_BIRTH_SEAL, issuer, descriptor)
|
|
1591
|
+
_SUPERVISOR_JOURNAL_BIRTHS[id(issuer)] = (issuer, handle, setup, descriptor)
|
|
1592
|
+
return handle
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def _resolve_original_supervisor_journal_birth(
|
|
1596
|
+
birth: object, *, issuer: object, context: object, supervisor: object,
|
|
1597
|
+
control_lease: object) -> dict[str, Any]:
|
|
1598
|
+
if (type(birth) is not _OriginalSupervisorJournalBirth
|
|
1599
|
+
or type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1600
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer
|
|
1601
|
+
or birth._issuer is not issuer):
|
|
1602
|
+
raise LocalPostgresError('supervisor-journal-birth-unverified')
|
|
1603
|
+
entry = _SUPERVISOR_JOURNAL_BIRTHS.get(id(issuer))
|
|
1604
|
+
if entry is None or entry[0] is not issuer or entry[1] is not birth:
|
|
1605
|
+
raise LocalPostgresError('supervisor-journal-birth-unverified')
|
|
1606
|
+
_resolve_original_control_lease(
|
|
1607
|
+
control_lease, context=context, supervisor=supervisor)
|
|
1608
|
+
if issuer._supervisor is not supervisor:
|
|
1609
|
+
raise LocalPostgresError('supervisor-journal-birth-unverified')
|
|
1610
|
+
issuer._owner_authority_context_material()
|
|
1611
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(issuer._enrollment_path)
|
|
1612
|
+
setup_raw = _read_private(issuer._profile.control_home / 'owner-bootstrap-context.json')
|
|
1613
|
+
setup = _parse_owner_setup(
|
|
1614
|
+
setup_raw, enrollment, enrollment_raw, issuer._configuration_digest,
|
|
1615
|
+
issuer._profile.control_home)
|
|
1616
|
+
_verify_primary_owner_resources(setup, enrollment, issuer._configuration_digest)
|
|
1617
|
+
if (setup['state'] != 'confirmed'
|
|
1618
|
+
or _canonical(enrollment.get('supervisorJournalBirth'))
|
|
1619
|
+
!= birth._descriptor_bytes):
|
|
1620
|
+
raise LocalPostgresError('supervisor-journal-birth-unverified')
|
|
1621
|
+
return json.loads(birth._descriptor_bytes)
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
def _target_custody_journal_birth_for_issuer(
|
|
1625
|
+
issuer: object) -> _OriginalTargetCustodyJournalBirth | None:
|
|
1626
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1627
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1628
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1629
|
+
entry = _TARGET_CUSTODY_JOURNAL_BIRTHS.get(id(issuer))
|
|
1630
|
+
if entry is None:
|
|
1631
|
+
return None
|
|
1632
|
+
if (entry[0] is not issuer
|
|
1633
|
+
or type(entry[1]) is not _OriginalTargetCustodyJournalBirth
|
|
1634
|
+
or entry[1]._issuer is not issuer
|
|
1635
|
+
or entry[2] != entry[1]._descriptor_bytes):
|
|
1636
|
+
raise LocalPostgresError('target-custody-journal-birth-unverified')
|
|
1637
|
+
return entry[1]
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _issue_original_target_custody_journal_birth(
|
|
1641
|
+
issuer: object) -> _OriginalTargetCustodyJournalBirth:
|
|
1642
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1643
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1644
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1645
|
+
existing = _target_custody_journal_birth_for_issuer(issuer)
|
|
1646
|
+
if existing is not None:
|
|
1647
|
+
return existing
|
|
1648
|
+
issuer._owner_authority_context_material()
|
|
1649
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(issuer._enrollment_path)
|
|
1650
|
+
if enrollment['profile'] != 'umf.local-owner-bootstrap-enrollment/0.5':
|
|
1651
|
+
raise LocalPostgresError('target-custody-journal-birth-unavailable')
|
|
1652
|
+
context_raw = _read_private(issuer._profile.control_home / 'owner-bootstrap-context.json')
|
|
1653
|
+
setup = _parse_owner_setup(
|
|
1654
|
+
context_raw, enrollment, enrollment_raw, issuer._configuration_digest,
|
|
1655
|
+
issuer._profile.control_home)
|
|
1656
|
+
if setup['state'] != 'confirmed':
|
|
1657
|
+
raise LocalPostgresError('target-custody-journal-birth-unconfirmed')
|
|
1658
|
+
_verify_primary_owner_resources(setup, enrollment, issuer._configuration_digest)
|
|
1659
|
+
descriptor = _canonical(enrollment['targetCustodyJournalBirth'])
|
|
1660
|
+
handle = _OriginalTargetCustodyJournalBirth(
|
|
1661
|
+
_TARGET_CUSTODY_JOURNAL_BIRTH_SEAL, issuer, descriptor)
|
|
1662
|
+
_TARGET_CUSTODY_JOURNAL_BIRTHS[id(issuer)] = (issuer, handle, descriptor)
|
|
1663
|
+
return handle
|
|
1664
|
+
|
|
1665
|
+
|
|
1666
|
+
def _resolve_original_target_custody_journal_birth(
|
|
1667
|
+
birth: object, *, issuer: object, context: object, supervisor: object,
|
|
1668
|
+
control_lease: object) -> dict[str, Any]:
|
|
1669
|
+
if (type(birth) is not _OriginalTargetCustodyJournalBirth
|
|
1670
|
+
or type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1671
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer
|
|
1672
|
+
or birth._issuer is not issuer):
|
|
1673
|
+
raise LocalPostgresError('target-custody-journal-birth-unverified')
|
|
1674
|
+
entry = _TARGET_CUSTODY_JOURNAL_BIRTHS.get(id(issuer))
|
|
1675
|
+
if (entry is None or entry[0] is not issuer or entry[1] is not birth
|
|
1676
|
+
or entry[2] != birth._descriptor_bytes):
|
|
1677
|
+
raise LocalPostgresError('target-custody-journal-birth-unverified')
|
|
1678
|
+
_resolve_original_control_lease(
|
|
1679
|
+
control_lease, context=context, supervisor=supervisor)
|
|
1680
|
+
if issuer._supervisor is not supervisor:
|
|
1681
|
+
raise LocalPostgresError('target-custody-journal-birth-unverified')
|
|
1682
|
+
issuer._owner_authority_context_material()
|
|
1683
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(issuer._enrollment_path)
|
|
1684
|
+
setup_raw = _read_private(issuer._profile.control_home / 'owner-bootstrap-context.json')
|
|
1685
|
+
setup = _parse_owner_setup(
|
|
1686
|
+
setup_raw, enrollment, enrollment_raw, issuer._configuration_digest,
|
|
1687
|
+
issuer._profile.control_home)
|
|
1688
|
+
_verify_primary_owner_resources(setup, enrollment, issuer._configuration_digest)
|
|
1689
|
+
if (setup['state'] != 'confirmed'
|
|
1690
|
+
or _canonical(enrollment.get('targetCustodyJournalBirth'))
|
|
1691
|
+
!= birth._descriptor_bytes):
|
|
1692
|
+
raise LocalPostgresError('target-custody-journal-birth-unverified')
|
|
1693
|
+
return json.loads(birth._descriptor_bytes)
|
|
1694
|
+
|
|
1695
|
+
|
|
1696
|
+
def _require_owner_context(context: object, *, issuer: object | None = None,
|
|
1697
|
+
configuration_digest: str | None = None) -> OwnerAuthorityContext:
|
|
1698
|
+
if (type(context) is not OwnerAuthorityContext
|
|
1699
|
+
or _CONTEXTS.get(id(context)) is not context
|
|
1700
|
+
or context._issuer_registry is not context._issuer
|
|
1701
|
+
or (issuer is not None and context._issuer is not issuer)
|
|
1702
|
+
or (configuration_digest is not None
|
|
1703
|
+
and context._configuration_digest != configuration_digest)):
|
|
1704
|
+
_context_reject('owner-authority-context-unverified')
|
|
1705
|
+
context._issuer._owner_authority_context_material()
|
|
1706
|
+
return context
|
|
1707
|
+
|
|
1708
|
+
|
|
1709
|
+
def _verify_control_lease_owner_binding(
|
|
1710
|
+
issuer: object, context: object, supervisor: object) -> tuple[LocalPostgresProfile, str]:
|
|
1711
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1712
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer
|
|
1713
|
+
or issuer._supervisor is not supervisor):
|
|
1714
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified')
|
|
1715
|
+
context = _require_owner_context(
|
|
1716
|
+
context, issuer=issuer, configuration_digest=issuer._configuration_digest)
|
|
1717
|
+
profile = issuer._profile
|
|
1718
|
+
try:
|
|
1719
|
+
if (supervisor._bootstrap_issuer is not issuer
|
|
1720
|
+
or supervisor._authority_context is not context
|
|
1721
|
+
or supervisor._profile is not profile
|
|
1722
|
+
or supervisor._supervisor_id != profile.supervisor_id
|
|
1723
|
+
or supervisor._custodian_id != profile.custodian_id
|
|
1724
|
+
or supervisor._provider_id != profile.provider_id
|
|
1725
|
+
or supervisor._bound_installation_id != profile.installation_id
|
|
1726
|
+
or supervisor._owner_core.configuration_digest != issuer._configuration_digest
|
|
1727
|
+
or Path(supervisor._owner_core._ledger.path).is_absolute() is not True):
|
|
1728
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified')
|
|
1729
|
+
_verify_confirmed_owner_ledger_birth(
|
|
1730
|
+
issuer, supervisor._owner_core._ledger.path,
|
|
1731
|
+
issuer._configuration_digest)
|
|
1732
|
+
setup_raw = _read_private(profile.control_home / 'owner-bootstrap-context.json')
|
|
1733
|
+
setup, enrollment, enrollment_raw = _parse_original_context_for_lease(
|
|
1734
|
+
issuer, setup_raw)
|
|
1735
|
+
except LocalPostgresError:
|
|
1736
|
+
raise
|
|
1737
|
+
except Exception: # noqa: BLE001 - private owner/session details are not public diagnostics.
|
|
1738
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified') from None
|
|
1739
|
+
if (setup['state'] != 'confirmed'
|
|
1740
|
+
or setup_raw != issuer._context_bytes
|
|
1741
|
+
or enrollment['context'] != {
|
|
1742
|
+
'custodianId': context._custodian_id,
|
|
1743
|
+
'supervisorId': context._supervisor_id,
|
|
1744
|
+
'providerId': context._provider_id,
|
|
1745
|
+
'installationId': context._installation_id,
|
|
1746
|
+
}
|
|
1747
|
+
or enrollment_raw != _canonical(enrollment)):
|
|
1748
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified')
|
|
1749
|
+
return profile, setup['setupId']
|
|
1750
|
+
|
|
1751
|
+
|
|
1752
|
+
def _parse_original_context_for_lease(
|
|
1753
|
+
issuer: _LocalOwnerBootstrapIssuer, raw: bytes
|
|
1754
|
+
) -> tuple[dict[str, Any], dict[str, Any], bytes]:
|
|
1755
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(
|
|
1756
|
+
issuer._profile.control_home / 'owner-bootstrap-enrollment.json')
|
|
1757
|
+
config, _keys = validate_owner_configuration(enrollment['ownerConfiguration'])
|
|
1758
|
+
digest = hashlib.sha256(canonical_json(config).encode('utf-8')).hexdigest()
|
|
1759
|
+
setup = _parse_owner_setup(
|
|
1760
|
+
raw, enrollment, enrollment_raw, digest, issuer._profile.control_home)
|
|
1761
|
+
return setup, enrollment, enrollment_raw
|
|
1762
|
+
|
|
1763
|
+
|
|
1764
|
+
@contextmanager
|
|
1765
|
+
def _acquire_original_control_lease(issuer: object, context: object,
|
|
1766
|
+
supervisor: object, *, operation_kind: str,
|
|
1767
|
+
timeout_ms: int = 5000):
|
|
1768
|
+
"""Acquire the one original setup mutex for a fixed native operation.
|
|
1769
|
+
|
|
1770
|
+
This lease is physical exclusion only. The native supervisor retains its
|
|
1771
|
+
own target wrapper and every effect still requires its original approval,
|
|
1772
|
+
reservation and phase binding.
|
|
1773
|
+
"""
|
|
1774
|
+
if type(operation_kind) is not str or operation_kind not in _CONTROL_LEASE_KINDS:
|
|
1775
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-kind-invalid')
|
|
1776
|
+
profile, setup_id = _verify_control_lease_owner_binding(
|
|
1777
|
+
issuer, context, supervisor)
|
|
1778
|
+
with _owner_setup_lease(profile.control_home, timeout_ms=timeout_ms) as lock_handle:
|
|
1779
|
+
profile_now, setup_now = _verify_control_lease_owner_binding(
|
|
1780
|
+
issuer, context, supervisor)
|
|
1781
|
+
if profile_now is not profile or setup_now != setup_id:
|
|
1782
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-binding-changed')
|
|
1783
|
+
lease = _OriginalControlLease(
|
|
1784
|
+
_CONTROL_LEASE_SEAL, issuer, context, supervisor, lock_handle,
|
|
1785
|
+
operation_kind, setup_id)
|
|
1786
|
+
with _CONTROL_LEASES_GUARD:
|
|
1787
|
+
_CONTROL_LEASES[id(lease)] = (
|
|
1788
|
+
lease, issuer, context, supervisor, operation_kind)
|
|
1789
|
+
try:
|
|
1790
|
+
_resolve_original_control_lease(
|
|
1791
|
+
lease, context=context, supervisor=supervisor,
|
|
1792
|
+
operation_kind=operation_kind)
|
|
1793
|
+
yield lease
|
|
1794
|
+
finally:
|
|
1795
|
+
with _CONTROL_LEASES_GUARD:
|
|
1796
|
+
_CONTROL_LEASES.pop(id(lease), None)
|
|
1797
|
+
|
|
1798
|
+
|
|
1799
|
+
def _resolve_original_control_lease(value: object, *, context: object,
|
|
1800
|
+
supervisor: object,
|
|
1801
|
+
operation_kind: str | None = None
|
|
1802
|
+
) -> _OriginalControlLease:
|
|
1803
|
+
if type(value) is not _OriginalControlLease:
|
|
1804
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified')
|
|
1805
|
+
entry = _CONTROL_LEASES.get(id(value))
|
|
1806
|
+
if (entry is None or entry[0] is not value or entry[1] is not value._issuer
|
|
1807
|
+
or entry[2] is not context or value._context is not context
|
|
1808
|
+
or entry[3] is not supervisor or value._supervisor is not supervisor
|
|
1809
|
+
or (operation_kind is not None and value._operation_kind != operation_kind)
|
|
1810
|
+
or value._profile is not value._issuer._profile
|
|
1811
|
+
or value._control_home != value._profile.control_home
|
|
1812
|
+
or value._process_id != os.getpid()
|
|
1813
|
+
or value._thread_id != threading.get_ident()):
|
|
1814
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-unverified')
|
|
1815
|
+
_verify_owner_setup_lock_handle(value._handle)
|
|
1816
|
+
profile, setup_id = _verify_control_lease_owner_binding(
|
|
1817
|
+
value._issuer, context, supervisor)
|
|
1818
|
+
if profile is not value._profile or setup_id != value._setup_id:
|
|
1819
|
+
raise LocalPostgresError('owner-bootstrap-control-lease-binding-changed')
|
|
1820
|
+
return value
|
|
1821
|
+
|
|
1822
|
+
|
|
1823
|
+
_OWNER_LEDGER_BIRTH_PROFILE = 'umf.owner-approval-ledger-birth/0.1'
|
|
1824
|
+
_OWNER_LEDGER_ANCHOR_PROFILE = 'umf.owner-approval-ledger-anchor/0.1'
|
|
1825
|
+
|
|
1826
|
+
|
|
1827
|
+
def _ledger_birth_path(issuer: object) -> Path:
|
|
1828
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1829
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1830
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1831
|
+
issuer._owner_authority_context_material()
|
|
1832
|
+
return issuer._profile.control_home / 'owner-approval-ledger-birth.json'
|
|
1833
|
+
|
|
1834
|
+
|
|
1835
|
+
def _ledger_anchor_path(issuer: object) -> Path:
|
|
1836
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1837
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer):
|
|
1838
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1839
|
+
issuer._owner_authority_context_material()
|
|
1840
|
+
return issuer._profile.control_home / 'owner-approval-ledger-anchor.json'
|
|
1841
|
+
|
|
1842
|
+
|
|
1843
|
+
def _ledger_birth_record(issuer: _LocalOwnerBootstrapIssuer, ledger_path: object,
|
|
1844
|
+
status: str) -> dict[str, Any]:
|
|
1845
|
+
if (type(ledger_path) is not str and not isinstance(ledger_path, Path)):
|
|
1846
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
1847
|
+
path = Path(ledger_path)
|
|
1848
|
+
if (not path.is_absolute() or os.path.normpath(str(path)) != str(path)
|
|
1849
|
+
or type(status) is not str or status not in ('pending', 'confirmed')):
|
|
1850
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
1851
|
+
material = issuer._owner_authority_context_material()
|
|
1852
|
+
configuration = issuer.owner_configuration
|
|
1853
|
+
return {'profile': _OWNER_LEDGER_BIRTH_PROFILE, 'status': status,
|
|
1854
|
+
'issuerId': issuer._issuer_id, 'enrollmentId': issuer._enrollment_id,
|
|
1855
|
+
'enrollmentDigest': issuer._enrollment_digest,
|
|
1856
|
+
'configurationDigest': issuer._configuration_digest,
|
|
1857
|
+
'authorityId': configuration['authorityId'],
|
|
1858
|
+
'purpose': material[0], 'custodianId': material[1],
|
|
1859
|
+
'supervisorId': material[2], 'providerId': material[3],
|
|
1860
|
+
'installationId': material[4], 'ledgerPath': str(path)}
|
|
1861
|
+
|
|
1862
|
+
|
|
1863
|
+
def _ledger_anchor_record(issuer: _LocalOwnerBootstrapIssuer, ledger_path: object,
|
|
1864
|
+
status: str) -> dict[str, Any]:
|
|
1865
|
+
birth = _ledger_birth_record(issuer, ledger_path, status)
|
|
1866
|
+
return {'profile': _OWNER_LEDGER_ANCHOR_PROFILE, 'status': status,
|
|
1867
|
+
'issuerId': birth['issuerId'], 'enrollmentId': birth['enrollmentId'],
|
|
1868
|
+
'enrollmentDigest': birth['enrollmentDigest'],
|
|
1869
|
+
'configurationDigest': birth['configurationDigest'],
|
|
1870
|
+
'authorityId': birth['authorityId'], 'purpose': birth['purpose'],
|
|
1871
|
+
'custodianId': birth['custodianId'], 'supervisorId': birth['supervisorId'],
|
|
1872
|
+
'providerId': birth['providerId'], 'installationId': birth['installationId'],
|
|
1873
|
+
'ledgerPath': birth['ledgerPath']}
|
|
1874
|
+
|
|
1875
|
+
|
|
1876
|
+
def _read_ledger_anchor(issuer: _LocalOwnerBootstrapIssuer) -> dict[str, Any]:
|
|
1877
|
+
raw = _read_private(_ledger_anchor_path(issuer))
|
|
1878
|
+
try:
|
|
1879
|
+
value = json.loads(raw, object_pairs_hook=_no_duplicates)
|
|
1880
|
+
except (json.JSONDecodeError, UnicodeDecodeError, LocalPostgresError):
|
|
1881
|
+
raise LocalPostgresError('owner-approval-ledger-anchor-invalid') from None
|
|
1882
|
+
if (type(value) is not dict or _canonical(value) != raw
|
|
1883
|
+
or set(value) != {'profile', 'status', 'issuerId', 'enrollmentId',
|
|
1884
|
+
'enrollmentDigest', 'configurationDigest', 'authorityId', 'purpose',
|
|
1885
|
+
'custodianId', 'supervisorId', 'providerId', 'installationId',
|
|
1886
|
+
'ledgerPath'}
|
|
1887
|
+
or value['profile'] != _OWNER_LEDGER_ANCHOR_PROFILE
|
|
1888
|
+
or value['status'] not in ('pending', 'confirmed')):
|
|
1889
|
+
raise LocalPostgresError('owner-approval-ledger-anchor-invalid')
|
|
1890
|
+
return value
|
|
1891
|
+
|
|
1892
|
+
|
|
1893
|
+
def _read_ledger_birth(issuer: _LocalOwnerBootstrapIssuer) -> dict[str, Any]:
|
|
1894
|
+
path = _ledger_birth_path(issuer)
|
|
1895
|
+
raw = _read_private(path)
|
|
1896
|
+
try:
|
|
1897
|
+
value = json.loads(raw, object_pairs_hook=_no_duplicates)
|
|
1898
|
+
except (json.JSONDecodeError, UnicodeDecodeError, LocalPostgresError):
|
|
1899
|
+
raise LocalPostgresError('owner-approval-ledger-birth-invalid') from None
|
|
1900
|
+
if type(value) is not dict or _canonical(value) != raw:
|
|
1901
|
+
raise LocalPostgresError('owner-approval-ledger-birth-invalid')
|
|
1902
|
+
return value
|
|
1903
|
+
|
|
1904
|
+
|
|
1905
|
+
def _begin_owner_ledger_birth(issuer: object, ledger_path: object,
|
|
1906
|
+
configuration_digest: str) -> Path:
|
|
1907
|
+
"""Durably bind one original ledger path before the approval core opens it."""
|
|
1908
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
1909
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer
|
|
1910
|
+
or issuer._configuration_digest != configuration_digest):
|
|
1911
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1912
|
+
path = _ledger_birth_path(issuer)
|
|
1913
|
+
anchor_path = _ledger_anchor_path(issuer)
|
|
1914
|
+
pending = _ledger_birth_record(issuer, ledger_path, 'pending')
|
|
1915
|
+
anchor = _ledger_anchor_record(issuer, ledger_path, 'pending')
|
|
1916
|
+
try:
|
|
1917
|
+
current_anchor = _read_ledger_anchor(issuer)
|
|
1918
|
+
except LocalPostgresError as exc:
|
|
1919
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
1920
|
+
raise
|
|
1921
|
+
# Upgrade an intact original birth record in place. If both binding
|
|
1922
|
+
# records are absent, an existing ledger is never adopted.
|
|
1923
|
+
try:
|
|
1924
|
+
existing_birth = _read_ledger_birth(issuer)
|
|
1925
|
+
except LocalPostgresError as birth_exc:
|
|
1926
|
+
if birth_exc.code != 'supervisor-private-file-unavailable':
|
|
1927
|
+
raise
|
|
1928
|
+
existing_birth = None
|
|
1929
|
+
if existing_birth is not None:
|
|
1930
|
+
existing_status = existing_birth.get('status')
|
|
1931
|
+
if (existing_status not in ('pending', 'confirmed')
|
|
1932
|
+
or existing_birth != _ledger_birth_record(
|
|
1933
|
+
issuer, ledger_path, existing_status)):
|
|
1934
|
+
raise LocalPostgresError('owner-approval-ledger-birth-mismatch')
|
|
1935
|
+
current_anchor = _ledger_anchor_record(issuer, ledger_path, existing_status)
|
|
1936
|
+
_write_private(anchor_path, _canonical(current_anchor))
|
|
1937
|
+
else:
|
|
1938
|
+
# The anchor precedes the ledger and birth marker. An existing
|
|
1939
|
+
# ledger without its original anchor cannot be adopted at a path.
|
|
1940
|
+
target = Path(pending['ledgerPath'])
|
|
1941
|
+
if target.exists() or target.with_name(target.name + '.lock').exists():
|
|
1942
|
+
raise LocalPostgresError('owner-approval-ledger-anchor-required') from None
|
|
1943
|
+
_write_private(anchor_path, _canonical(anchor))
|
|
1944
|
+
current_anchor = anchor
|
|
1945
|
+
expected_anchor = dict(anchor)
|
|
1946
|
+
expected_anchor['status'] = current_anchor.get('status')
|
|
1947
|
+
if current_anchor != expected_anchor:
|
|
1948
|
+
raise LocalPostgresError('owner-approval-ledger-anchor-mismatch')
|
|
1949
|
+
if current_anchor['status'] == 'confirmed':
|
|
1950
|
+
try:
|
|
1951
|
+
current_birth = _read_ledger_birth(issuer)
|
|
1952
|
+
except LocalPostgresError:
|
|
1953
|
+
raise LocalPostgresError('owner-approval-ledger-birth-missing') from None
|
|
1954
|
+
expected = _ledger_birth_record(issuer, ledger_path, 'confirmed')
|
|
1955
|
+
if current_birth != expected:
|
|
1956
|
+
raise LocalPostgresError('owner-approval-ledger-birth-mismatch')
|
|
1957
|
+
_verify_confirmed_owner_ledger_birth(issuer, ledger_path,
|
|
1958
|
+
configuration_digest)
|
|
1959
|
+
return Path(expected['ledgerPath'])
|
|
1960
|
+
try:
|
|
1961
|
+
current = _read_ledger_birth(issuer)
|
|
1962
|
+
except LocalPostgresError as exc:
|
|
1963
|
+
if exc.code != 'supervisor-private-file-unavailable':
|
|
1964
|
+
raise
|
|
1965
|
+
target = Path(pending['ledgerPath'])
|
|
1966
|
+
lock_path = target.with_name(target.name + '.lock')
|
|
1967
|
+
if target.exists() or lock_path.exists():
|
|
1968
|
+
_verify_unconfirmed_owner_ledger(target, configuration_digest,
|
|
1969
|
+
_ledger_anchor_record(issuer, ledger_path,
|
|
1970
|
+
'pending')['authorityId'])
|
|
1971
|
+
_write_private(path, _canonical(pending))
|
|
1972
|
+
return Path(pending['ledgerPath'])
|
|
1973
|
+
expected = dict(pending)
|
|
1974
|
+
expected['status'] = current.get('status') if type(current) is dict else None
|
|
1975
|
+
if current != expected or current.get('status') not in ('pending', 'confirmed'):
|
|
1976
|
+
raise LocalPostgresError('owner-approval-ledger-birth-mismatch')
|
|
1977
|
+
if current['status'] == 'pending':
|
|
1978
|
+
target = Path(pending['ledgerPath'])
|
|
1979
|
+
if target.exists():
|
|
1980
|
+
_verify_unconfirmed_owner_ledger(
|
|
1981
|
+
target, configuration_digest, pending['authorityId'])
|
|
1982
|
+
if current['status'] == 'confirmed':
|
|
1983
|
+
_verify_confirmed_owner_ledger_birth(issuer, current['ledgerPath'],
|
|
1984
|
+
configuration_digest)
|
|
1985
|
+
return Path(current['ledgerPath'])
|
|
1986
|
+
|
|
1987
|
+
|
|
1988
|
+
def _verify_confirmed_owner_ledger_birth(issuer: object, ledger_path: object,
|
|
1989
|
+
configuration_digest: str) -> Path:
|
|
1990
|
+
if type(issuer) is not _LocalOwnerBootstrapIssuer:
|
|
1991
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
1992
|
+
issuer._owner_authority_context_material()
|
|
1993
|
+
if type(ledger_path) is not str and not isinstance(ledger_path, Path):
|
|
1994
|
+
raise LocalPostgresError('owner-approval-ledger-path-invalid')
|
|
1995
|
+
target = _canonical_private_path(str(ledger_path))
|
|
1996
|
+
context_path = issuer._profile.control_home / 'owner-bootstrap-context.json'
|
|
1997
|
+
try:
|
|
1998
|
+
raw = _read_private(context_path)
|
|
1999
|
+
except LocalPostgresError:
|
|
2000
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unavailable') from None
|
|
2001
|
+
enrollment, enrollment_raw = _read_bootstrap_enrollment(
|
|
2002
|
+
issuer._profile.control_home / 'owner-bootstrap-enrollment.json')
|
|
2003
|
+
setup = _parse_owner_setup(raw, enrollment, enrollment_raw,
|
|
2004
|
+
configuration_digest, issuer._profile.control_home)
|
|
2005
|
+
if (setup['state'] != 'confirmed'
|
|
2006
|
+
or setup['ownerLedger']['ledgerPath'] != str(target)
|
|
2007
|
+
or raw != issuer._context_bytes):
|
|
2008
|
+
raise LocalPostgresError('local-postgresql-bootstrap-context-unverified')
|
|
2009
|
+
_verify_primary_owner_resources(setup, enrollment, configuration_digest)
|
|
2010
|
+
try:
|
|
2011
|
+
_read_private(issuer._profile.control_home / _OWNER_SETUP_LOCK)
|
|
2012
|
+
except LocalPostgresError:
|
|
2013
|
+
raise LocalPostgresError('owner-bootstrap-setup-lock-unavailable') from None
|
|
2014
|
+
return target
|
|
2015
|
+
|
|
2016
|
+
|
|
2017
|
+
def _confirm_owner_ledger_birth(issuer: object, ledger_path: object,
|
|
2018
|
+
configuration_digest: str) -> Path:
|
|
2019
|
+
if (type(issuer) is not _LocalOwnerBootstrapIssuer
|
|
2020
|
+
or _BOOTSTRAP_ISSUERS.get(id(issuer)) is not issuer
|
|
2021
|
+
or issuer._configuration_digest != configuration_digest):
|
|
2022
|
+
raise LocalPostgresError('local-postgresql-bootstrap-issuer-unverified')
|
|
2023
|
+
path = _ledger_birth_path(issuer)
|
|
2024
|
+
current = _read_ledger_birth(issuer)
|
|
2025
|
+
pending = _ledger_birth_record(issuer, ledger_path, 'pending')
|
|
2026
|
+
if current != pending:
|
|
2027
|
+
if current == _ledger_birth_record(issuer, ledger_path, 'confirmed'):
|
|
2028
|
+
return _verify_confirmed_owner_ledger_birth(
|
|
2029
|
+
issuer, ledger_path, configuration_digest)
|
|
2030
|
+
raise LocalPostgresError('owner-approval-ledger-birth-mismatch')
|
|
2031
|
+
anchor_path = _ledger_anchor_path(issuer)
|
|
2032
|
+
anchor = _read_ledger_anchor(issuer)
|
|
2033
|
+
if anchor != _ledger_anchor_record(issuer, ledger_path, 'pending'):
|
|
2034
|
+
raise LocalPostgresError('owner-approval-ledger-anchor-mismatch')
|
|
2035
|
+
confirmed = _ledger_birth_record(issuer, ledger_path, 'confirmed')
|
|
2036
|
+
target = Path(ledger_path)
|
|
2037
|
+
try:
|
|
2038
|
+
ledger = _read_private(target)
|
|
2039
|
+
lock = _read_private(target.with_name(target.name + '.lock'))
|
|
2040
|
+
except LocalPostgresError:
|
|
2041
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete') from None
|
|
2042
|
+
try:
|
|
2043
|
+
first = json.loads(ledger.splitlines()[0], object_pairs_hook=_no_duplicates)
|
|
2044
|
+
except (IndexError, json.JSONDecodeError, UnicodeDecodeError, LocalPostgresError):
|
|
2045
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete') from None
|
|
2046
|
+
issuer._owner_authority_context_material()
|
|
2047
|
+
if (type(first) is not dict
|
|
2048
|
+
or first.get('profile') != 'umf.configured-owner-approval-ledger/0.1'
|
|
2049
|
+
or first.get('configurationDigest') != configuration_digest
|
|
2050
|
+
or first.get('authorityId') != confirmed['authorityId']
|
|
2051
|
+
or type(lock) is not bytes):
|
|
2052
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete')
|
|
2053
|
+
# Mark the independent anchor first. If the following write is interrupted,
|
|
2054
|
+
# the remaining pending marker is rejected rather than rebinding history.
|
|
2055
|
+
_write_private(anchor_path,
|
|
2056
|
+
_canonical(_ledger_anchor_record(issuer, ledger_path, 'confirmed')),
|
|
2057
|
+
exclusive=False)
|
|
2058
|
+
_write_private(path, _canonical(confirmed), exclusive=False)
|
|
2059
|
+
return _verify_confirmed_owner_ledger_birth(issuer, ledger_path,
|
|
2060
|
+
configuration_digest)
|
|
2061
|
+
|
|
2062
|
+
|
|
2063
|
+
def _verify_unconfirmed_owner_ledger(path: Path, configuration_digest: str,
|
|
2064
|
+
authority_id: str) -> None:
|
|
2065
|
+
"""Allow only the initialized header when resuming an anchored pending birth."""
|
|
2066
|
+
try:
|
|
2067
|
+
raw = _read_private(path)
|
|
2068
|
+
_read_private(path.with_name(path.name + '.lock'))
|
|
2069
|
+
first_line, *tail = raw.splitlines()
|
|
2070
|
+
first = json.loads(first_line, object_pairs_hook=_no_duplicates)
|
|
2071
|
+
except (LocalPostgresError, ValueError, IndexError, UnicodeDecodeError):
|
|
2072
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete') from None
|
|
2073
|
+
if (tail or type(first) is not dict
|
|
2074
|
+
or first.get('profile') != 'umf.configured-owner-approval-ledger/0.1'
|
|
2075
|
+
or first.get('configurationDigest') != configuration_digest
|
|
2076
|
+
or first.get('authorityId') != authority_id):
|
|
2077
|
+
raise LocalPostgresError('owner-approval-ledger-birth-incomplete')
|