umf-access 0.1.0.dev8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,306 @@
1
+ /* SPDX-License-Identifier: MIT OR Apache-2.0 */
2
+ /*
3
+ * Source for the pinned Darwin process observer used by the local G11
4
+ * PostgreSQL supervisor. It is deliberately a tiny native helper instead of
5
+ * a ctypes layout guess. Build identity and this source are qualified
6
+ * separately before the production adapter can be enabled.
7
+ */
8
+ #include <errno.h>
9
+ #include <arpa/inet.h>
10
+ #include <libproc.h>
11
+ #include <netinet/in.h>
12
+ #include <stdint.h>
13
+ #include <stdio.h>
14
+ #include <stdlib.h>
15
+ #include <string.h>
16
+ #include <sys/proc_info.h>
17
+ #include <sys/sysctl.h>
18
+ #include <sys/time.h>
19
+ #include <unistd.h>
20
+
21
+ #define MAX_PIDS 65536
22
+ #define MAX_ARGS_BYTES (1024 * 1024)
23
+ #define MAX_ARGC 4096
24
+ #define MAX_FDS 65536
25
+
26
+ static void json_string(const char *s) {
27
+ putchar('"');
28
+ for (const unsigned char *p = (const unsigned char *)s; *p; ++p) {
29
+ switch (*p) {
30
+ case '"': fputs("\\\"", stdout); break;
31
+ case '\\': fputs("\\\\", stdout); break;
32
+ case '\n': fputs("\\n", stdout); break;
33
+ case '\r': fputs("\\r", stdout); break;
34
+ case '\t': fputs("\\t", stdout); break;
35
+ default:
36
+ if (*p < 0x20) printf("\\u%04x", (unsigned)*p);
37
+ else putchar(*p);
38
+ }
39
+ }
40
+ putchar('"');
41
+ }
42
+
43
+ static int process_args(pid_t pid, char ***out, int *count, char **storage) {
44
+ int mib[3] = {CTL_KERN, KERN_PROCARGS2, pid};
45
+ size_t size = 0;
46
+ if (sysctl(mib, 3, NULL, &size, NULL, 0) != 0 || size < sizeof(int) ||
47
+ size > MAX_ARGS_BYTES) return -1;
48
+ char *buffer = calloc(1, size + 1);
49
+ if (!buffer) return -1;
50
+ if (sysctl(mib, 3, buffer, &size, NULL, 0) != 0 || size < sizeof(int)) {
51
+ free(buffer);
52
+ return -1;
53
+ }
54
+ int argc = 0;
55
+ memcpy(&argc, buffer, sizeof(argc));
56
+ if (argc < 0 || argc > MAX_ARGC) {
57
+ free(buffer);
58
+ return -1;
59
+ }
60
+ char *cursor = buffer + sizeof(int), *end = buffer + size;
61
+ while (cursor < end && *cursor) ++cursor; /* executable path */
62
+ while (cursor < end && !*cursor) ++cursor;
63
+ char **args = calloc((size_t)argc + 1, sizeof(char *));
64
+ if (!args) {
65
+ free(buffer);
66
+ return -1;
67
+ }
68
+ for (int i = 0; i < argc; ++i) {
69
+ while (cursor < end && !*cursor) ++cursor;
70
+ if (cursor >= end) {
71
+ free(args);
72
+ free(buffer);
73
+ return -1;
74
+ }
75
+ args[i] = cursor;
76
+ while (cursor < end && *cursor) ++cursor;
77
+ if (cursor >= end) {
78
+ free(args);
79
+ free(buffer);
80
+ return -1;
81
+ }
82
+ ++cursor;
83
+ }
84
+ *out = args;
85
+ *count = argc;
86
+ *storage = buffer;
87
+ return 0;
88
+ }
89
+
90
+ static int emit_process(pid_t pid, int with_args) {
91
+ struct proc_bsdinfo info;
92
+ memset(&info, 0, sizeof(info));
93
+ int got = proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info));
94
+ if (got != (int)sizeof(info)) return -1;
95
+ char path[PROC_PIDPATHINFO_MAXSIZE];
96
+ memset(path, 0, sizeof(path));
97
+ int path_size = proc_pidpath(pid, path, sizeof(path));
98
+ if (path_size <= 0 || path_size >= (int)sizeof(path)) return -1;
99
+ printf("{\"pid\":%d,\"pgid\":%d,\"uid\":%u,\"gid\":%u,"
100
+ "\"startSec\":%llu,\"startUsec\":%u,\"path\":",
101
+ info.pbi_pid, info.pbi_pgid, info.pbi_uid, info.pbi_gid,
102
+ (unsigned long long)info.pbi_start_tvsec, info.pbi_start_tvusec);
103
+ json_string(path);
104
+ if (with_args) {
105
+ char **args = NULL;
106
+ char *storage = NULL;
107
+ int argc = 0;
108
+ if (process_args(pid, &args, &argc, &storage) != 0) return -1;
109
+ printf(",\"argv\":[");
110
+ for (int i = 0; i < argc; ++i) {
111
+ if (i) putchar(',');
112
+ json_string(args[i]);
113
+ }
114
+ printf("]");
115
+ free(storage);
116
+ free(args);
117
+ }
118
+ putchar('}');
119
+ return 0;
120
+ }
121
+
122
+ static int emit_one(pid_t pid) {
123
+ struct timeval boot;
124
+ size_t boot_size = sizeof(boot);
125
+ if (sysctlbyname("kern.boottime", &boot, &boot_size, NULL, 0) != 0 ||
126
+ boot_size != sizeof(boot)) return 2;
127
+ printf("{\"profile\":\"umf.darwin-process-observer/0.1\","
128
+ "\"bootSec\":%lld,\"bootUsec\":%lld,\"process\":",
129
+ (long long)boot.tv_sec, (long long)boot.tv_usec);
130
+ if (emit_process(pid, 1) != 0) return 3;
131
+ puts("}");
132
+ return 0;
133
+ }
134
+
135
+ static int emit_group(pid_t pgid) {
136
+ pid_t *pids = calloc(MAX_PIDS, sizeof(pid_t));
137
+ if (!pids) return 2;
138
+ int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids,
139
+ (int)(MAX_PIDS * sizeof(pid_t)));
140
+ if (bytes <= 0 || bytes >= (int)(MAX_PIDS * sizeof(pid_t)) ||
141
+ bytes % (int)sizeof(pid_t)) {
142
+ free(pids);
143
+ return 3;
144
+ }
145
+ printf("{\"profile\":\"umf.darwin-process-group-observer/0.1\","
146
+ "\"pgid\":%d,\"processes\":[", pgid);
147
+ int first = 1;
148
+ for (int i = 0; i < bytes / (int)sizeof(pid_t); ++i) {
149
+ if (pids[i] <= 0) continue;
150
+ struct proc_bsdinfo info;
151
+ memset(&info, 0, sizeof(info));
152
+ int got = proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &info, sizeof(info));
153
+ if (got == 0) continue; /* process exited between enumeration and read */
154
+ if (got != (int)sizeof(info)) {
155
+ free(pids);
156
+ return 4;
157
+ }
158
+ if (info.pbi_pgid != pgid) continue;
159
+ if (!first) putchar(',');
160
+ first = 0;
161
+ if (emit_process(pids[i], 1) != 0) {
162
+ free(pids);
163
+ return 5;
164
+ }
165
+ }
166
+ puts("]}");
167
+ free(pids);
168
+ return 0;
169
+ }
170
+
171
+ static int emit_sockets(pid_t pgid) {
172
+ pid_t *pids = calloc(MAX_PIDS, sizeof(pid_t));
173
+ if (!pids) return 2;
174
+ int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids,
175
+ (int)(MAX_PIDS * sizeof(pid_t)));
176
+ if (bytes <= 0 || bytes >= (int)(MAX_PIDS * sizeof(pid_t)) ||
177
+ bytes % (int)sizeof(pid_t)) {
178
+ free(pids);
179
+ return 3;
180
+ }
181
+ printf("{\"profile\":\"umf.darwin-socket-group-observer/0.1\","
182
+ "\"pgid\":%d,\"sockets\":[", pgid);
183
+ int first = 1;
184
+ for (int i = 0; i < bytes / (int)sizeof(pid_t); ++i) {
185
+ if (pids[i] <= 0) continue;
186
+ struct proc_bsdinfo process;
187
+ memset(&process, 0, sizeof(process));
188
+ int got = proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &process,
189
+ sizeof(process));
190
+ if (got == 0) continue;
191
+ if (got != (int)sizeof(process)) { free(pids); return 4; }
192
+ if (process.pbi_pgid != pgid) continue;
193
+ size_t fd_capacity = MAX_FDS * sizeof(struct proc_fdinfo);
194
+ struct proc_fdinfo *fds = calloc(MAX_FDS, sizeof(struct proc_fdinfo));
195
+ if (!fds) { free(pids); return 6; }
196
+ int actual = proc_pidinfo(pids[i], PROC_PIDLISTFDS, 0, fds,
197
+ (int)fd_capacity);
198
+ if (actual <= 0 || actual >= (int)fd_capacity ||
199
+ actual % (int)sizeof(struct proc_fdinfo)) {
200
+ free(fds); free(pids); return 7;
201
+ }
202
+ for (int j = 0; j < actual / (int)sizeof(struct proc_fdinfo); ++j) {
203
+ if (fds[j].proc_fdtype != PROX_FDTYPE_SOCKET) continue;
204
+ struct socket_fdinfo socket;
205
+ memset(&socket, 0, sizeof(socket));
206
+ int socket_bytes = proc_pidfdinfo(pids[i], fds[j].proc_fd,
207
+ PROC_PIDFDSOCKETINFO, &socket,
208
+ sizeof(socket));
209
+ if (socket_bytes != (int)sizeof(socket)) {
210
+ free(fds); free(pids); return 8;
211
+ }
212
+ if (!first) putchar(',');
213
+ first = 0;
214
+ printf("{\"pid\":%d,\"fd\":%d,\"family\":%d,"
215
+ "\"kind\":%d,\"type\":%d,\"protocol\":%d,"
216
+ "\"state\":%d,\"listening\":%s,\"address\":",
217
+ pids[i], fds[j].proc_fd, socket.psi.soi_family,
218
+ socket.psi.soi_kind, socket.psi.soi_type,
219
+ socket.psi.soi_protocol,
220
+ socket.psi.soi_kind == SOCKINFO_TCP
221
+ ? socket.psi.soi_proto.pri_tcp.tcpsi_state : -1,
222
+ socket.psi.soi_kind == SOCKINFO_TCP &&
223
+ socket.psi.soi_proto.pri_tcp.tcpsi_state == TSI_S_LISTEN
224
+ ? "true" : "false");
225
+ if (socket.psi.soi_kind == SOCKINFO_TCP &&
226
+ socket.psi.soi_family == AF_INET) {
227
+ char address[INET_ADDRSTRLEN] = {0};
228
+ const void *source = &socket.psi.soi_proto.pri_tcp.tcpsi_ini
229
+ .insi_laddr.ina_46.i46a_addr4;
230
+ if (!inet_ntop(AF_INET, source, address, sizeof(address))) {
231
+ free(fds); free(pids); return 9;
232
+ }
233
+ json_string(address);
234
+ printf(",\"port\":%u", ntohs((uint16_t)socket.psi.soi_proto
235
+ .pri_tcp.tcpsi_ini.insi_lport));
236
+ char peer[INET_ADDRSTRLEN] = {0};
237
+ const void *peer_source = &socket.psi.soi_proto.pri_tcp.tcpsi_ini
238
+ .insi_faddr.ina_46.i46a_addr4;
239
+ if (!inet_ntop(AF_INET, peer_source, peer, sizeof(peer))) {
240
+ free(fds); free(pids); return 11;
241
+ }
242
+ fputs(",\"peerAddress\":", stdout);
243
+ json_string(peer);
244
+ } else if (socket.psi.soi_kind == SOCKINFO_TCP &&
245
+ socket.psi.soi_family == AF_INET6) {
246
+ char address[INET6_ADDRSTRLEN] = {0};
247
+ const void *source = &socket.psi.soi_proto.pri_tcp.tcpsi_ini
248
+ .insi_laddr.ina_6;
249
+ if (!inet_ntop(AF_INET6, source, address, sizeof(address))) {
250
+ free(fds); free(pids); return 10;
251
+ }
252
+ json_string(address);
253
+ printf(",\"port\":%u", ntohs((uint16_t)socket.psi.soi_proto
254
+ .pri_tcp.tcpsi_ini.insi_lport));
255
+ char peer[INET6_ADDRSTRLEN] = {0};
256
+ const void *peer_source = &socket.psi.soi_proto.pri_tcp.tcpsi_ini
257
+ .insi_faddr.ina_6;
258
+ if (!inet_ntop(AF_INET6, peer_source, peer, sizeof(peer))) {
259
+ free(fds); free(pids); return 12;
260
+ }
261
+ fputs(",\"peerAddress\":", stdout);
262
+ json_string(peer);
263
+ } else if (socket.psi.soi_kind == SOCKINFO_UN) {
264
+ char path[sizeof(socket.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path) + 1];
265
+ memcpy(path, socket.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path,
266
+ sizeof(path) - 1);
267
+ path[sizeof(path) - 1] = '\0';
268
+ json_string(path);
269
+ fputs(",\"port\":null", stdout);
270
+ fputs(",\"peerAddress\":null", stdout);
271
+ } else {
272
+ json_string("");
273
+ fputs(",\"port\":null", stdout);
274
+ fputs(",\"peerAddress\":null", stdout);
275
+ }
276
+ putchar('}');
277
+ }
278
+ free(fds);
279
+ }
280
+ puts("]}");
281
+ free(pids);
282
+ return 0;
283
+ }
284
+
285
+ int main(int argc, char **argv) {
286
+ if (argc == 3 && strcmp(argv[1], "--pid") == 0) {
287
+ char *end = NULL;
288
+ long value = strtol(argv[2], &end, 10);
289
+ if (!end || *end || value <= 0 || value > INT32_MAX) return 64;
290
+ return emit_one((pid_t)value);
291
+ }
292
+ if (argc == 3 && strcmp(argv[1], "--pgid") == 0) {
293
+ char *end = NULL;
294
+ long value = strtol(argv[2], &end, 10);
295
+ if (!end || *end || value <= 0 || value > INT32_MAX) return 64;
296
+ return emit_group((pid_t)value);
297
+ }
298
+ if (argc == 3 && strcmp(argv[1], "--sockets") == 0) {
299
+ char *end = NULL;
300
+ long value = strtol(argv[2], &end, 10);
301
+ if (!end || *end || value <= 0 || value > INT32_MAX) return 64;
302
+ return emit_sockets((pid_t)value);
303
+ }
304
+ fputs("usage: process-observer (--pid PID | --pgid PGID)\n", stderr);
305
+ return 64;
306
+ }
@@ -0,0 +1,366 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Source-bound approval values for host-owned migration custody.
3
+
4
+ These values describe an approval binding; constructing them is not approval.
5
+ Only a host-authenticated adapter may persist and return an approval receipt.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass
13
+ from datetime import datetime
14
+ from typing import Any
15
+ from uuid import uuid4
16
+
17
+ from .catalog import (
18
+ CatalogError,
19
+ _all,
20
+ _columns,
21
+ _constraint_shapes,
22
+ _execute,
23
+ _index_shapes,
24
+ _one,
25
+ _q,
26
+ )
27
+
28
+ APPROVAL_PROFILE = {
29
+ "version": "umf.table-migration-approval/0.1",
30
+ "relation": "umf_lifecycle_approvals",
31
+ "ownerOnly": True,
32
+ }
33
+ APPROVAL_BINDING_VERSION = "umf.table-migration-approval-binding/0.1"
34
+ _HEX_DIGEST = re.compile(r"^[a-f0-9]{64}$")
35
+ _APPROVAL_DEFINITIONS = [
36
+ '"approval_id" pg_catalog.uuid NOT NULL',
37
+ '"binding_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
38
+ '"binding" pg_catalog.jsonb NOT NULL',
39
+ '"decision" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
40
+ '"decider" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
41
+ '"decided_at" pg_catalog.timestamptz NOT NULL',
42
+ '"qualification_profile" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
43
+ '"evidence_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
44
+ ]
45
+ _APPROVAL_CONSTRAINTS = [
46
+ ("umf_lifecycle_approvals_pkey", 'PRIMARY KEY ("approval_id")'),
47
+ ("approval_binding_unique", 'UNIQUE ("binding_digest")'),
48
+ ("approval_binding_digest", 'CHECK ("binding_digest" ~ \'^[a-f0-9]{64}$\')'),
49
+ ("approval_binding_object", 'CHECK (pg_catalog.jsonb_typeof("binding")=\'object\')'),
50
+ ("approval_decision", 'CHECK ("decision" IN (\'approved\',\'denied\'))'),
51
+ ("approval_decider", 'CHECK ("decider"<>\'\')'),
52
+ ("approval_profile", 'CHECK ("qualification_profile"<>\'\')'),
53
+ ("approval_evidence_digest", 'CHECK ("evidence_digest" ~ \'^[a-f0-9]{64}$\')'),
54
+ ]
55
+ _APPROVAL_STATE = """SELECT c.relkind,c.relpersistence,r.rolname,c.relrowsecurity,c.relforcerowsecurity,
56
+ c.relispartition,c.relhassubclass,c.relhasrules,c.relreplident,
57
+ EXISTS(SELECT FROM pg_catalog.pg_trigger t WHERE t.tgrelid=c.oid AND NOT t.tgisinternal),
58
+ EXISTS(SELECT FROM pg_catalog.pg_inherits i WHERE i.inhrelid=c.oid),
59
+ EXISTS(SELECT FROM pg_catalog.pg_policy p WHERE p.polrelid=c.oid),r.oid,c.oid,c.relam,
60
+ EXISTS(SELECT FROM pg_catalog.pg_depend d WHERE d.refclassid='pg_catalog.pg_class'::pg_catalog.regclass
61
+ AND d.refobjid=c.oid AND NOT (d.classid='pg_catalog.pg_class'::pg_catalog.regclass
62
+ AND EXISTS(SELECT FROM pg_catalog.pg_class dep WHERE dep.oid=d.objid AND dep.relkind='i'
63
+ AND dep.relnamespace=c.relnamespace)) AND NOT (d.classid='pg_catalog.pg_constraint'::pg_catalog.regclass
64
+ AND EXISTS(SELECT FROM pg_catalog.pg_constraint k WHERE k.oid=d.objid AND k.conrelid=c.oid))
65
+ AND d.deptype NOT IN ('i','a'))
66
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
67
+ JOIN pg_catalog.pg_roles r ON r.oid=c.relowner WHERE n.nspname=%s AND c.relname=%s"""
68
+
69
+
70
+ def _canonical(value: Any) -> bytes:
71
+ try:
72
+ return json.dumps(value, ensure_ascii=False, sort_keys=True,
73
+ separators=(",", ":"), allow_nan=False).encode("utf-8")
74
+ except (TypeError, ValueError, UnicodeError):
75
+ raise CatalogError("approval-binding-invalid") from None
76
+
77
+
78
+ def _digest(value: Any) -> str:
79
+ return hashlib.sha256(_canonical(value)).hexdigest()
80
+
81
+
82
+ def _require_digest(value: Any, *, nullable: bool = False) -> str | None:
83
+ if nullable and value is None:
84
+ return None
85
+ if type(value) is not str or _HEX_DIGEST.fullmatch(value) is None:
86
+ raise CatalogError("approval-binding-invalid")
87
+ return value
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class TargetIdentity:
92
+ """Stable non-secret identity for one installed database target."""
93
+
94
+ engine: str
95
+ profile: str
96
+ installation_id: str
97
+ database_oid: int
98
+ database: str
99
+ schema: str
100
+ module: str
101
+ owner_role: str
102
+
103
+ def as_json(self) -> dict[str, Any]:
104
+ if (self.engine != "postgresql" or not self.profile or not self.installation_id
105
+ or type(self.database_oid) is not int or self.database_oid <= 0
106
+ or any(type(value) is not str or not value for value in
107
+ (self.database, self.schema, self.module, self.owner_role))):
108
+ raise CatalogError("approval-target-identity-invalid")
109
+ return {
110
+ "engine": self.engine,
111
+ "profile": self.profile,
112
+ "installationId": self.installation_id,
113
+ "databaseOid": self.database_oid,
114
+ "database": self.database,
115
+ "schema": self.schema,
116
+ "module": self.module,
117
+ "ownerRole": self.owner_role,
118
+ }
119
+
120
+ @property
121
+ def digest(self) -> str:
122
+ return _digest(self.as_json())
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class ApprovalBinding:
127
+ """Exact plan and predecessor binding presented for host approval."""
128
+
129
+ target: TargetIdentity
130
+ migration_id: str
131
+ plan_digest: str
132
+ file_digest: str
133
+ source_bundle_digest: str
134
+ expected_head: str | None
135
+ phase_digests: tuple[str, ...]
136
+ qualification_profile: str
137
+ evidence_digest: str
138
+
139
+ def as_json(self) -> dict[str, Any]:
140
+ if (type(self.migration_id) is not str or not self.migration_id
141
+ or not isinstance(self.target, TargetIdentity)
142
+ or type(self.phase_digests) is not tuple
143
+ or type(self.qualification_profile) is not str or not self.qualification_profile):
144
+ raise CatalogError("approval-binding-invalid")
145
+ return {
146
+ "version": APPROVAL_BINDING_VERSION,
147
+ "target": self.target.as_json(),
148
+ "migrationId": self.migration_id,
149
+ "planDigest": _require_digest(self.plan_digest),
150
+ "fileDigest": _require_digest(self.file_digest),
151
+ "sourceBundleDigest": _require_digest(self.source_bundle_digest),
152
+ "expectedHead": _require_digest(self.expected_head, nullable=True),
153
+ "phaseDigests": [_require_digest(value) for value in self.phase_digests],
154
+ "qualificationProfile": self.qualification_profile,
155
+ "evidenceDigest": _require_digest(self.evidence_digest),
156
+ }
157
+
158
+ @property
159
+ def digest(self) -> str:
160
+ return _digest(self.as_json())
161
+
162
+
163
+ @dataclass(frozen=True, slots=True)
164
+ class ApprovalReceipt:
165
+ """Receipt returned from a protected host-owned approval store.
166
+
167
+ Values copied from a migration source are never accepted as a receipt.
168
+ The host adapter verifies catalog ownership/ACL before constructing this
169
+ value and obtains decider/time from the authenticated database session.
170
+ """
171
+
172
+ receipt_id: str
173
+ binding_digest: str
174
+ decision: str
175
+ decider: str
176
+ decided_at: str
177
+ qualification_profile: str
178
+ evidence_digest: str
179
+
180
+ def verify(self, binding: ApprovalBinding) -> None:
181
+ try:
182
+ decided_at = datetime.fromisoformat(self.decided_at)
183
+ except (AttributeError, ValueError):
184
+ decided_at = None
185
+ if (type(self.receipt_id) is not str or not self.receipt_id
186
+ or _require_digest(self.binding_digest) != binding.digest
187
+ or self.decision != "approved"
188
+ or type(self.decider) is not str or not self.decider
189
+ or decided_at is None or decided_at.tzinfo is None
190
+ or type(self.qualification_profile) is not str or not self.qualification_profile
191
+ or self.qualification_profile != binding.qualification_profile
192
+ or _require_digest(self.evidence_digest) != binding.evidence_digest):
193
+ raise CatalogError("approval-receipt-mismatch")
194
+
195
+
196
+ def _create_approval_relation(connection: Any, schema: str,
197
+ relation: str = APPROVAL_PROFILE["relation"]) -> dict[str, str]:
198
+ definitions = list(_APPROVAL_DEFINITIONS)
199
+ aliases: dict[str, str] = {}
200
+ for name, body in _APPROVAL_CONSTRAINTS:
201
+ actual = name if relation == APPROVAL_PROFILE["relation"] else "umf_verify_" + uuid4().hex
202
+ aliases[actual] = name
203
+ definitions.append("CONSTRAINT " + _q(actual) + " " + body)
204
+ _execute(connection, "CREATE TABLE " + _q(schema) + "." + _q(relation)
205
+ + " (" + ", ".join(definitions) + ") USING heap")
206
+ return aliases
207
+
208
+
209
+ def _verify_approval_relation(connection: Any, source: dict[str, Any], *,
210
+ create: bool = False) -> bool:
211
+ """Verify exact selected receipt schema, owner-only ACL and catalog shape."""
212
+ schema, owner = source["configuration"]["schema"], source["configuration"]["ownerRole"]
213
+ relation = APPROVAL_PROFILE["relation"]
214
+ state = _one(connection, _APPROVAL_STATE, (schema, relation))
215
+ if state is None:
216
+ if not create:
217
+ return False
218
+ _create_approval_relation(connection, schema)
219
+ state = _one(connection, _APPROVAL_STATE, (schema, relation))
220
+ if tuple(state[:12]) != ("r", "p", owner, False, False, False, False, False,
221
+ "d", False, False, False):
222
+ raise CatalogError("approval-catalog-mismatch")
223
+ if state[15:] != (False,):
224
+ raise CatalogError("approval-catalog-mismatch")
225
+ owner_id, relation_id = state[12:14]
226
+ heap_id = _one(connection, "SELECT oid FROM pg_catalog.pg_am WHERE amname='heap'")[0]
227
+ if state[14] != heap_id:
228
+ raise CatalogError("approval-catalog-mismatch")
229
+ _execute(connection, "LOCK TABLE " + _q(schema) + "." + _q(relation)
230
+ + " IN ACCESS EXCLUSIVE MODE")
231
+ if _one(connection, _APPROVAL_STATE, (schema, relation)) != state:
232
+ raise CatalogError("approval-catalog-mismatch")
233
+ actual_acl = _all(connection, """SELECT x.grantor,x.grantee,x.privilege_type,x.is_grantable
234
+ FROM pg_catalog.pg_class c,LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) x
235
+ WHERE c.oid=%s ORDER BY 1,2,3,4""", (relation_id,))
236
+ expected_acl = _all(connection, """SELECT grantor,grantee,privilege_type,is_grantable
237
+ FROM pg_catalog.aclexplode(pg_catalog.acldefault('r',%s::pg_catalog.oid)) ORDER BY 1,2,3,4""", (owner_id,))
238
+ if (actual_acl != expected_acl
239
+ or _one(connection, """SELECT count(*) FROM pg_catalog.pg_attribute a,
240
+ LATERAL pg_catalog.aclexplode(a.attacl) x WHERE a.attrelid=%s""", (relation_id,)) != (0,)):
241
+ raise CatalogError("approval-privilege-mismatch")
242
+ temporary = "umf_verify_" + uuid4().hex
243
+ aliases = _create_approval_relation(connection, schema, temporary)
244
+ if (_columns(connection, schema, relation) != _columns(connection, schema, temporary)
245
+ or _constraint_shapes(connection, schema, relation, {})
246
+ != _constraint_shapes(connection, schema, temporary, aliases)
247
+ or _index_shapes(connection, schema, relation, {})
248
+ != _index_shapes(connection, schema, temporary, aliases)):
249
+ _execute(connection, "DROP TABLE " + _q(schema) + "." + _q(temporary))
250
+ raise CatalogError("approval-catalog-mismatch")
251
+ _execute(connection, "DROP TABLE " + _q(schema) + "." + _q(temporary))
252
+ return True
253
+
254
+
255
+ def _approval_shape(connection: Any, source: dict[str, Any]) -> dict[str, Any]:
256
+ """Return read-only native shape after the trusted scratch-schema proof."""
257
+ from .catalog import _COLUMNS, _CONSTRAINTS, _INDEXES
258
+
259
+ schema, relation = source["configuration"]["schema"], APPROVAL_PROFILE["relation"]
260
+ if not _verify_approval_relation(connection, source):
261
+ raise CatalogError("approval-catalog-mismatch")
262
+ state = _one(connection, _APPROVAL_STATE, (schema, relation))
263
+ if state is None:
264
+ raise CatalogError("approval-catalog-mismatch")
265
+ relation_oid = state[13]
266
+ table_acl = _all(connection, """SELECT x.grantor,x.grantee,x.privilege_type,x.is_grantable
267
+ FROM pg_catalog.pg_class c,LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) x
268
+ WHERE c.oid=%s ORDER BY 1,2,3,4""", (relation_oid,))
269
+ column_acl = _all(connection, """SELECT a.attname,x.grantor,x.grantee,x.privilege_type,x.is_grantable
270
+ FROM pg_catalog.pg_attribute a,LATERAL pg_catalog.aclexplode(a.attacl) x
271
+ WHERE a.attrelid=%s ORDER BY 1,2,3,4,5""", (relation_oid,))
272
+ return {
273
+ "state": list(state),
274
+ "columns": _all(connection, _COLUMNS, (schema, relation)),
275
+ "constraints": _all(connection, _CONSTRAINTS, (schema, relation)),
276
+ "indexes": _all(connection, _INDEXES, (schema, relation)),
277
+ "tableAcl": table_acl,
278
+ "columnAcl": column_acl,
279
+ }
280
+
281
+
282
+ def _approval_shape_steps(schema: str):
283
+ """Read-only pg_catalog observer for ordinary generated head clients."""
284
+ from .catalog import _COLUMNS, _CONSTRAINTS, _INDEXES
285
+ from .probe import _Query
286
+
287
+ relation = APPROVAL_PROFILE["relation"]
288
+ state = yield _Query("one", _APPROVAL_STATE, (schema, relation))
289
+ if state is None:
290
+ raise CatalogError("approval-catalog-mismatch")
291
+ relation_oid = state[13]
292
+ table_acl = yield _Query("all", """SELECT x.grantor,x.grantee,x.privilege_type,x.is_grantable
293
+ FROM pg_catalog.pg_class c,LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) x
294
+ WHERE c.oid=%s ORDER BY 1,2,3,4""", (relation_oid,))
295
+ column_acl = yield _Query("all", """SELECT a.attname,x.grantor,x.grantee,x.privilege_type,x.is_grantable
296
+ FROM pg_catalog.pg_attribute a,LATERAL pg_catalog.aclexplode(a.attacl) x
297
+ WHERE a.attrelid=%s ORDER BY 1,2,3,4,5""", (relation_oid,))
298
+ return {
299
+ "state": list(state),
300
+ "columns": (yield _Query("all", _COLUMNS, (schema, relation))),
301
+ "constraints": (yield _Query("all", _CONSTRAINTS, (schema, relation))),
302
+ "indexes": (yield _Query("all", _INDEXES, (schema, relation))),
303
+ "tableAcl": table_acl,
304
+ "columnAcl": column_acl,
305
+ }
306
+
307
+
308
+ def _record_approval(connection: Any, source: dict[str, Any], binding: ApprovalBinding, *,
309
+ decision: str, qualification_profile: str,
310
+ evidence_digest: str) -> ApprovalReceipt:
311
+ """Persist an immutable decision under the authenticated owner session."""
312
+ from psycopg.types.json import Jsonb
313
+
314
+ if decision not in {"approved", "denied"}:
315
+ raise CatalogError("approval-decision-invalid")
316
+ if (type(qualification_profile) is not str or not qualification_profile
317
+ or _require_digest(evidence_digest) is None
318
+ or qualification_profile != binding.qualification_profile
319
+ or evidence_digest != binding.evidence_digest):
320
+ raise CatalogError("approval-binding-invalid")
321
+ schema = source["configuration"]["schema"]
322
+ relation = _q(schema) + "." + _q(APPROVAL_PROFILE["relation"])
323
+ existing = _approval_row(connection, schema, binding)
324
+ if existing is not None:
325
+ receipt = existing
326
+ if (receipt.decision != decision or receipt.qualification_profile != qualification_profile
327
+ or receipt.evidence_digest != evidence_digest):
328
+ raise CatalogError("approval-receipt-conflict")
329
+ return receipt
330
+ decider = _one(connection, "SELECT session_user")[0]
331
+ if type(decider) is not str or not decider:
332
+ raise CatalogError("approval-decider-unavailable")
333
+ receipt_id = str(uuid4())
334
+ row = _one(connection, """INSERT INTO """ + relation + """
335
+ (approval_id,binding_digest,binding,decision,decider,decided_at,qualification_profile,evidence_digest)
336
+ VALUES (%s,%s,%s,%s,%s,pg_catalog.clock_timestamp(),%s,%s)
337
+ RETURNING approval_id::pg_catalog.text,decided_at""",
338
+ (receipt_id, binding.digest, Jsonb(binding.as_json()), decision,
339
+ decider, qualification_profile, evidence_digest))
340
+ if row is None or row[0] != receipt_id or row[1] is None:
341
+ raise CatalogError("approval-receipt-write-failed")
342
+ return ApprovalReceipt(receipt_id, binding.digest, decision, decider,
343
+ row[1].isoformat(), qualification_profile, evidence_digest)
344
+
345
+
346
+ def _approval_row(connection: Any, schema: str,
347
+ binding: ApprovalBinding) -> ApprovalReceipt | None:
348
+ row = _one(connection, """SELECT approval_id::pg_catalog.text,binding_digest,binding,decision,
349
+ decider,decided_at,qualification_profile,evidence_digest
350
+ FROM """ + _q(schema) + "." + _q(APPROVAL_PROFILE["relation"])
351
+ + " WHERE binding_digest=%s", (binding.digest,))
352
+ if row is None:
353
+ return None
354
+ if row[2] != binding.as_json():
355
+ raise CatalogError("approval-receipt-mismatch")
356
+ receipt = ApprovalReceipt(row[0], row[1], row[3], row[4],
357
+ row[5].isoformat() if row[5] is not None else "",
358
+ row[6], row[7])
359
+ if receipt.decision == "approved":
360
+ receipt.verify(binding)
361
+ elif (receipt.decision != "denied" or receipt.binding_digest != binding.digest
362
+ or receipt.qualification_profile != binding.qualification_profile
363
+ or receipt.evidence_digest != binding.evidence_digest):
364
+ raise CatalogError("approval-receipt-mismatch")
365
+ return receipt
366
+