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,1488 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Fixed PostgreSQL control store for the G11 generation-ingress provider.
|
|
3
|
+
|
|
4
|
+
This is a finite native adapter, not a generic metadata API. It is not yet
|
|
5
|
+
selected by the migration host and its source controls do not qualify native
|
|
6
|
+
ownership, ACL, transaction-hook, or external-custody enforcement.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import re
|
|
14
|
+
import uuid
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .catalog import (
|
|
19
|
+
CatalogError,
|
|
20
|
+
_all,
|
|
21
|
+
_columns,
|
|
22
|
+
_constraint_shapes,
|
|
23
|
+
_execute,
|
|
24
|
+
_index_shapes,
|
|
25
|
+
_one,
|
|
26
|
+
_q,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
STORE_PROFILE = 'umf.pg-generation-ingress-store/0.1'
|
|
30
|
+
EPOCH_PROFILE = 'umf.native-ingress-epoch/0.1'
|
|
31
|
+
TRANSITION_PROFILE = 'umf.native-ingress-transition/0.1'
|
|
32
|
+
TARGET_CUSTODY_PROFILE = 'umf.native-target-custody/0.1'
|
|
33
|
+
_MAX_SAFE = 9_007_199_254_740_991
|
|
34
|
+
_MAX_RECORD_BYTES = 1_048_576
|
|
35
|
+
_HEX = re.compile(r'^[a-f0-9]{64}$')
|
|
36
|
+
_SYSTEM_IDENTIFIER = re.compile(r'^(0|[1-9][0-9]{0,19})$')
|
|
37
|
+
_CAPABILITY_SEAL = object()
|
|
38
|
+
_SCHEMA_MARKER_PREFIX = STORE_PROFILE + ':'
|
|
39
|
+
_STORE_SETTINGS = (
|
|
40
|
+
('search_path', 'pg_catalog'), ('TimeZone', 'UTC'), ('row_security', 'on'),
|
|
41
|
+
('session_replication_role', 'origin'), ('server_encoding', 'UTF8'),
|
|
42
|
+
('transaction_read_only', 'off'), ('transaction_isolation', 'read committed'),
|
|
43
|
+
)
|
|
44
|
+
_LOG = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
_EPOCH_COLUMNS = [
|
|
47
|
+
'"provider_id" pg_catalog.uuid NOT NULL',
|
|
48
|
+
'"installation_id" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
49
|
+
'"epoch" pg_catalog.uuid NOT NULL',
|
|
50
|
+
'"state" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
51
|
+
'"source_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
52
|
+
'"bundle_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
53
|
+
'"head_digest" pg_catalog.text COLLATE pg_catalog."C"',
|
|
54
|
+
'"principals_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
55
|
+
'"custody_sequence" pg_catalog.int8 NOT NULL',
|
|
56
|
+
'"record" pg_catalog.jsonb NOT NULL',
|
|
57
|
+
'"record_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
58
|
+
]
|
|
59
|
+
_EPOCH_CONSTRAINTS = [
|
|
60
|
+
('ingress_epochs_pk', 'PRIMARY KEY ("provider_id", "installation_id", "epoch")'),
|
|
61
|
+
('ingress_epochs_installation', 'CHECK ("installation_id" <> \'\')'),
|
|
62
|
+
('ingress_epochs_state', 'CHECK ("state" IN (\'prepared\',\'active\',\'retired\'))'),
|
|
63
|
+
('ingress_epochs_head', 'CHECK (("state" = \'prepared\' AND "head_digest" IS NULL) OR ("state" IN (\'active\',\'retired\') AND "head_digest" IS NOT NULL AND "head_digest" ~ \'^[a-f0-9]{64}$\'))'),
|
|
64
|
+
('ingress_epochs_digests', 'CHECK ("source_digest" ~ \'^[a-f0-9]{64}$\' AND "bundle_digest" ~ \'^[a-f0-9]{64}$\' AND "principals_digest" ~ \'^[a-f0-9]{64}$\' AND "record_digest" ~ \'^[a-f0-9]{64}$\')'),
|
|
65
|
+
('ingress_epochs_sequence', 'CHECK ("custody_sequence" BETWEEN 1 AND 9007199254740991)'),
|
|
66
|
+
('ingress_epochs_record', 'CHECK (pg_catalog.jsonb_typeof("record") = \'object\')'),
|
|
67
|
+
]
|
|
68
|
+
_TRANSITION_COLUMNS = [
|
|
69
|
+
'"transition_id" pg_catalog.uuid NOT NULL',
|
|
70
|
+
'"provider_id" pg_catalog.uuid NOT NULL',
|
|
71
|
+
'"installation_id" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
72
|
+
'"old_epoch" pg_catalog.uuid NOT NULL',
|
|
73
|
+
'"new_epoch" pg_catalog.uuid NOT NULL',
|
|
74
|
+
'"request_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
75
|
+
'"reservation_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
76
|
+
'"state" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
77
|
+
'"phase_index" pg_catalog.int2 NOT NULL',
|
|
78
|
+
'"record" pg_catalog.jsonb NOT NULL',
|
|
79
|
+
'"record_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
|
|
80
|
+
]
|
|
81
|
+
_TRANSITION_CONSTRAINTS = [
|
|
82
|
+
('ingress_transitions_pk', 'PRIMARY KEY ("transition_id")'),
|
|
83
|
+
('ingress_transitions_request', 'UNIQUE ("request_digest")'),
|
|
84
|
+
('ingress_transitions_reservation', 'UNIQUE ("reservation_digest")'),
|
|
85
|
+
('ingress_transitions_epochs', 'CHECK ("old_epoch" <> "new_epoch")'),
|
|
86
|
+
('ingress_transitions_state', 'CHECK ("state" IN (\'prepared\',\'fencing\',\'fenced\',\'cutover\',\'published\'))'),
|
|
87
|
+
('ingress_transitions_phase', 'CHECK (("state" IN (\'prepared\',\'fencing\',\'fenced\') AND "phase_index" = 0) OR ("state" IN (\'cutover\',\'published\') AND "phase_index" = 1))'),
|
|
88
|
+
('ingress_transitions_digests', 'CHECK ("request_digest" ~ \'^[a-f0-9]{64}$\' AND "reservation_digest" ~ \'^[a-f0-9]{64}$\' AND "record_digest" ~ \'^[a-f0-9]{64}$\')'),
|
|
89
|
+
('ingress_transitions_record', 'CHECK (pg_catalog.jsonb_typeof("record") = \'object\')'),
|
|
90
|
+
('ingress_transitions_old_fk', 'FOREIGN KEY ("provider_id","installation_id","old_epoch") REFERENCES {schema}."epochs" ("provider_id","installation_id","epoch") ON UPDATE RESTRICT ON DELETE RESTRICT'),
|
|
91
|
+
('ingress_transitions_new_fk', 'FOREIGN KEY ("provider_id","installation_id","new_epoch") REFERENCES {schema}."epochs" ("provider_id","installation_id","epoch") ON UPDATE RESTRICT ON DELETE RESTRICT'),
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _canonical_bytes(value: Any) -> bytes:
|
|
96
|
+
# Closed receipts use JSON values, safe integer counters, and ASCII member
|
|
97
|
+
# names. Validate iteratively before encoding so hostile nesting, huge
|
|
98
|
+
# counters, lone surrogates, or Python-only values cannot escape as
|
|
99
|
+
# serializer errors or consume unbounded recursion.
|
|
100
|
+
stack: list[tuple[Any, int]] = [(value, 0)]
|
|
101
|
+
nodes = 0
|
|
102
|
+
while stack:
|
|
103
|
+
item, depth = stack.pop()
|
|
104
|
+
nodes += 1
|
|
105
|
+
if nodes > 100_000 or depth > 64:
|
|
106
|
+
raise CatalogError('ingress-record-capacity')
|
|
107
|
+
if item is None or type(item) is bool:
|
|
108
|
+
continue
|
|
109
|
+
if type(item) is int:
|
|
110
|
+
if abs(item) > _MAX_SAFE:
|
|
111
|
+
raise CatalogError('ingress-record-invalid')
|
|
112
|
+
continue
|
|
113
|
+
if type(item) is str:
|
|
114
|
+
try:
|
|
115
|
+
item.encode('utf-8')
|
|
116
|
+
except UnicodeEncodeError:
|
|
117
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
118
|
+
continue
|
|
119
|
+
if type(item) is list:
|
|
120
|
+
stack.extend((child, depth + 1) for child in item)
|
|
121
|
+
continue
|
|
122
|
+
if type(item) is dict:
|
|
123
|
+
for key, child in item.items():
|
|
124
|
+
if type(key) is not str or not key.isascii():
|
|
125
|
+
raise CatalogError('ingress-record-invalid')
|
|
126
|
+
stack.append((key, depth + 1))
|
|
127
|
+
stack.append((child, depth + 1))
|
|
128
|
+
continue
|
|
129
|
+
raise CatalogError('ingress-record-invalid')
|
|
130
|
+
try:
|
|
131
|
+
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
132
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
133
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
134
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
135
|
+
if len(encoded) > _MAX_RECORD_BYTES:
|
|
136
|
+
raise CatalogError('ingress-record-capacity')
|
|
137
|
+
return encoded
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _digest(value: Any) -> str:
|
|
141
|
+
return hashlib.sha256(_canonical_bytes(value)).hexdigest()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _object(value: Any, keys: set[str], reason: str = 'ingress-record-invalid') -> dict[str, Any]:
|
|
145
|
+
if type(value) is not dict or set(value) != keys:
|
|
146
|
+
raise CatalogError(reason)
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _text(value: Any, *, max_bytes: int = 4096, empty: bool = False) -> str:
|
|
151
|
+
if type(value) is not str or (not empty and not value):
|
|
152
|
+
raise CatalogError('ingress-record-invalid')
|
|
153
|
+
try:
|
|
154
|
+
size = len(value.encode('utf-8'))
|
|
155
|
+
except UnicodeEncodeError:
|
|
156
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
157
|
+
if size > max_bytes or '\x00' in value:
|
|
158
|
+
raise CatalogError('ingress-record-invalid')
|
|
159
|
+
return value
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _uuid(value: Any) -> str:
|
|
163
|
+
if type(value) is not str:
|
|
164
|
+
raise CatalogError('ingress-record-invalid')
|
|
165
|
+
try:
|
|
166
|
+
parsed = uuid.UUID(value)
|
|
167
|
+
except (ValueError, AttributeError):
|
|
168
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
169
|
+
if str(parsed) != value:
|
|
170
|
+
raise CatalogError('ingress-record-invalid')
|
|
171
|
+
return value
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _hex(value: Any, *, nullable: bool = False) -> str | None:
|
|
175
|
+
if nullable and value is None:
|
|
176
|
+
return None
|
|
177
|
+
if type(value) is not str or _HEX.fullmatch(value) is None:
|
|
178
|
+
raise CatalogError('ingress-record-invalid')
|
|
179
|
+
return value
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _safe_int(value: Any, low: int = 1, high: int = _MAX_SAFE) -> int:
|
|
183
|
+
if type(value) is not int or not low <= value <= high:
|
|
184
|
+
raise CatalogError('ingress-record-invalid')
|
|
185
|
+
return value
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _system_identifier(value: Any) -> str:
|
|
189
|
+
if (type(value) is not str or _SYSTEM_IDENTIFIER.fullmatch(value) is None
|
|
190
|
+
or int(value) > 18_446_744_073_709_551_615):
|
|
191
|
+
raise CatalogError('ingress-record-invalid')
|
|
192
|
+
return value
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _validate_target_custody(value: Any) -> dict[str, Any]:
|
|
196
|
+
_object(value, {'profile', 'custodianId', 'registrationId', 'resourceId',
|
|
197
|
+
'incarnation', 'registrationDigest'})
|
|
198
|
+
if value['profile'] != TARGET_CUSTODY_PROFILE:
|
|
199
|
+
raise CatalogError('ingress-record-invalid')
|
|
200
|
+
for key in ('custodianId', 'registrationId', 'resourceId', 'incarnation'):
|
|
201
|
+
_uuid(value[key])
|
|
202
|
+
_hex(value['registrationDigest'])
|
|
203
|
+
return value
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _validate_principals(value: Any) -> str:
|
|
207
|
+
if type(value) is not list or not value or len(value) > 256:
|
|
208
|
+
raise CatalogError('ingress-record-invalid')
|
|
209
|
+
seen_logins: set[int] = set()
|
|
210
|
+
seen_subjects: set[int] = set()
|
|
211
|
+
membership_total = 0
|
|
212
|
+
for principal in value:
|
|
213
|
+
_object(principal, {'login', 'subject', 'audience', 'issuerProfile',
|
|
214
|
+
'issuerReceiptDigest', 'ownershipReceiptDigest', 'memberships'})
|
|
215
|
+
for role_key in ('login', 'subject'):
|
|
216
|
+
role = principal[role_key]
|
|
217
|
+
_object(role, {'oid', 'name'})
|
|
218
|
+
_safe_int(role['oid'], 1, 2**32 - 1)
|
|
219
|
+
_text(role['name'], max_bytes=63)
|
|
220
|
+
login_oid, subject_oid = principal['login']['oid'], principal['subject']['oid']
|
|
221
|
+
if login_oid in seen_logins or subject_oid in seen_subjects:
|
|
222
|
+
raise CatalogError('ingress-record-invalid')
|
|
223
|
+
seen_logins.add(login_oid)
|
|
224
|
+
seen_subjects.add(subject_oid)
|
|
225
|
+
if principal['audience'] not in ('person', 'batch'):
|
|
226
|
+
raise CatalogError('ingress-record-invalid')
|
|
227
|
+
_text(principal['issuerProfile'], max_bytes=256)
|
|
228
|
+
_hex(principal['issuerReceiptDigest'])
|
|
229
|
+
_hex(principal['ownershipReceiptDigest'])
|
|
230
|
+
memberships = principal['memberships']
|
|
231
|
+
if type(memberships) is not list:
|
|
232
|
+
raise CatalogError('ingress-record-invalid')
|
|
233
|
+
membership_total += len(memberships)
|
|
234
|
+
if membership_total > 1024:
|
|
235
|
+
raise CatalogError('ingress-record-invalid')
|
|
236
|
+
seen_memberships: set[int] = set()
|
|
237
|
+
for membership in memberships:
|
|
238
|
+
_object(membership, {'roleOid', 'roleName', 'inherit', 'set', 'admin'})
|
|
239
|
+
_safe_int(membership['roleOid'], 1, 2**32 - 1)
|
|
240
|
+
_text(membership['roleName'], max_bytes=63)
|
|
241
|
+
if any(type(membership[key]) is not bool for key in ('inherit', 'set', 'admin')):
|
|
242
|
+
raise CatalogError('ingress-record-invalid')
|
|
243
|
+
if membership['roleOid'] in seen_memberships:
|
|
244
|
+
raise CatalogError('ingress-record-invalid')
|
|
245
|
+
seen_memberships.add(membership['roleOid'])
|
|
246
|
+
return _digest(value)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _validate_epoch_record(value: Any) -> dict[str, Any]:
|
|
250
|
+
keys = {'profile', 'providerId', 'enrollmentId', 'installationId',
|
|
251
|
+
'targetCustody', 'epoch', 'state', 'sourceDigest', 'bundleDigest',
|
|
252
|
+
'headDigest', 'principals', 'principalsDigest', 'custodySequence',
|
|
253
|
+
'origin', 'originReceipt'}
|
|
254
|
+
_object(value, keys)
|
|
255
|
+
if value['profile'] != EPOCH_PROFILE or value['state'] not in ('prepared', 'active', 'retired'):
|
|
256
|
+
raise CatalogError('ingress-record-invalid')
|
|
257
|
+
_uuid(value['providerId']); _uuid(value['epoch'])
|
|
258
|
+
_text(value['enrollmentId'], max_bytes=256)
|
|
259
|
+
_text(value['installationId'], max_bytes=256)
|
|
260
|
+
_validate_target_custody(value['targetCustody'])
|
|
261
|
+
_hex(value['sourceDigest']); _hex(value['bundleDigest'])
|
|
262
|
+
_hex(value['headDigest'], nullable=value['state'] == 'prepared')
|
|
263
|
+
if value['state'] == 'prepared' and value['headDigest'] is not None:
|
|
264
|
+
raise CatalogError('ingress-record-invalid')
|
|
265
|
+
_hex(value['principalsDigest'])
|
|
266
|
+
if _validate_principals(value['principals']) != value['principalsDigest']:
|
|
267
|
+
raise CatalogError('ingress-record-invalid')
|
|
268
|
+
_safe_int(value['custodySequence'])
|
|
269
|
+
if value['origin'] == 'enrollment':
|
|
270
|
+
receipt = value['originReceipt']
|
|
271
|
+
_object(receipt, {'profile', 'providerId', 'enrollmentId', 'installationId',
|
|
272
|
+
'targetCustody', 'epoch', 'sourceDigest', 'bundleDigest',
|
|
273
|
+
'headDigest', 'principalsDigest', 'ownershipObservationDigest',
|
|
274
|
+
'externalReservationDigest'})
|
|
275
|
+
if (receipt['profile'] != 'umf.native-ingress-enrollment/0.1'
|
|
276
|
+
or any(receipt[key] != value[key] for key in
|
|
277
|
+
('providerId', 'enrollmentId', 'installationId', 'targetCustody',
|
|
278
|
+
'epoch', 'sourceDigest', 'bundleDigest', 'headDigest', 'principalsDigest'))):
|
|
279
|
+
raise CatalogError('ingress-record-invalid')
|
|
280
|
+
_hex(receipt['ownershipObservationDigest']); _hex(receipt['externalReservationDigest'])
|
|
281
|
+
elif value['origin'] == 'provision':
|
|
282
|
+
receipt = value['originReceipt']
|
|
283
|
+
_object(receipt, {'profile', 'providerId', 'enrollmentId', 'epoch',
|
|
284
|
+
'requestDigest', 'reservationDigest', 'principalsDigest',
|
|
285
|
+
'nativeOwnershipDigest', 'targetObservationDigest'})
|
|
286
|
+
if (receipt['profile'] != 'umf.native-ingress-provision-receipt/0.1'
|
|
287
|
+
or any(receipt[key] != value[key] for key in
|
|
288
|
+
('providerId', 'enrollmentId', 'epoch', 'principalsDigest'))):
|
|
289
|
+
raise CatalogError('ingress-record-invalid')
|
|
290
|
+
for key in ('requestDigest', 'reservationDigest', 'nativeOwnershipDigest',
|
|
291
|
+
'targetObservationDigest'):
|
|
292
|
+
_hex(receipt[key])
|
|
293
|
+
else:
|
|
294
|
+
raise CatalogError('ingress-record-invalid')
|
|
295
|
+
_canonical_bytes(value)
|
|
296
|
+
return value
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _validate_request(value: Any) -> dict[str, Any]:
|
|
300
|
+
keys = {'profile', 'providerId', 'enrollmentId', 'installationId',
|
|
301
|
+
'targetIdentityDigest', 'planDigest', 'fileDigest', 'expectedHead',
|
|
302
|
+
'previousSourceDigest', 'nextSourceDigest', 'previousBundleDigest',
|
|
303
|
+
'nextBundleDigest', 'oldEpoch', 'newEpoch', 'oldPrincipalsDigest',
|
|
304
|
+
'newPrincipalsDigest', 'approvalDigest', 'targetCustody',
|
|
305
|
+
'executionPolicyDigest'}
|
|
306
|
+
_object(value, keys)
|
|
307
|
+
if value['profile'] != 'umf.table-generation-ingress/0.1':
|
|
308
|
+
raise CatalogError('ingress-record-invalid')
|
|
309
|
+
for key in ('providerId', 'oldEpoch', 'newEpoch'):
|
|
310
|
+
_uuid(value[key])
|
|
311
|
+
if value['oldEpoch'] == value['newEpoch']:
|
|
312
|
+
raise CatalogError('ingress-record-invalid')
|
|
313
|
+
_uuid(value['enrollmentId'])
|
|
314
|
+
_text(value['installationId'], max_bytes=128)
|
|
315
|
+
for key in ('targetIdentityDigest', 'planDigest', 'fileDigest', 'previousSourceDigest',
|
|
316
|
+
'nextSourceDigest', 'previousBundleDigest', 'nextBundleDigest',
|
|
317
|
+
'oldPrincipalsDigest', 'newPrincipalsDigest', 'approvalDigest',
|
|
318
|
+
'executionPolicyDigest'):
|
|
319
|
+
_hex(value[key])
|
|
320
|
+
_hex(value['expectedHead'], nullable=True)
|
|
321
|
+
_validate_target_custody(value['targetCustody'])
|
|
322
|
+
_canonical_bytes(value)
|
|
323
|
+
return value
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _validate_reservation(value: Any) -> dict[str, Any]:
|
|
327
|
+
_object(value, {'profile', 'id', 'custodianId', 'registrationId', 'incarnation',
|
|
328
|
+
'sequence', 'requestDigest', 'ingressApprovalDigest', 'parentStateDigest'})
|
|
329
|
+
if value['profile'] != 'umf.native-target-reservation/0.1':
|
|
330
|
+
raise CatalogError('ingress-record-invalid')
|
|
331
|
+
for key in ('id', 'custodianId', 'registrationId', 'incarnation'):
|
|
332
|
+
_text(value[key], max_bytes=256)
|
|
333
|
+
_safe_int(value['sequence'])
|
|
334
|
+
for key in ('requestDigest', 'ingressApprovalDigest', 'parentStateDigest'):
|
|
335
|
+
_hex(value[key])
|
|
336
|
+
_canonical_bytes(value)
|
|
337
|
+
return value
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _validate_execution_policy(value: Any) -> Any:
|
|
341
|
+
_object(value, {'version', 'phaseTimeoutMs', 'aggregateAffectedRows',
|
|
342
|
+
'statementTimeoutMs', 'lockTimeoutMs', 'derivedModuleProfile'})
|
|
343
|
+
if value['version'] != 'umf.g11.execution-policy/0.1' or value['derivedModuleProfile'] != 'weft.table-operation-module/0.2':
|
|
344
|
+
raise CatalogError('ingress-record-invalid')
|
|
345
|
+
phase = _safe_int(value['phaseTimeoutMs'], 1, 300_000)
|
|
346
|
+
aggregate = _safe_int(value['aggregateAffectedRows'], 0, 1_000_000)
|
|
347
|
+
statement = _safe_int(value['statementTimeoutMs'], 1, phase)
|
|
348
|
+
_safe_int(value['lockTimeoutMs'], 1, statement)
|
|
349
|
+
try:
|
|
350
|
+
from .phase_policy import FieldReplacementExecutionPolicy
|
|
351
|
+
return FieldReplacementExecutionPolicy(
|
|
352
|
+
phase_timeout_ms=phase,
|
|
353
|
+
aggregate_affected_rows=aggregate,
|
|
354
|
+
statement_timeout_ms=statement,
|
|
355
|
+
lock_timeout_ms=value['lockTimeoutMs'])
|
|
356
|
+
except (CatalogError, TypeError):
|
|
357
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _validate_transition_record(value: Any) -> dict[str, Any]:
|
|
361
|
+
keys = {'profile', 'transitionId', 'request', 'requestDigest',
|
|
362
|
+
'ingressApprovalDigest', 'reservation', 'reservationDigest', 'state',
|
|
363
|
+
'phaseIndex', 'executionPolicy', 'fenceReceipt', 'phaseReceipt',
|
|
364
|
+
'phaseBudgetReceipt', 'publicationReceipt'}
|
|
365
|
+
_object(value, keys)
|
|
366
|
+
if value['profile'] != TRANSITION_PROFILE:
|
|
367
|
+
raise CatalogError('ingress-record-invalid')
|
|
368
|
+
_uuid(value['transitionId'])
|
|
369
|
+
_validate_request(value['request']); _validate_reservation(value['reservation'])
|
|
370
|
+
if (_digest(value['request']) != value['requestDigest']
|
|
371
|
+
or _digest(value['reservation']) != value['reservationDigest']
|
|
372
|
+
or value['reservation']['requestDigest'] != value['requestDigest']
|
|
373
|
+
or value['reservation']['ingressApprovalDigest'] != value['ingressApprovalDigest']
|
|
374
|
+
or any(value['reservation'][key] != value['request']['targetCustody'][target_key]
|
|
375
|
+
for key, target_key in (('custodianId', 'custodianId'),
|
|
376
|
+
('registrationId', 'registrationId'),
|
|
377
|
+
('incarnation', 'incarnation')))):
|
|
378
|
+
raise CatalogError('ingress-record-invalid')
|
|
379
|
+
_hex(value['requestDigest']); _hex(value['reservationDigest']); _hex(value['ingressApprovalDigest'])
|
|
380
|
+
policy = _validate_execution_policy(value['executionPolicy'])
|
|
381
|
+
if _digest(value['executionPolicy']) != value['request']['executionPolicyDigest']:
|
|
382
|
+
raise CatalogError('ingress-record-invalid')
|
|
383
|
+
state, index = value['state'], value['phaseIndex']
|
|
384
|
+
_safe_int(index, 0, 1)
|
|
385
|
+
if state not in ('prepared', 'fencing', 'fenced', 'cutover', 'published'):
|
|
386
|
+
raise CatalogError('ingress-record-invalid')
|
|
387
|
+
if (state in ('prepared', 'fencing', 'fenced') and index != 0
|
|
388
|
+
or state in ('cutover', 'published') and index != 1):
|
|
389
|
+
raise CatalogError('ingress-record-invalid')
|
|
390
|
+
for receipt in ('fenceReceipt', 'phaseReceipt', 'phaseBudgetReceipt', 'publicationReceipt'):
|
|
391
|
+
if value[receipt] is not None and type(value[receipt]) is not dict:
|
|
392
|
+
raise CatalogError('ingress-record-invalid')
|
|
393
|
+
expected_receipts = {
|
|
394
|
+
'prepared': (False, False, False, False),
|
|
395
|
+
'fencing': (False, False, False, False),
|
|
396
|
+
'fenced': (True, False, False, False),
|
|
397
|
+
'cutover': (True, True, True, False),
|
|
398
|
+
'published': (True, True, True, True),
|
|
399
|
+
}[state]
|
|
400
|
+
if tuple(value[key] is not None for key in
|
|
401
|
+
('fenceReceipt', 'phaseReceipt', 'phaseBudgetReceipt', 'publicationReceipt')) != expected_receipts:
|
|
402
|
+
raise CatalogError('ingress-record-invalid')
|
|
403
|
+
if value['phaseReceipt'] is not None:
|
|
404
|
+
phase = value['phaseReceipt']
|
|
405
|
+
_object(phase, {'migrationId', 'planDigest', 'expectedHead', 'fileDigest',
|
|
406
|
+
'phaseIndex', 'state', 'phaseDigest', 'completedSteps',
|
|
407
|
+
'prefixWitness'})
|
|
408
|
+
if (type(phase['migrationId']) is not str or not phase['migrationId']
|
|
409
|
+
or phase['planDigest'] != value['request']['planDigest']
|
|
410
|
+
or phase['expectedHead'] != value['request']['expectedHead']
|
|
411
|
+
or phase['fileDigest'] != value['request']['fileDigest']
|
|
412
|
+
or phase['phaseIndex'] != 1 or type(phase['phaseIndex']) is not int
|
|
413
|
+
or phase['state'] != 'complete'
|
|
414
|
+
or type(phase['completedSteps']) is not list
|
|
415
|
+
or type(phase['prefixWitness']) is not dict):
|
|
416
|
+
raise CatalogError('ingress-record-invalid')
|
|
417
|
+
_hex(phase['phaseDigest'])
|
|
418
|
+
for step_id in phase['completedSteps']:
|
|
419
|
+
if type(step_id) is not str or re.fullmatch(r'step-[0-9]{5}', step_id) is None:
|
|
420
|
+
raise CatalogError('ingress-record-invalid')
|
|
421
|
+
_canonical_bytes(phase)
|
|
422
|
+
if value['phaseBudgetReceipt'] is not None:
|
|
423
|
+
from .phase_policy import validate_phase_budget_receipt
|
|
424
|
+
try:
|
|
425
|
+
validate_phase_budget_receipt(value['phaseBudgetReceipt'], policy)
|
|
426
|
+
except CatalogError:
|
|
427
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
428
|
+
if value['publicationReceipt'] is not None:
|
|
429
|
+
_validate_publication_reference(value['publicationReceipt'], value['request'])
|
|
430
|
+
if value['fenceReceipt'] is not None:
|
|
431
|
+
fence = value['fenceReceipt']
|
|
432
|
+
_object(fence, {'profile', 'requestDigest', 'reservationDigest',
|
|
433
|
+
'targetObservationDigest', 'oldRolesDigest',
|
|
434
|
+
'oldMembershipsDigest', 'affectedAclsDigest',
|
|
435
|
+
'barrierCandidates', 'retiredSessions', 'catalogSide'})
|
|
436
|
+
if (fence['profile'] != 'umf.native-ingress-fence/0.1'
|
|
437
|
+
or fence['requestDigest'] != value['requestDigest']
|
|
438
|
+
or fence['reservationDigest'] != value['reservationDigest']
|
|
439
|
+
or fence['catalogSide'] not in ('previous', 'next')):
|
|
440
|
+
raise CatalogError('ingress-record-invalid')
|
|
441
|
+
for key in ('targetObservationDigest', 'oldRolesDigest',
|
|
442
|
+
'oldMembershipsDigest', 'affectedAclsDigest'):
|
|
443
|
+
_hex(fence[key])
|
|
444
|
+
_validate_fence_rows(fence['barrierCandidates'], barrier=True)
|
|
445
|
+
_validate_fence_rows(fence['retiredSessions'], barrier=False)
|
|
446
|
+
_canonical_bytes(value)
|
|
447
|
+
return value
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _validate_publication_reference(value: Any, request: dict[str, Any]) -> None:
|
|
451
|
+
keys = {'version', 'bundleDigest', 'sourceDigest', 'configurationDigest',
|
|
452
|
+
'generation', 'headDigest', 'planDigest', 'headRelationOid',
|
|
453
|
+
'headShape', 'nativeWitness', 'historyShape', 'referenceDigest',
|
|
454
|
+
'outcomeShape', 'approvalProfile', 'approvalPlanDigest', 'approvalShape'}
|
|
455
|
+
_object(value, keys)
|
|
456
|
+
_canonical_bytes(value)
|
|
457
|
+
checked = dict(value)
|
|
458
|
+
reference_digest = checked.pop('referenceDigest')
|
|
459
|
+
if (value['version'] != 'umf.table-installation/0.3'
|
|
460
|
+
or _digest(checked) != reference_digest
|
|
461
|
+
or value['bundleDigest'] != request['nextBundleDigest']
|
|
462
|
+
or value['sourceDigest'] != request['nextSourceDigest']
|
|
463
|
+
or value['planDigest'] != request['planDigest']
|
|
464
|
+
or value['approvalPlanDigest'] != request['planDigest']
|
|
465
|
+
or value['approvalProfile'] != {'version': 'umf.table-migration-approval/0.1',
|
|
466
|
+
'relation': 'umf_lifecycle_approvals',
|
|
467
|
+
'ownerOnly': True}
|
|
468
|
+
or type(value['generation']) is not int or not 1 <= value['generation'] <= 128
|
|
469
|
+
or type(value['headRelationOid']) is not int or not 1 <= value['headRelationOid'] < 2**32
|
|
470
|
+
or type(value['headShape']) is not dict
|
|
471
|
+
or type(value['nativeWitness']) is not dict
|
|
472
|
+
or type(value['historyShape']) is not dict
|
|
473
|
+
or type(value['outcomeShape']) is not dict
|
|
474
|
+
or type(value['approvalShape']) is not dict):
|
|
475
|
+
raise CatalogError('ingress-record-invalid')
|
|
476
|
+
for key in ('configurationDigest', 'headDigest', 'planDigest',
|
|
477
|
+
'approvalPlanDigest', 'referenceDigest'):
|
|
478
|
+
_hex(value[key])
|
|
479
|
+
from .head import _checked_reference
|
|
480
|
+
try:
|
|
481
|
+
_checked_reference(value, {
|
|
482
|
+
'bundleDigest': request['nextBundleDigest'],
|
|
483
|
+
'sourceDigest': request['nextSourceDigest'],
|
|
484
|
+
'configurationDigest': value['configurationDigest'],
|
|
485
|
+
})
|
|
486
|
+
except CatalogError:
|
|
487
|
+
raise CatalogError('ingress-record-invalid') from None
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _validate_fence_rows(value: Any, *, barrier: bool) -> None:
|
|
491
|
+
if type(value) is not list or len(value) > 4096:
|
|
492
|
+
raise CatalogError('ingress-record-invalid')
|
|
493
|
+
keys = {'pid', 'backendStart', 'databaseOid', 'loginOid', 'state'} if barrier else {
|
|
494
|
+
'pid', 'backendStart', 'databaseOid', 'loginOid', 'outcome'}
|
|
495
|
+
seen: set[tuple[Any, Any]] = set()
|
|
496
|
+
for row in value:
|
|
497
|
+
_object(row, keys)
|
|
498
|
+
_safe_int(row['pid'], 1, 2**31 - 1)
|
|
499
|
+
_text(row['backendStart'], max_bytes=64)
|
|
500
|
+
for key in ('databaseOid', 'loginOid'):
|
|
501
|
+
if row[key] is not None:
|
|
502
|
+
_safe_int(row[key], 1, 2**32 - 1)
|
|
503
|
+
if barrier:
|
|
504
|
+
_text(row['state'], max_bytes=64)
|
|
505
|
+
if row['state'] != 'starting' and (row['databaseOid'] is None or row['loginOid'] is None):
|
|
506
|
+
raise CatalogError('ingress-record-invalid')
|
|
507
|
+
elif row['outcome'] not in ('terminated', 'already-exited'):
|
|
508
|
+
raise CatalogError('ingress-record-invalid')
|
|
509
|
+
token = (row['pid'], row['backendStart'])
|
|
510
|
+
if token in seen:
|
|
511
|
+
raise CatalogError('ingress-record-invalid')
|
|
512
|
+
seen.add(token)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _record_target(record: dict[str, Any]) -> tuple[str, str]:
|
|
516
|
+
if record['profile'] == EPOCH_PROFILE:
|
|
517
|
+
return record['providerId'], record['installationId']
|
|
518
|
+
request = record['request']
|
|
519
|
+
return request['providerId'], request['installationId']
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _record_columns(record: dict[str, Any]) -> tuple[Any, ...]:
|
|
523
|
+
if record['profile'] == EPOCH_PROFILE:
|
|
524
|
+
return (record['providerId'], record['installationId'], record['epoch'],
|
|
525
|
+
record['state'], record['sourceDigest'], record['bundleDigest'],
|
|
526
|
+
record['headDigest'], record['principalsDigest'],
|
|
527
|
+
record['custodySequence'])
|
|
528
|
+
request = record['request']
|
|
529
|
+
return (record['transitionId'], request['providerId'], request['installationId'],
|
|
530
|
+
request['oldEpoch'], request['newEpoch'],
|
|
531
|
+
record['requestDigest'], record['reservationDigest'], record['state'],
|
|
532
|
+
record['phaseIndex'])
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _validate_store_record(record: Any, expected_profile: str) -> tuple[dict[str, Any], str]:
|
|
536
|
+
if expected_profile == EPOCH_PROFILE:
|
|
537
|
+
checked = _validate_epoch_record(record)
|
|
538
|
+
elif expected_profile == TRANSITION_PROFILE:
|
|
539
|
+
checked = _validate_transition_record(record)
|
|
540
|
+
else:
|
|
541
|
+
raise CatalogError('ingress-record-invalid')
|
|
542
|
+
return checked, _digest(checked)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _create_table(connection: Any, schema: str, name: str,
|
|
546
|
+
columns: list[str], constraints: list[tuple[str, str]],
|
|
547
|
+
aliases: dict[str, str], *, foreign_keys: bool = False) -> None:
|
|
548
|
+
definitions = list(columns)
|
|
549
|
+
for constraint, body in constraints:
|
|
550
|
+
actual = constraint if name in ('epochs', 'transitions') else 'umf_verify_' + uuid.uuid4().hex
|
|
551
|
+
aliases[actual] = constraint
|
|
552
|
+
if foreign_keys and '{schema}' in body:
|
|
553
|
+
body = body.format(schema=_q(schema))
|
|
554
|
+
definitions.append('CONSTRAINT ' + _q(actual) + ' ' + body)
|
|
555
|
+
_execute(connection, 'CREATE TABLE ' + _q(schema) + '.' + _q(name)
|
|
556
|
+
+ ' (' + ', '.join(definitions) + ') USING heap')
|
|
557
|
+
if not foreign_keys and columns == _EPOCH_COLUMNS:
|
|
558
|
+
index_name = 'ingress_epochs_one_active'
|
|
559
|
+
if name != 'epochs':
|
|
560
|
+
# Scratch relations use a unique physical name, but normalize
|
|
561
|
+
# their parsed index back to the frozen profile name.
|
|
562
|
+
index_name = 'umf_verify_' + uuid.uuid4().hex
|
|
563
|
+
aliases[index_name] = 'ingress_epochs_one_active'
|
|
564
|
+
_execute(connection, 'CREATE UNIQUE INDEX ' + _q(index_name) + ' ON '
|
|
565
|
+
+ _q(schema) + '.' + _q(name)
|
|
566
|
+
+ ' ("provider_id","installation_id") WHERE "state" = \'active\'')
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _expected_schema_name(provider_id: str) -> str:
|
|
570
|
+
parsed = _uuid(provider_id)
|
|
571
|
+
return 'umf_ingress_' + parsed.replace('-', '')
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _literal(value: str) -> str:
|
|
575
|
+
"""Quote a validated internal literal for a PostgreSQL utility command."""
|
|
576
|
+
if type(value) is not str or '\x00' in value:
|
|
577
|
+
raise CatalogError('ingress-record-invalid')
|
|
578
|
+
return "'" + value.replace("'", "''") + "'"
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _verify_relation_side_objects(connection: Any, schema: str, table: str,
|
|
582
|
+
expected_column_count: int) -> None:
|
|
583
|
+
attributes = _all(connection, """SELECT a.attnum,a.attisdropped
|
|
584
|
+
FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
|
|
585
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
586
|
+
WHERE n.nspname=%s AND c.relname=%s AND a.attnum>0 ORDER BY a.attnum""",
|
|
587
|
+
(schema, table))
|
|
588
|
+
if attributes != [(number, False) for number in range(1, expected_column_count + 1)]:
|
|
589
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
590
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_trigger t
|
|
591
|
+
JOIN pg_catalog.pg_class c ON c.oid=t.tgrelid
|
|
592
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
593
|
+
WHERE n.nspname=%s AND c.relname=%s AND NOT t.tgisinternal""",
|
|
594
|
+
(schema, table)) != (0,):
|
|
595
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
596
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_policy p
|
|
597
|
+
JOIN pg_catalog.pg_class c ON c.oid=p.polrelid
|
|
598
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
599
|
+
WHERE n.nspname=%s AND c.relname=%s""", (schema, table)) != (0,):
|
|
600
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
@dataclass(frozen=True, slots=True)
|
|
604
|
+
class _OriginalStoreCreationAuthority:
|
|
605
|
+
"""Opaque binding to original custody and its native maintenance actor.
|
|
606
|
+
|
|
607
|
+
Production issuance is deliberately absent until the native owner adapter
|
|
608
|
+
can authorize principal preparation and exact store creation. The journal
|
|
609
|
+
registration alone proves target continuity, not PostgreSQL role authority.
|
|
610
|
+
"""
|
|
611
|
+
|
|
612
|
+
provider_id: str
|
|
613
|
+
installation_id: str
|
|
614
|
+
custodian: object
|
|
615
|
+
verified_target: object
|
|
616
|
+
target_handle: object
|
|
617
|
+
target_custody: object
|
|
618
|
+
schema_oid: int | None
|
|
619
|
+
registration_digest: str
|
|
620
|
+
authority_preparation_receipt_digest: str
|
|
621
|
+
creation_approval_digest: str
|
|
622
|
+
target_custody_digest: str
|
|
623
|
+
maintenance_user: str
|
|
624
|
+
maintenance_user_oid: int
|
|
625
|
+
controller_role: str
|
|
626
|
+
controller_oid: int
|
|
627
|
+
business_owner: str
|
|
628
|
+
business_owner_oid: int
|
|
629
|
+
# Flags in role order maintenance/controller/business owner, each in
|
|
630
|
+
# canLogin, superuser, createDatabase, createRole, replication, bypassRls,
|
|
631
|
+
# inherit order.
|
|
632
|
+
principal_flags: tuple[tuple[bool, ...], tuple[bool, ...], tuple[bool, ...]]
|
|
633
|
+
# Sorted tuples (member oid, role oid, inherit, set, admin).
|
|
634
|
+
# This is the complete native SET-reachable membership closure observed
|
|
635
|
+
# at original enrollment, not a caller-selected role name.
|
|
636
|
+
membership_observations: tuple[tuple[int, int, bool, bool, bool], ...]
|
|
637
|
+
required_settings: tuple[tuple[str, str], ...]
|
|
638
|
+
database_name: str
|
|
639
|
+
database_system_identifier: str
|
|
640
|
+
native_authority_observation_digest: str
|
|
641
|
+
_seal: object
|
|
642
|
+
|
|
643
|
+
def __post_init__(self) -> None:
|
|
644
|
+
if self._seal is not _CAPABILITY_SEAL:
|
|
645
|
+
raise TypeError('original store creation authority is provider-issued')
|
|
646
|
+
from .ingress_custody import (
|
|
647
|
+
CustodyJournalError,
|
|
648
|
+
LocalTargetCustodian,
|
|
649
|
+
_VerifiedTargetCustody,
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
if (type(self.custodian) is not LocalTargetCustodian
|
|
653
|
+
or type(self.verified_target) is not _VerifiedTargetCustody
|
|
654
|
+
or self.verified_target.custodian is not self.custodian):
|
|
655
|
+
raise CatalogError('ingress-store-custody-required')
|
|
656
|
+
try:
|
|
657
|
+
if self.custodian._resolve_target_custody(self.target_handle) is not self.verified_target:
|
|
658
|
+
raise CatalogError('ingress-store-custody-mismatch')
|
|
659
|
+
reference = self.custodian._public_reference(self.target_handle)
|
|
660
|
+
except (AttributeError, TypeError, CustodyJournalError):
|
|
661
|
+
raise CatalogError('ingress-store-custody-required') from None
|
|
662
|
+
if type(self.target_custody) is not dict or reference != self.target_custody:
|
|
663
|
+
raise CatalogError('ingress-store-custody-mismatch')
|
|
664
|
+
_validate_target_custody(self.target_custody)
|
|
665
|
+
_uuid(self.provider_id)
|
|
666
|
+
_text(self.installation_id, max_bytes=128)
|
|
667
|
+
if self.schema_oid is not None:
|
|
668
|
+
_safe_int(self.schema_oid, 1, 2**32 - 1)
|
|
669
|
+
for digest in (self.registration_digest, self.authority_preparation_receipt_digest,
|
|
670
|
+
self.creation_approval_digest, self.target_custody_digest,
|
|
671
|
+
self.native_authority_observation_digest):
|
|
672
|
+
_hex(digest)
|
|
673
|
+
if self.target_custody_digest != _digest(self.target_custody):
|
|
674
|
+
raise CatalogError('ingress-record-invalid')
|
|
675
|
+
_text(self.maintenance_user, max_bytes=63)
|
|
676
|
+
_safe_int(self.maintenance_user_oid, 1, 2**32 - 1)
|
|
677
|
+
_text(self.controller_role, max_bytes=63)
|
|
678
|
+
_safe_int(self.controller_oid, 1, 2**32 - 1)
|
|
679
|
+
_text(self.business_owner, max_bytes=63)
|
|
680
|
+
_safe_int(self.business_owner_oid, 1, 2**32 - 1)
|
|
681
|
+
principals = ((self.maintenance_user_oid, self.maintenance_user),
|
|
682
|
+
(self.controller_oid, self.controller_role),
|
|
683
|
+
(self.business_owner_oid, self.business_owner))
|
|
684
|
+
if (len({item[0] for item in principals}) != 3
|
|
685
|
+
or len({item[1] for item in principals}) != 3):
|
|
686
|
+
raise CatalogError('ingress-record-invalid')
|
|
687
|
+
if (type(self.principal_flags) is not tuple or len(self.principal_flags) != 3
|
|
688
|
+
or any(type(flags) is not tuple or len(flags) != 7
|
|
689
|
+
or any(type(flag) is not bool for flag in flags)
|
|
690
|
+
for flags in self.principal_flags)):
|
|
691
|
+
raise CatalogError('ingress-record-invalid')
|
|
692
|
+
if self.required_settings != _STORE_SETTINGS:
|
|
693
|
+
raise CatalogError('ingress-record-invalid')
|
|
694
|
+
_text(self.database_name, max_bytes=63)
|
|
695
|
+
_system_identifier(self.database_system_identifier)
|
|
696
|
+
required = ((self.maintenance_user_oid, self.controller_oid, False, True, False),
|
|
697
|
+
(self.maintenance_user_oid, self.business_owner_oid, False, True, False))
|
|
698
|
+
if (type(self.membership_observations) is not tuple
|
|
699
|
+
or len(self.membership_observations) > 4096):
|
|
700
|
+
raise CatalogError('ingress-record-invalid')
|
|
701
|
+
previous: tuple[int, int, bool, bool, bool] | None = None
|
|
702
|
+
reached = {self.maintenance_user_oid}
|
|
703
|
+
for membership in self.membership_observations:
|
|
704
|
+
if type(membership) is not tuple or len(membership) != 5:
|
|
705
|
+
raise CatalogError('ingress-record-invalid')
|
|
706
|
+
member_oid, role_oid, inherit_option, set_option, admin_option = membership
|
|
707
|
+
_safe_int(member_oid, 1, 2**32 - 1)
|
|
708
|
+
_safe_int(role_oid, 1, 2**32 - 1)
|
|
709
|
+
if any(type(option) is not bool for option in
|
|
710
|
+
(inherit_option, set_option, admin_option)):
|
|
711
|
+
raise CatalogError('ingress-record-invalid')
|
|
712
|
+
if previous is not None and membership <= previous:
|
|
713
|
+
raise CatalogError('ingress-record-invalid')
|
|
714
|
+
previous = membership
|
|
715
|
+
changed = True
|
|
716
|
+
while changed:
|
|
717
|
+
changed = False
|
|
718
|
+
for member_oid, role_oid, _inherit, set_option, _admin in self.membership_observations:
|
|
719
|
+
if member_oid in reached and set_option and role_oid not in reached:
|
|
720
|
+
reached.add(role_oid)
|
|
721
|
+
changed = True
|
|
722
|
+
direct_required = {
|
|
723
|
+
item for item in self.membership_observations
|
|
724
|
+
if item[0] == self.maintenance_user_oid and item[1] in
|
|
725
|
+
(self.controller_oid, self.business_owner_oid)
|
|
726
|
+
}
|
|
727
|
+
if (self.controller_oid not in reached or self.business_owner_oid not in reached
|
|
728
|
+
or direct_required != set(required)):
|
|
729
|
+
raise CatalogError('ingress-controller-set-membership-required')
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
@dataclass(frozen=True, slots=True)
|
|
733
|
+
class _PhaseTransactionBinding:
|
|
734
|
+
"""Private lease binding for one host business-owner physical transaction."""
|
|
735
|
+
|
|
736
|
+
connection: Any
|
|
737
|
+
provider_id: str
|
|
738
|
+
installation_id: str
|
|
739
|
+
target_identity_digest: str
|
|
740
|
+
session_user: str
|
|
741
|
+
session_user_oid: int
|
|
742
|
+
business_owner: str
|
|
743
|
+
business_owner_oid: int
|
|
744
|
+
database_oid: int
|
|
745
|
+
_seal: object
|
|
746
|
+
_invalidated: bool = False
|
|
747
|
+
|
|
748
|
+
def __post_init__(self) -> None:
|
|
749
|
+
if self._seal is not _CAPABILITY_SEAL:
|
|
750
|
+
raise TypeError('phase transaction binding is host-issued')
|
|
751
|
+
_uuid(self.provider_id); _text(self.installation_id, max_bytes=256)
|
|
752
|
+
_hex(self.target_identity_digest)
|
|
753
|
+
_text(self.session_user, max_bytes=63); _text(self.business_owner, max_bytes=63)
|
|
754
|
+
_safe_int(self.session_user_oid, 1, 2**32 - 1)
|
|
755
|
+
_safe_int(self.business_owner_oid, 1, 2**32 - 1)
|
|
756
|
+
_safe_int(self.database_oid, 1, 2**32 - 1)
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def _bind_phase_transaction(connection: Any, *, provider_id: str,
|
|
760
|
+
installation_id: str, target_identity_digest: str,
|
|
761
|
+
session_user: str, session_user_oid: int, business_owner: str,
|
|
762
|
+
business_owner_oid: int, database_oid: int) -> _PhaseTransactionBinding:
|
|
763
|
+
"""Private host hook; possession alone never substitutes for DB checks."""
|
|
764
|
+
return _PhaseTransactionBinding(connection, provider_id, installation_id,
|
|
765
|
+
target_identity_digest, session_user,
|
|
766
|
+
session_user_oid, business_owner, business_owner_oid,
|
|
767
|
+
database_oid, _CAPABILITY_SEAL)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
class PgGenerationIngressStore:
|
|
771
|
+
"""Fixed source-side adapter; does not establish issuer/custodian authority."""
|
|
772
|
+
|
|
773
|
+
__slots__ = (
|
|
774
|
+
'_connection',
|
|
775
|
+
'_custodian',
|
|
776
|
+
'_custody',
|
|
777
|
+
'_schema_oid',
|
|
778
|
+
'_target_handle',
|
|
779
|
+
'controller_oid',
|
|
780
|
+
'controller_role',
|
|
781
|
+
'database_name',
|
|
782
|
+
'database_oid',
|
|
783
|
+
'database_system_identifier',
|
|
784
|
+
'installation_id',
|
|
785
|
+
'provider_id',
|
|
786
|
+
'schema',
|
|
787
|
+
)
|
|
788
|
+
|
|
789
|
+
def __init__(self, controller_connection: Any, *, provider_id: str,
|
|
790
|
+
installation_id: str, controller_role: str,
|
|
791
|
+
controller_oid: int, database_oid: int,
|
|
792
|
+
custodian: Any, target_custody: Any,
|
|
793
|
+
creation_authority: _OriginalStoreCreationAuthority):
|
|
794
|
+
if (type(creation_authority) is not _OriginalStoreCreationAuthority
|
|
795
|
+
or creation_authority.provider_id != provider_id
|
|
796
|
+
or creation_authority.custodian is not custodian
|
|
797
|
+
or creation_authority.target_handle is not target_custody):
|
|
798
|
+
raise CatalogError('ingress-store-custody-required')
|
|
799
|
+
from .ingress_custody import CustodyJournalError, LocalTargetCustodian
|
|
800
|
+
|
|
801
|
+
if type(custodian) is not LocalTargetCustodian:
|
|
802
|
+
raise CatalogError('ingress-store-custody-required')
|
|
803
|
+
try:
|
|
804
|
+
verified = custodian._resolve_target_custody(target_custody)
|
|
805
|
+
public_reference = custodian._public_reference(target_custody)
|
|
806
|
+
except CustodyJournalError:
|
|
807
|
+
raise CatalogError('ingress-store-custody-required') from None
|
|
808
|
+
if (verified is not creation_authority.verified_target
|
|
809
|
+
or public_reference != creation_authority.target_custody):
|
|
810
|
+
raise CatalogError('ingress-store-custody-mismatch')
|
|
811
|
+
self._connection = controller_connection
|
|
812
|
+
self.provider_id = _uuid(provider_id)
|
|
813
|
+
self.installation_id = _text(installation_id, max_bytes=256)
|
|
814
|
+
self.schema = _expected_schema_name(provider_id)
|
|
815
|
+
self.controller_role = _text(controller_role, max_bytes=63)
|
|
816
|
+
self.controller_oid = _safe_int(controller_oid, 1, 2**32 - 1)
|
|
817
|
+
self.database_oid = _safe_int(database_oid, 1, 2**32 - 1)
|
|
818
|
+
self.database_name = creation_authority.database_name
|
|
819
|
+
self.database_system_identifier = creation_authority.database_system_identifier
|
|
820
|
+
self._custody = creation_authority
|
|
821
|
+
self._custodian = custodian
|
|
822
|
+
self._target_handle = target_custody
|
|
823
|
+
self._schema_oid = creation_authority.schema_oid
|
|
824
|
+
if (creation_authority.installation_id != installation_id
|
|
825
|
+
or creation_authority.controller_role != self.controller_role
|
|
826
|
+
or creation_authority.controller_oid != self.controller_oid):
|
|
827
|
+
raise CatalogError('ingress-store-custody-mismatch')
|
|
828
|
+
|
|
829
|
+
def create_original_store(self) -> int:
|
|
830
|
+
"""Create once under original custody; never adopts by name or shape."""
|
|
831
|
+
if self._custody.schema_oid is not None:
|
|
832
|
+
raise CatalogError('ingress-store-already-created')
|
|
833
|
+
self._require_active_transaction(self._connection)
|
|
834
|
+
self._verify_controller_session()
|
|
835
|
+
if _one(self._connection, 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s',
|
|
836
|
+
(self.schema,)) is not None:
|
|
837
|
+
raise CatalogError('ingress-store-custody-conflict')
|
|
838
|
+
_execute(self._connection, 'CREATE SCHEMA ' + _q(self.schema)
|
|
839
|
+
+ ' AUTHORIZATION ' + _q(self.controller_role))
|
|
840
|
+
_execute(self._connection, 'COMMENT ON SCHEMA ' + _q(self.schema) + ' IS '
|
|
841
|
+
+ _literal(_SCHEMA_MARKER_PREFIX + self.provider_id))
|
|
842
|
+
aliases: dict[str, str] = {}
|
|
843
|
+
_create_table(self._connection, self.schema, 'epochs', _EPOCH_COLUMNS,
|
|
844
|
+
_EPOCH_CONSTRAINTS, aliases)
|
|
845
|
+
_create_table(self._connection, self.schema, 'transitions', _TRANSITION_COLUMNS,
|
|
846
|
+
_TRANSITION_CONSTRAINTS, aliases, foreign_keys=True)
|
|
847
|
+
schema_oid = _one(self._connection,
|
|
848
|
+
'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s',
|
|
849
|
+
(self.schema,))
|
|
850
|
+
if schema_oid is None:
|
|
851
|
+
raise CatalogError('ingress-store-create-unobserved')
|
|
852
|
+
self._schema_oid = int(schema_oid[0])
|
|
853
|
+
self._verify_store_shape(self._schema_oid, self._connection)
|
|
854
|
+
return self._schema_oid
|
|
855
|
+
|
|
856
|
+
def verify_original_store(self) -> None:
|
|
857
|
+
"""Verify only the externally pinned original schema incarnation."""
|
|
858
|
+
expected_oid = self._schema_oid
|
|
859
|
+
if expected_oid is None:
|
|
860
|
+
raise CatalogError('ingress-store-custody-required')
|
|
861
|
+
self._verify_controller_session()
|
|
862
|
+
row = _one(self._connection,
|
|
863
|
+
'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s',
|
|
864
|
+
(self.schema,))
|
|
865
|
+
if row is None or row[0] != expected_oid:
|
|
866
|
+
raise CatalogError('ingress-store-custody-mismatch')
|
|
867
|
+
self._require_active_transaction(self._connection)
|
|
868
|
+
self._verify_store_shape(expected_oid, self._connection)
|
|
869
|
+
|
|
870
|
+
def _verify_controller_session(self, connection: Any | None = None) -> None:
|
|
871
|
+
connection = self._connection if connection is None else connection
|
|
872
|
+
state = _one(connection, """SELECT c.oid,
|
|
873
|
+
current_user,(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=current_user),
|
|
874
|
+
session_user,
|
|
875
|
+
(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=session_user),
|
|
876
|
+
pg_catalog.current_setting('role'),
|
|
877
|
+
pg_catalog.current_setting('search_path'),pg_catalog.current_setting('TimeZone'),
|
|
878
|
+
pg_catalog.current_setting('row_security'),pg_catalog.current_setting('session_replication_role'),
|
|
879
|
+
pg_catalog.current_setting('server_encoding'),pg_catalog.current_setting('transaction_read_only'),
|
|
880
|
+
pg_catalog.current_setting('transaction_isolation'),
|
|
881
|
+
pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
|
|
882
|
+
c.datname,(SELECT system_identifier FROM pg_catalog.pg_control_system())
|
|
883
|
+
FROM pg_catalog.pg_database c
|
|
884
|
+
WHERE c.datname=pg_catalog.current_database()""")
|
|
885
|
+
if (state is None or state[0] != self.database_oid
|
|
886
|
+
or state[1] != self.controller_role or state[2] != self.controller_oid
|
|
887
|
+
or state[3] != self._custody.maintenance_user
|
|
888
|
+
or state[4] != self._custody.maintenance_user_oid
|
|
889
|
+
or state[5] != self.controller_role
|
|
890
|
+
or state[6:13] != tuple(value for _name, value in _STORE_SETTINGS)
|
|
891
|
+
or state[13] != 180006 or state[14] != self.database_name
|
|
892
|
+
or str(state[15]) != self.database_system_identifier
|
|
893
|
+
or self._set_membership_snapshot(connection, state[4])
|
|
894
|
+
!= self._custody.membership_observations):
|
|
895
|
+
raise CatalogError('ingress-store-controller-required')
|
|
896
|
+
self._verify_principal_observations(connection)
|
|
897
|
+
|
|
898
|
+
def _verify_principal_observations(self, connection: Any) -> None:
|
|
899
|
+
expected = (
|
|
900
|
+
(self._custody.maintenance_user_oid, self._custody.maintenance_user,
|
|
901
|
+
self._custody.principal_flags[0]),
|
|
902
|
+
(self.controller_oid, self.controller_role, self._custody.principal_flags[1]),
|
|
903
|
+
(self._custody.business_owner_oid, self._custody.business_owner,
|
|
904
|
+
self._custody.principal_flags[2]),
|
|
905
|
+
)
|
|
906
|
+
rows = _all(connection, """SELECT oid,rolname,rolcanlogin,rolsuper,rolcreatedb,
|
|
907
|
+
rolcreaterole,rolreplication,rolbypassrls,rolinherit
|
|
908
|
+
FROM pg_catalog.pg_roles WHERE oid = ANY(%s::pg_catalog.oid[])""",
|
|
909
|
+
([item[0] for item in expected],))
|
|
910
|
+
actual = {(row[0], row[1]): tuple(row[2:]) for row in rows}
|
|
911
|
+
if len(rows) != 3 or any(actual.get((oid, name)) != flags
|
|
912
|
+
for oid, name, flags in expected):
|
|
913
|
+
raise CatalogError('ingress-store-principal-mismatch')
|
|
914
|
+
|
|
915
|
+
@staticmethod
|
|
916
|
+
def _set_membership_snapshot(connection: Any, member_oid: int
|
|
917
|
+
) -> tuple[tuple[int, int, int, bool, bool, bool], ...]:
|
|
918
|
+
"""Read the complete SET-reachable native role-membership closure."""
|
|
919
|
+
rows = _all(connection, """WITH RECURSIVE reachable(role_oid, path) AS (
|
|
920
|
+
SELECT %s::pg_catalog.oid, ARRAY[%s::pg_catalog.oid]
|
|
921
|
+
UNION ALL
|
|
922
|
+
SELECT m.roleid, reachable.path || m.roleid
|
|
923
|
+
FROM reachable JOIN pg_catalog.pg_auth_members m ON m.member=reachable.role_oid
|
|
924
|
+
WHERE m.set_option AND NOT m.roleid=ANY(reachable.path)
|
|
925
|
+
), edges AS (
|
|
926
|
+
SELECT m.member,m.roleid,m.inherit_option,m.set_option,m.admin_option
|
|
927
|
+
FROM pg_catalog.pg_auth_members m
|
|
928
|
+
WHERE m.member IN (SELECT role_oid FROM reachable)
|
|
929
|
+
)
|
|
930
|
+
SELECT member,roleid,inherit_option,set_option,admin_option
|
|
931
|
+
FROM edges ORDER BY member,roleid""", (member_oid, member_oid))
|
|
932
|
+
if len(rows) > 4096:
|
|
933
|
+
raise CatalogError('ingress-record-capacity')
|
|
934
|
+
result: list[tuple[int, int, int, bool, bool, bool]] = []
|
|
935
|
+
for row in rows:
|
|
936
|
+
if (len(row) != 5 or any(type(value) is not int for value in row[:2])
|
|
937
|
+
or any(type(value) is not bool for value in row[2:])):
|
|
938
|
+
raise CatalogError('ingress-record-invalid')
|
|
939
|
+
result.append(tuple(row)) # type: ignore[arg-type]
|
|
940
|
+
return tuple(result)
|
|
941
|
+
|
|
942
|
+
def _verify_store_shape(self, schema_oid: int, connection: Any) -> None:
|
|
943
|
+
schema_state = _one(connection, """SELECT n.oid,n.nspowner,r.rolname,
|
|
944
|
+
pg_catalog.obj_description(n.oid,'pg_namespace'),n.nspacl
|
|
945
|
+
FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_roles r ON r.oid=n.nspowner
|
|
946
|
+
WHERE n.nspname=%s""", (self.schema,))
|
|
947
|
+
if (schema_state is None or schema_state[0] != schema_oid
|
|
948
|
+
or schema_state[1] != self.controller_oid
|
|
949
|
+
or schema_state[2] != self.controller_role
|
|
950
|
+
or schema_state[3] != _SCHEMA_MARKER_PREFIX + self.provider_id):
|
|
951
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
952
|
+
expected_relations = {
|
|
953
|
+
'epochs', 'transitions', 'ingress_epochs_pk', 'ingress_epochs_one_active',
|
|
954
|
+
'ingress_transitions_pk', 'ingress_transitions_request',
|
|
955
|
+
'ingress_transitions_reservation',
|
|
956
|
+
}
|
|
957
|
+
rows = _all(connection, """SELECT c.relname,c.relkind,c.relpersistence,
|
|
958
|
+
r.oid,r.rolname,c.relrowsecurity,c.relforcerowsecurity,c.relispartition,
|
|
959
|
+
c.relhassubclass,c.relhasrules,c.relreplident
|
|
960
|
+
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_roles r ON r.oid=c.relowner
|
|
961
|
+
WHERE c.relnamespace=%s ORDER BY c.relname""", (schema_oid,))
|
|
962
|
+
if {row[0] for row in rows} != expected_relations:
|
|
963
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
964
|
+
for row in rows:
|
|
965
|
+
if (row[2] != 'p' or row[3] != self.controller_oid
|
|
966
|
+
or row[4] != self.controller_role or row[5:11] != (False, False, False, False, False, 'd')):
|
|
967
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
968
|
+
expected_kind = 'r' if row[0] in ('epochs', 'transitions') else 'i'
|
|
969
|
+
if row[1] != expected_kind:
|
|
970
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
971
|
+
self._verify_acl(schema_oid, connection)
|
|
972
|
+
for name, columns, constraints, foreign_keys in (
|
|
973
|
+
('epochs', _EPOCH_COLUMNS, _EPOCH_CONSTRAINTS, False),
|
|
974
|
+
('transitions', _TRANSITION_COLUMNS, _TRANSITION_CONSTRAINTS, True)):
|
|
975
|
+
self._verify_relation(connection, name, columns, constraints, foreign_keys)
|
|
976
|
+
|
|
977
|
+
def _verify_acl(self, schema_oid: int, connection: Any) -> None:
|
|
978
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_roles r
|
|
979
|
+
WHERE r.oid NOT IN (%s,%s,%s) AND (
|
|
980
|
+
pg_catalog.pg_has_role(r.oid,%s,'SET') OR
|
|
981
|
+
pg_catalog.pg_has_role(r.oid,%s,'SET'))""",
|
|
982
|
+
(self._custody.maintenance_user_oid, self.controller_oid,
|
|
983
|
+
self._custody.business_owner_oid, self.controller_oid,
|
|
984
|
+
self._custody.business_owner_oid)) != (0,):
|
|
985
|
+
raise CatalogError('ingress-store-role-reachability-mismatch')
|
|
986
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_namespace n,
|
|
987
|
+
LATERAL pg_catalog.aclexplode(COALESCE(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) a
|
|
988
|
+
WHERE n.oid=%s AND a.grantee<>n.nspowner""", (schema_oid,)) != (0,):
|
|
989
|
+
raise CatalogError('ingress-store-privilege-mismatch')
|
|
990
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_class c,
|
|
991
|
+
LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) a
|
|
992
|
+
WHERE c.relnamespace=%s AND a.grantee<>c.relowner""", (schema_oid,)) != (0,):
|
|
993
|
+
raise CatalogError('ingress-store-privilege-mismatch')
|
|
994
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_attribute a,
|
|
995
|
+
LATERAL pg_catalog.aclexplode(a.attacl) x JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
|
|
996
|
+
WHERE c.relnamespace=%s""", (schema_oid,)) != (0,):
|
|
997
|
+
raise CatalogError('ingress-store-privilege-mismatch')
|
|
998
|
+
if _one(connection, """SELECT count(*) FROM pg_catalog.pg_roles r
|
|
999
|
+
WHERE NOT r.rolsuper AND r.oid<>%s AND (
|
|
1000
|
+
pg_catalog.has_schema_privilege(r.oid,%s,'USAGE') OR
|
|
1001
|
+
pg_catalog.has_schema_privilege(r.oid,%s,'CREATE') OR EXISTS (
|
|
1002
|
+
SELECT 1 FROM pg_catalog.pg_class c WHERE c.relnamespace=%s AND (
|
|
1003
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'SELECT') OR
|
|
1004
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'INSERT') OR
|
|
1005
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'UPDATE') OR
|
|
1006
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'DELETE') OR
|
|
1007
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'TRUNCATE') OR
|
|
1008
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'REFERENCES') OR
|
|
1009
|
+
pg_catalog.has_table_privilege(r.oid,c.oid,'TRIGGER'))))""",
|
|
1010
|
+
(self.controller_oid, self.schema, self.schema, schema_oid)) != (0,):
|
|
1011
|
+
raise CatalogError('ingress-store-privilege-mismatch')
|
|
1012
|
+
|
|
1013
|
+
def _verify_relation(self, connection: Any, name: str, columns: list[str],
|
|
1014
|
+
constraints: list[tuple[str, str]], foreign_keys: bool) -> None:
|
|
1015
|
+
actual_columns = _columns(connection, self.schema, name)
|
|
1016
|
+
_verify_relation_side_objects(connection, self.schema, name, len(columns))
|
|
1017
|
+
# Create the reference in a SAVEPOINT-local unique relation name, then
|
|
1018
|
+
# compare parsed native descriptors instead of trusting DDL strings.
|
|
1019
|
+
temporary = 'umf_verify_' + uuid.uuid4().hex
|
|
1020
|
+
aliases: dict[str, str] = {}
|
|
1021
|
+
_create_table(connection, self.schema, temporary, columns,
|
|
1022
|
+
constraints, aliases, foreign_keys=foreign_keys)
|
|
1023
|
+
try:
|
|
1024
|
+
if (actual_columns != _columns(connection, self.schema, temporary)
|
|
1025
|
+
or _constraint_shapes(connection, self.schema, name, {})
|
|
1026
|
+
!= _constraint_shapes(connection, self.schema, temporary, aliases)
|
|
1027
|
+
or _index_shapes(connection, self.schema, name, {})
|
|
1028
|
+
!= _index_shapes(connection, self.schema, temporary, aliases)):
|
|
1029
|
+
raise CatalogError('ingress-store-catalog-mismatch')
|
|
1030
|
+
finally:
|
|
1031
|
+
_execute(connection, 'DROP TABLE ' + _q(self.schema) + '.' + _q(temporary) + ' CASCADE')
|
|
1032
|
+
|
|
1033
|
+
def insert_epoch(self, record: dict[str, Any]) -> None:
|
|
1034
|
+
checked, digest = _validate_store_record(record, EPOCH_PROFILE)
|
|
1035
|
+
if checked['providerId'] != self.provider_id or checked['installationId'] != self.installation_id:
|
|
1036
|
+
raise CatalogError('ingress-record-target-mismatch')
|
|
1037
|
+
if (checked['state'] not in ('prepared', 'active')
|
|
1038
|
+
or checked['targetCustody'] != self._custody.target_custody):
|
|
1039
|
+
raise CatalogError('ingress-epoch-initial-state-invalid')
|
|
1040
|
+
self.verify_original_store()
|
|
1041
|
+
count, maximum = _one(self._connection, 'SELECT count(*),COALESCE(max(custody_sequence),0) FROM '
|
|
1042
|
+
+ _q(self.schema) + '."epochs" WHERE provider_id=%s AND installation_id=%s',
|
|
1043
|
+
(self.provider_id, self.installation_id))
|
|
1044
|
+
if count >= 4096 or checked['custodySequence'] <= maximum:
|
|
1045
|
+
raise CatalogError('ingress-history-capacity-or-order')
|
|
1046
|
+
from psycopg.types.json import Jsonb
|
|
1047
|
+
columns = _record_columns(checked)
|
|
1048
|
+
result = _one(self._connection, 'INSERT INTO ' + _q(self.schema) + '."epochs" '
|
|
1049
|
+
'(provider_id,installation_id,epoch,state,source_digest,bundle_digest,head_digest,principals_digest,custody_sequence,record,record_digest) '
|
|
1050
|
+
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING epoch',
|
|
1051
|
+
(*columns, Jsonb(checked), digest))
|
|
1052
|
+
if result != (checked['epoch'],):
|
|
1053
|
+
raise CatalogError('ingress-record-write-failed')
|
|
1054
|
+
|
|
1055
|
+
def insert_transition(self, record: dict[str, Any]) -> dict[str, Any]:
|
|
1056
|
+
"""Insert the original prepared transition once; exact replay is safe."""
|
|
1057
|
+
checked, digest = _validate_store_record(record, TRANSITION_PROFILE)
|
|
1058
|
+
request = checked['request']
|
|
1059
|
+
if (checked['state'] != 'prepared' or checked['phaseIndex'] != 0
|
|
1060
|
+
or checked['fenceReceipt'] is not None or checked['phaseReceipt'] is not None
|
|
1061
|
+
or checked['phaseBudgetReceipt'] is not None or checked['publicationReceipt'] is not None
|
|
1062
|
+
or request['providerId'] != self.provider_id
|
|
1063
|
+
or request['installationId'] != self.installation_id
|
|
1064
|
+
or request['targetCustody'] != self._custody.target_custody):
|
|
1065
|
+
raise CatalogError('ingress-transition-initial-state-invalid')
|
|
1066
|
+
self.verify_original_store()
|
|
1067
|
+
existing = self._read_transition_on(self._connection, checked['transitionId'])
|
|
1068
|
+
if existing is not None:
|
|
1069
|
+
if existing == checked:
|
|
1070
|
+
return checked
|
|
1071
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1072
|
+
count = _one(self._connection, 'SELECT count(*) FROM ' + _q(self.schema)
|
|
1073
|
+
+ '."transitions" WHERE provider_id=%s AND installation_id=%s',
|
|
1074
|
+
(self.provider_id, self.installation_id))[0]
|
|
1075
|
+
if count >= 4096:
|
|
1076
|
+
raise CatalogError('ingress-history-capacity')
|
|
1077
|
+
old = self.read_epoch(request['oldEpoch'])
|
|
1078
|
+
new = self.read_epoch(request['newEpoch'])
|
|
1079
|
+
if old is None or new is None:
|
|
1080
|
+
raise CatalogError('ingress-transition-epoch-missing')
|
|
1081
|
+
if (old['state'] != 'active' or new['state'] != 'prepared'
|
|
1082
|
+
or old['targetCustody'] != new['targetCustody']
|
|
1083
|
+
or old['targetCustody'] != request['targetCustody']
|
|
1084
|
+
or old['principalsDigest'] != request['oldPrincipalsDigest']
|
|
1085
|
+
or new['principalsDigest'] != request['newPrincipalsDigest']
|
|
1086
|
+
or old['sourceDigest'] != request['previousSourceDigest']
|
|
1087
|
+
or old['bundleDigest'] != request['previousBundleDigest']
|
|
1088
|
+
or new['sourceDigest'] != request['nextSourceDigest']
|
|
1089
|
+
or new['bundleDigest'] != request['nextBundleDigest']
|
|
1090
|
+
or old['headDigest'] != request['expectedHead']):
|
|
1091
|
+
raise CatalogError('ingress-transition-epoch-mismatch')
|
|
1092
|
+
from psycopg.types.json import Jsonb
|
|
1093
|
+
columns = _record_columns(checked)
|
|
1094
|
+
result = _one(self._connection, 'INSERT INTO ' + _q(self.schema) + '."transitions" '
|
|
1095
|
+
'(transition_id,provider_id,installation_id,old_epoch,new_epoch,request_digest,reservation_digest,state,phase_index,record,record_digest) '
|
|
1096
|
+
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING transition_id',
|
|
1097
|
+
(*columns, Jsonb(checked), digest))
|
|
1098
|
+
if result != (checked['transitionId'],):
|
|
1099
|
+
raise CatalogError('ingress-record-write-failed')
|
|
1100
|
+
return checked
|
|
1101
|
+
|
|
1102
|
+
def read_epoch(self, epoch: str) -> dict[str, Any] | None:
|
|
1103
|
+
_uuid(epoch); self.verify_original_store()
|
|
1104
|
+
return self._read_epoch_on(self._connection, epoch)
|
|
1105
|
+
|
|
1106
|
+
def _read_epoch_on(self, connection: Any, epoch: str) -> dict[str, Any] | None:
|
|
1107
|
+
row = _one(connection, 'SELECT provider_id,installation_id,epoch,state,source_digest,bundle_digest,head_digest,principals_digest,custody_sequence,record,record_digest '
|
|
1108
|
+
'FROM ' + _q(self.schema) + '."epochs" WHERE provider_id=%s AND installation_id=%s AND epoch=%s',
|
|
1109
|
+
(self.provider_id, self.installation_id, epoch))
|
|
1110
|
+
if row is None:
|
|
1111
|
+
return None
|
|
1112
|
+
return self._checked_row(row, EPOCH_PROFILE)
|
|
1113
|
+
|
|
1114
|
+
def read_transition(self, transition_id: str) -> dict[str, Any] | None:
|
|
1115
|
+
_uuid(transition_id); self.verify_original_store()
|
|
1116
|
+
row = _one(self._connection, 'SELECT transition_id,provider_id,installation_id,old_epoch,new_epoch,request_digest,reservation_digest,state,phase_index,record,record_digest '
|
|
1117
|
+
'FROM ' + _q(self.schema) + '."transitions" WHERE transition_id=%s', (transition_id,))
|
|
1118
|
+
if row is None:
|
|
1119
|
+
return None
|
|
1120
|
+
return self._checked_row(row, TRANSITION_PROFILE)
|
|
1121
|
+
|
|
1122
|
+
def _checked_row(self, row: tuple[Any, ...], profile: str) -> dict[str, Any]:
|
|
1123
|
+
record, stored_digest = row[-2], row[-1]
|
|
1124
|
+
checked, digest = _validate_store_record(record, profile)
|
|
1125
|
+
if digest != stored_digest or tuple(row[:-2]) != _record_columns(checked):
|
|
1126
|
+
raise CatalogError('ingress-record-column-mismatch')
|
|
1127
|
+
provider_id, installation_id = _record_target(checked)
|
|
1128
|
+
if provider_id != self.provider_id or installation_id != self.installation_id:
|
|
1129
|
+
raise CatalogError('ingress-record-target-mismatch')
|
|
1130
|
+
return checked
|
|
1131
|
+
|
|
1132
|
+
def advance_transition(self, transition_id: str, expected_state: str,
|
|
1133
|
+
next_record: dict[str, Any]) -> dict[str, Any]:
|
|
1134
|
+
"""CAS one legal durable transition; caller owns outer controller xact."""
|
|
1135
|
+
checked, _ = _validate_store_record(next_record, TRANSITION_PROFILE)
|
|
1136
|
+
if expected_state == 'cutover' or checked['state'] in ('cutover', 'published'):
|
|
1137
|
+
raise CatalogError('ingress-publication-hook-required')
|
|
1138
|
+
self.verify_original_store()
|
|
1139
|
+
return self._advance_transition_on(self._connection, transition_id,
|
|
1140
|
+
expected_state, next_record)
|
|
1141
|
+
|
|
1142
|
+
def _advance_transition_on(self, connection: Any, transition_id: str,
|
|
1143
|
+
expected_state: str,
|
|
1144
|
+
next_record: dict[str, Any], *,
|
|
1145
|
+
phase_binding: _PhaseTransactionBinding | None = None
|
|
1146
|
+
) -> dict[str, Any]:
|
|
1147
|
+
checked, digest = _validate_store_record(next_record, TRANSITION_PROFILE)
|
|
1148
|
+
if checked['state'] in ('cutover', 'published'):
|
|
1149
|
+
self._require_effect_binding(connection, phase_binding)
|
|
1150
|
+
if checked['transitionId'] != _uuid(transition_id):
|
|
1151
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1152
|
+
if type(expected_state) is not str:
|
|
1153
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1154
|
+
current = self._read_transition_on(connection, transition_id)
|
|
1155
|
+
if current is None:
|
|
1156
|
+
raise CatalogError('ingress-transition-missing')
|
|
1157
|
+
if current == checked:
|
|
1158
|
+
return checked
|
|
1159
|
+
if current['state'] != expected_state or not _legal_transition(current, checked):
|
|
1160
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1161
|
+
from psycopg.types.json import Jsonb
|
|
1162
|
+
columns = _record_columns(checked)
|
|
1163
|
+
result = _one(connection, 'UPDATE ' + _q(self.schema) + '."transitions" SET '
|
|
1164
|
+
'state=%s,phase_index=%s,record=%s,record_digest=%s '
|
|
1165
|
+
'WHERE transition_id=%s AND state=%s RETURNING transition_id',
|
|
1166
|
+
(checked['state'], checked['phaseIndex'], Jsonb(checked), digest,
|
|
1167
|
+
transition_id, expected_state))
|
|
1168
|
+
if result is None or result[0] != transition_id:
|
|
1169
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1170
|
+
# The DB columns are not mutable except the legal CAS fields. This
|
|
1171
|
+
# tuple check also documents the duplicated identity binding.
|
|
1172
|
+
if columns[:7] != _record_columns(current)[:7]:
|
|
1173
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1174
|
+
return checked
|
|
1175
|
+
|
|
1176
|
+
def _read_transition_on(self, connection: Any, transition_id: str) -> dict[str, Any] | None:
|
|
1177
|
+
_uuid(transition_id)
|
|
1178
|
+
row = _one(connection, 'SELECT transition_id,provider_id,installation_id,old_epoch,new_epoch,request_digest,reservation_digest,state,phase_index,record,record_digest '
|
|
1179
|
+
'FROM ' + _q(self.schema) + '."transitions" WHERE transition_id=%s', (transition_id,))
|
|
1180
|
+
if row is None:
|
|
1181
|
+
return None
|
|
1182
|
+
return self._checked_row(row, TRANSITION_PROFILE)
|
|
1183
|
+
|
|
1184
|
+
def record_phase_in_transaction(self, phase_binding: _PhaseTransactionBinding, *,
|
|
1185
|
+
transition_id: str, expected_state: str,
|
|
1186
|
+
next_record: dict[str, Any]) -> dict[str, Any]:
|
|
1187
|
+
"""Persist phase receipt on the host's current business transaction.
|
|
1188
|
+
|
|
1189
|
+
The sealed binding belongs to a concrete private host lease. This
|
|
1190
|
+
method executes only fixed controller DML on that same transaction.
|
|
1191
|
+
"""
|
|
1192
|
+
if type(phase_binding) is not _PhaseTransactionBinding:
|
|
1193
|
+
raise CatalogError('ingress-phase-connection-mismatch')
|
|
1194
|
+
phase_connection = phase_binding.connection
|
|
1195
|
+
try:
|
|
1196
|
+
self._check_phase_binding(phase_binding)
|
|
1197
|
+
self._require_active_transaction(phase_connection)
|
|
1198
|
+
checked, _ = _validate_store_record(next_record, TRANSITION_PROFILE)
|
|
1199
|
+
if checked['request']['targetIdentityDigest'] != phase_binding.target_identity_digest:
|
|
1200
|
+
raise CatalogError('ingress-phase-target-mismatch')
|
|
1201
|
+
before = self._phase_identity(phase_connection, phase_binding)
|
|
1202
|
+
self._verify_business_owner_context(phase_connection, phase_binding)
|
|
1203
|
+
return self._execute_controller_hook(
|
|
1204
|
+
phase_connection, before, phase_binding, transition_id,
|
|
1205
|
+
expected_state, checked)
|
|
1206
|
+
except BaseException:
|
|
1207
|
+
self._abort_and_close(phase_connection, phase_binding)
|
|
1208
|
+
raise
|
|
1209
|
+
|
|
1210
|
+
def record_publication_in_transaction(self, phase_binding: _PhaseTransactionBinding, *,
|
|
1211
|
+
transition_id: str, expected_state: str,
|
|
1212
|
+
next_record: dict[str, Any]) -> dict[str, Any]:
|
|
1213
|
+
"""Persist final reference/active-epoch receipt in the same transaction."""
|
|
1214
|
+
if type(phase_binding) is not _PhaseTransactionBinding:
|
|
1215
|
+
raise CatalogError('ingress-publication-state-invalid')
|
|
1216
|
+
connection = phase_binding.connection
|
|
1217
|
+
try:
|
|
1218
|
+
checked, _ = _validate_store_record(next_record, TRANSITION_PROFILE)
|
|
1219
|
+
if (checked['state'] != 'published' or checked['phaseIndex'] != 1
|
|
1220
|
+
or expected_state != 'cutover'
|
|
1221
|
+
or phase_binding._seal is not _CAPABILITY_SEAL):
|
|
1222
|
+
raise CatalogError('ingress-publication-state-invalid')
|
|
1223
|
+
self._check_phase_binding(phase_binding)
|
|
1224
|
+
self._require_active_transaction(connection)
|
|
1225
|
+
if checked['request']['targetIdentityDigest'] != phase_binding.target_identity_digest:
|
|
1226
|
+
raise CatalogError('ingress-phase-target-mismatch')
|
|
1227
|
+
before = self._phase_identity(connection, phase_binding)
|
|
1228
|
+
self._verify_business_owner_context(connection, phase_binding)
|
|
1229
|
+
return self._execute_controller_hook(
|
|
1230
|
+
connection, before, phase_binding, transition_id,
|
|
1231
|
+
expected_state, checked, publication=True)
|
|
1232
|
+
except BaseException:
|
|
1233
|
+
self._abort_and_close(connection, phase_binding)
|
|
1234
|
+
raise
|
|
1235
|
+
|
|
1236
|
+
@staticmethod
|
|
1237
|
+
def _require_active_transaction(connection: Any) -> None:
|
|
1238
|
+
try:
|
|
1239
|
+
from psycopg.pq import TransactionStatus
|
|
1240
|
+
active = connection.info.transaction_status == TransactionStatus.INTRANS
|
|
1241
|
+
except (AttributeError, ImportError):
|
|
1242
|
+
active = False
|
|
1243
|
+
if not active:
|
|
1244
|
+
raise CatalogError('ingress-phase-transaction-required')
|
|
1245
|
+
|
|
1246
|
+
def _phase_identity(self, connection: Any,
|
|
1247
|
+
binding: _PhaseTransactionBinding) -> tuple[Any, ...]:
|
|
1248
|
+
row = _one(connection, """SELECT session_user,current_user,
|
|
1249
|
+
pg_catalog.current_schemas(false),pg_catalog.current_setting('row_security'),
|
|
1250
|
+
pg_catalog.current_setting('session_replication_role'),
|
|
1251
|
+
pg_catalog.current_setting('server_encoding'),
|
|
1252
|
+
pg_catalog.current_setting('transaction_isolation'),
|
|
1253
|
+
pg_catalog.current_setting('transaction_read_only'),
|
|
1254
|
+
pg_catalog.current_setting('role'),pg_catalog.current_setting('search_path'),
|
|
1255
|
+
pg_catalog.current_setting('TimeZone'),
|
|
1256
|
+
(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=current_user),
|
|
1257
|
+
(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=session_user),
|
|
1258
|
+
(SELECT oid FROM pg_catalog.pg_database WHERE datname=pg_catalog.current_database()),
|
|
1259
|
+
pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
|
|
1260
|
+
pg_catalog.current_database(),
|
|
1261
|
+
(SELECT system_identifier FROM pg_catalog.pg_control_system())""")
|
|
1262
|
+
normalized = self._normalize_phase_row(row)
|
|
1263
|
+
if (normalized[0] != binding.session_user or normalized[1] != binding.business_owner
|
|
1264
|
+
or normalized[2] != ['pg_catalog']
|
|
1265
|
+
or normalized[3:8] != ('on', 'origin', 'UTF8', 'read committed', 'off')
|
|
1266
|
+
or normalized[8:11] != (binding.business_owner, 'pg_catalog', 'UTC')
|
|
1267
|
+
or normalized[11] != binding.business_owner_oid
|
|
1268
|
+
or normalized[12] != binding.session_user_oid or normalized[13] != binding.database_oid
|
|
1269
|
+
or normalized[14] != 180006 or normalized[15] != self.database_name
|
|
1270
|
+
or normalized[16] != self.database_system_identifier):
|
|
1271
|
+
raise CatalogError('ingress-phase-identity-mismatch')
|
|
1272
|
+
return normalized
|
|
1273
|
+
|
|
1274
|
+
@staticmethod
|
|
1275
|
+
def _normalize_phase_row(row: Any) -> tuple[Any, ...]:
|
|
1276
|
+
if type(row) is not tuple or len(row) != 17:
|
|
1277
|
+
raise CatalogError('ingress-phase-identity-mismatch')
|
|
1278
|
+
identifier = row[16]
|
|
1279
|
+
if type(identifier) not in (int, str):
|
|
1280
|
+
raise CatalogError('ingress-phase-identity-mismatch')
|
|
1281
|
+
try:
|
|
1282
|
+
normalized_identifier = _system_identifier(str(identifier))
|
|
1283
|
+
except CatalogError:
|
|
1284
|
+
raise CatalogError('ingress-phase-identity-mismatch') from None
|
|
1285
|
+
return (*row[:16], normalized_identifier)
|
|
1286
|
+
|
|
1287
|
+
def _check_phase_binding(self, binding: _PhaseTransactionBinding) -> None:
|
|
1288
|
+
if (type(binding) is not _PhaseTransactionBinding
|
|
1289
|
+
or binding._invalidated
|
|
1290
|
+
or binding._seal is not _CAPABILITY_SEAL
|
|
1291
|
+
or binding.provider_id != self.provider_id
|
|
1292
|
+
or binding.installation_id != self.installation_id
|
|
1293
|
+
or binding.session_user != self._custody.maintenance_user
|
|
1294
|
+
or binding.session_user_oid != self._custody.maintenance_user_oid
|
|
1295
|
+
or binding.business_owner != self._custody.business_owner
|
|
1296
|
+
or binding.business_owner_oid != self._custody.business_owner_oid
|
|
1297
|
+
or binding.database_oid != self.database_oid):
|
|
1298
|
+
raise CatalogError('ingress-phase-connection-mismatch')
|
|
1299
|
+
|
|
1300
|
+
def _require_effect_binding(self, connection: Any,
|
|
1301
|
+
binding: _PhaseTransactionBinding | None) -> None:
|
|
1302
|
+
if type(binding) is not _PhaseTransactionBinding or binding.connection is not connection:
|
|
1303
|
+
raise CatalogError('ingress-phase-transaction-required')
|
|
1304
|
+
self._check_phase_binding(binding)
|
|
1305
|
+
|
|
1306
|
+
@staticmethod
|
|
1307
|
+
def _abort_and_close(connection: Any, binding: _PhaseTransactionBinding) -> None:
|
|
1308
|
+
"""Invalidate the lease, then attempt rollback and unconditional close."""
|
|
1309
|
+
object.__setattr__(binding, '_invalidated', True)
|
|
1310
|
+
try:
|
|
1311
|
+
connection.rollback()
|
|
1312
|
+
except BaseException: # noqa: BLE001 - cleanup must not mask the primary hook error
|
|
1313
|
+
_LOG.debug('rollback failed while aborting failed phase hook')
|
|
1314
|
+
finally:
|
|
1315
|
+
try:
|
|
1316
|
+
connection.close()
|
|
1317
|
+
except BaseException: # noqa: BLE001 - cleanup must not mask the primary hook error
|
|
1318
|
+
_LOG.debug('close failed while aborting failed phase hook')
|
|
1319
|
+
|
|
1320
|
+
def _verify_business_owner_context(self, connection: Any,
|
|
1321
|
+
binding: _PhaseTransactionBinding) -> None:
|
|
1322
|
+
self._phase_identity(connection, binding)
|
|
1323
|
+
if (self._set_membership_snapshot(connection, binding.session_user_oid)
|
|
1324
|
+
!= self._custody.membership_observations):
|
|
1325
|
+
raise CatalogError('ingress-phase-identity-mismatch')
|
|
1326
|
+
self._verify_principal_observations(connection)
|
|
1327
|
+
|
|
1328
|
+
def _execute_controller_hook(self, connection: Any, before: tuple[Any, ...],
|
|
1329
|
+
binding: _PhaseTransactionBinding,
|
|
1330
|
+
transition_id: str, expected_state: str,
|
|
1331
|
+
next_record: dict[str, Any], *,
|
|
1332
|
+
publication: bool = False) -> dict[str, Any]:
|
|
1333
|
+
_execute(connection, 'SET LOCAL ROLE ' + _q(self.controller_role))
|
|
1334
|
+
state = _one(connection, """SELECT session_user,current_user,
|
|
1335
|
+
pg_catalog.current_schemas(false),pg_catalog.current_setting('row_security'),
|
|
1336
|
+
pg_catalog.current_setting('session_replication_role'),
|
|
1337
|
+
pg_catalog.current_setting('server_encoding'),
|
|
1338
|
+
pg_catalog.current_setting('transaction_isolation'),
|
|
1339
|
+
pg_catalog.current_setting('transaction_read_only'),
|
|
1340
|
+
pg_catalog.current_setting('role'),pg_catalog.current_setting('search_path'),
|
|
1341
|
+
pg_catalog.current_setting('TimeZone'),
|
|
1342
|
+
(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=current_user),
|
|
1343
|
+
(SELECT oid FROM pg_catalog.pg_roles WHERE rolname=session_user),
|
|
1344
|
+
(SELECT oid FROM pg_catalog.pg_database WHERE datname=pg_catalog.current_database()),
|
|
1345
|
+
pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
|
|
1346
|
+
pg_catalog.current_database(),
|
|
1347
|
+
(SELECT system_identifier FROM pg_catalog.pg_control_system())""")
|
|
1348
|
+
controller_identity = (binding.session_user, self.controller_role,
|
|
1349
|
+
before[2], before[3], before[4], before[5],
|
|
1350
|
+
before[6], before[7], self.controller_role,
|
|
1351
|
+
'pg_catalog', 'UTC', self.controller_oid,
|
|
1352
|
+
binding.session_user_oid, binding.database_oid,
|
|
1353
|
+
180006, self.database_name, self.database_system_identifier)
|
|
1354
|
+
state = self._normalize_phase_row(state)
|
|
1355
|
+
controller_identity = (*controller_identity[:16], self.database_system_identifier)
|
|
1356
|
+
if state != controller_identity:
|
|
1357
|
+
raise CatalogError('ingress-phase-controller-mismatch')
|
|
1358
|
+
self._verify_controller_session(connection)
|
|
1359
|
+
if self._schema_oid is None:
|
|
1360
|
+
raise CatalogError('ingress-store-custody-required')
|
|
1361
|
+
self._verify_store_shape(self._schema_oid, connection)
|
|
1362
|
+
if publication:
|
|
1363
|
+
result = self._publish_transition_on(connection, transition_id,
|
|
1364
|
+
expected_state, next_record,
|
|
1365
|
+
phase_binding=binding)
|
|
1366
|
+
else:
|
|
1367
|
+
result = self._advance_transition_on(connection, transition_id,
|
|
1368
|
+
expected_state, next_record,
|
|
1369
|
+
phase_binding=binding)
|
|
1370
|
+
# Always restore the fixed business-owner role, never RESET ROLE (which
|
|
1371
|
+
# would return to the distinct maintenance SESSION_USER).
|
|
1372
|
+
_execute(connection, 'SET LOCAL ROLE ' + _q(binding.business_owner))
|
|
1373
|
+
after = self._phase_identity(connection, binding)
|
|
1374
|
+
self._verify_business_owner_context(connection, binding)
|
|
1375
|
+
if after != before:
|
|
1376
|
+
raise CatalogError('ingress-phase-restore-mismatch')
|
|
1377
|
+
return result
|
|
1378
|
+
|
|
1379
|
+
def _publish_transition_on(self, connection: Any, transition_id: str,
|
|
1380
|
+
expected_state: str,
|
|
1381
|
+
following: dict[str, Any], *,
|
|
1382
|
+
phase_binding: _PhaseTransactionBinding | None = None
|
|
1383
|
+
) -> dict[str, Any]:
|
|
1384
|
+
"""Atomically publish the transition and swap its two admitted epochs."""
|
|
1385
|
+
self._require_effect_binding(connection, phase_binding)
|
|
1386
|
+
current = self._read_transition_on(connection, transition_id)
|
|
1387
|
+
if (current is None or current['state'] != expected_state
|
|
1388
|
+
or expected_state != 'cutover' or not _legal_transition(current, following)):
|
|
1389
|
+
raise CatalogError('ingress-transition-conflict')
|
|
1390
|
+
request = current['request']
|
|
1391
|
+
reference = following['publicationReceipt']
|
|
1392
|
+
if (reference['version'] != 'umf.table-installation/0.3'
|
|
1393
|
+
or reference['bundleDigest'] != request['nextBundleDigest']
|
|
1394
|
+
or reference['sourceDigest'] != request['nextSourceDigest']
|
|
1395
|
+
or reference['planDigest'] != request['planDigest']
|
|
1396
|
+
or reference['approvalPlanDigest'] != request['planDigest']):
|
|
1397
|
+
raise CatalogError('ingress-publication-binding-mismatch')
|
|
1398
|
+
old = self._read_epoch_on(connection, request['oldEpoch'])
|
|
1399
|
+
new = self._read_epoch_on(connection, request['newEpoch'])
|
|
1400
|
+
if (old is None or new is None or old['state'] != 'active'
|
|
1401
|
+
or new['state'] != 'prepared'
|
|
1402
|
+
or old['headDigest'] != request['expectedHead']
|
|
1403
|
+
or old['sourceDigest'] != request['previousSourceDigest']
|
|
1404
|
+
or old['bundleDigest'] != request['previousBundleDigest']
|
|
1405
|
+
or new['sourceDigest'] != request['nextSourceDigest']
|
|
1406
|
+
or new['bundleDigest'] != request['nextBundleDigest']
|
|
1407
|
+
or old['principalsDigest'] != request['oldPrincipalsDigest']
|
|
1408
|
+
or new['principalsDigest'] != request['newPrincipalsDigest']
|
|
1409
|
+
or old['targetCustody'] != request['targetCustody']
|
|
1410
|
+
or new['targetCustody'] != request['targetCustody']):
|
|
1411
|
+
raise CatalogError('ingress-transition-epoch-mismatch')
|
|
1412
|
+
old_next = dict(old)
|
|
1413
|
+
old_next['state'] = 'retired'
|
|
1414
|
+
new_next = dict(new)
|
|
1415
|
+
new_next['state'] = 'active'
|
|
1416
|
+
new_next['headDigest'] = reference['headDigest']
|
|
1417
|
+
self._replace_epoch_state_on(connection, old, old_next)
|
|
1418
|
+
self._replace_epoch_state_on(connection, new, new_next)
|
|
1419
|
+
return self._advance_transition_on(connection, transition_id,
|
|
1420
|
+
expected_state, following,
|
|
1421
|
+
phase_binding=phase_binding)
|
|
1422
|
+
|
|
1423
|
+
def _replace_epoch_state_on(self, connection: Any, current: dict[str, Any],
|
|
1424
|
+
following: dict[str, Any]) -> None:
|
|
1425
|
+
checked, digest = _validate_store_record(following, EPOCH_PROFILE)
|
|
1426
|
+
allowed = {('active', 'retired'), ('prepared', 'active')}
|
|
1427
|
+
immutable = ('profile', 'providerId', 'enrollmentId', 'installationId',
|
|
1428
|
+
'targetCustody', 'epoch', 'sourceDigest', 'bundleDigest',
|
|
1429
|
+
'principals', 'principalsDigest', 'custodySequence', 'origin',
|
|
1430
|
+
'originReceipt')
|
|
1431
|
+
if ((current['state'], checked['state']) not in allowed
|
|
1432
|
+
or any(current[key] != checked[key] for key in immutable)
|
|
1433
|
+
or current['state'] == 'active' and current['headDigest'] != checked['headDigest']):
|
|
1434
|
+
raise CatalogError('ingress-epoch-conflict')
|
|
1435
|
+
from psycopg.types.json import Jsonb
|
|
1436
|
+
result = _one(connection, 'UPDATE ' + _q(self.schema) + '."epochs" '
|
|
1437
|
+
'SET state=%s,head_digest=%s,record=%s,record_digest=%s '
|
|
1438
|
+
'WHERE provider_id=%s AND installation_id=%s AND epoch=%s AND state=%s '
|
|
1439
|
+
'AND record_digest=%s RETURNING epoch',
|
|
1440
|
+
(checked['state'], checked['headDigest'], Jsonb(checked), digest,
|
|
1441
|
+
self.provider_id, self.installation_id, checked['epoch'],
|
|
1442
|
+
current['state'], _digest(current)))
|
|
1443
|
+
if result != (checked['epoch'],):
|
|
1444
|
+
raise CatalogError('ingress-epoch-conflict')
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def _legal_transition(current: dict[str, Any], following: dict[str, Any]) -> bool:
|
|
1448
|
+
states = {'prepared': ('fencing',), 'fencing': ('fenced',),
|
|
1449
|
+
'fenced': ('cutover',), 'cutover': ('published',), 'published': ()}
|
|
1450
|
+
if following['state'] not in states[current['state']]:
|
|
1451
|
+
return False
|
|
1452
|
+
immutable = ('transitionId', 'request', 'requestDigest', 'ingressApprovalDigest',
|
|
1453
|
+
'reservation', 'reservationDigest', 'executionPolicy')
|
|
1454
|
+
if any(current[key] != following[key] for key in immutable):
|
|
1455
|
+
return False
|
|
1456
|
+
if following['state'] in ('prepared', 'fencing', 'fenced') and following['phaseIndex'] != 0:
|
|
1457
|
+
return False
|
|
1458
|
+
if following['state'] in ('cutover', 'published') and following['phaseIndex'] != 1:
|
|
1459
|
+
return False
|
|
1460
|
+
if current['state'] == 'prepared' and following['fenceReceipt'] is not None:
|
|
1461
|
+
return False
|
|
1462
|
+
if current['state'] == 'fencing' and following['fenceReceipt'] is None:
|
|
1463
|
+
return False
|
|
1464
|
+
if current['state'] in ('fenced', 'cutover', 'published') and (
|
|
1465
|
+
current['fenceReceipt'] != following['fenceReceipt']):
|
|
1466
|
+
return False
|
|
1467
|
+
if current['state'] in ('prepared', 'fencing') and (
|
|
1468
|
+
following['phaseReceipt'] is not None
|
|
1469
|
+
or following['phaseBudgetReceipt'] is not None
|
|
1470
|
+
or following['publicationReceipt'] is not None):
|
|
1471
|
+
return False
|
|
1472
|
+
if current['state'] in ('cutover', 'published') and (
|
|
1473
|
+
current['phaseReceipt'] != following['phaseReceipt']
|
|
1474
|
+
or current['phaseBudgetReceipt'] != following['phaseBudgetReceipt']):
|
|
1475
|
+
return False
|
|
1476
|
+
if current['state'] == 'fenced' and following['publicationReceipt'] is not None:
|
|
1477
|
+
return False
|
|
1478
|
+
if current['state'] == 'fenced' and (
|
|
1479
|
+
following['phaseReceipt'] is None
|
|
1480
|
+
or following['phaseBudgetReceipt'] is None
|
|
1481
|
+
or following['publicationReceipt'] is not None):
|
|
1482
|
+
return False
|
|
1483
|
+
if current['state'] == 'cutover' and (
|
|
1484
|
+
following['publicationReceipt'] is None):
|
|
1485
|
+
return False
|
|
1486
|
+
if current['state'] != 'cutover' and following['publicationReceipt'] is not None:
|
|
1487
|
+
return False
|
|
1488
|
+
return not (current['state'] == 'published' and current != following)
|