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,358 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Inert, closed PostgreSQL syntax containment. This never authorizes execution.
|
|
3
|
+
|
|
4
|
+
The parser is trusted host code, not a caller-supplied AST. Native catalog,
|
|
5
|
+
privilege, operator/type resolution and approval remain host obligations.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from typing import Protocol
|
|
12
|
+
|
|
13
|
+
PROFILE = 'umf.sql-containment/0.1'
|
|
14
|
+
PARSER = 'pglast@7.20/postgresql17.7'
|
|
15
|
+
MAX_BYTES = 262144
|
|
16
|
+
MAX_NODES = 20000
|
|
17
|
+
MAX_DEPTH = 64
|
|
18
|
+
MAX_STATEMENTS = 128
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SqlParser(Protocol):
|
|
22
|
+
identity: str
|
|
23
|
+
|
|
24
|
+
def parse_json(self, source: str) -> str: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ContainmentRefused(ValueError):
|
|
28
|
+
def __init__(self, code, path, offset=None):
|
|
29
|
+
self.code, self.path, self.offset = code, path, offset
|
|
30
|
+
super().__init__(code)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _fail(code, path, value=None):
|
|
34
|
+
offset = value.get('location') if isinstance(value, dict) else None
|
|
35
|
+
raise ContainmentRefused(code, path, offset if type(offset) is int and offset >= 0 else None)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _object(value, keys, path):
|
|
39
|
+
if not isinstance(value, dict) or set(value) - set(keys):
|
|
40
|
+
_fail('SQL_UNSUPPORTED_FIELDS', path, value)
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _strings(value, path):
|
|
45
|
+
if not isinstance(value, list) or not value:
|
|
46
|
+
_fail('SQL_IDENTIFIER', path)
|
|
47
|
+
result = []
|
|
48
|
+
for item in value:
|
|
49
|
+
if (not isinstance(item, dict) or set(item) != {'String'}
|
|
50
|
+
or not isinstance(item['String'], dict) or set(item['String']) != {'sval'}
|
|
51
|
+
or not isinstance(item['String']['sval'], str)):
|
|
52
|
+
_fail('SQL_IDENTIFIER', path)
|
|
53
|
+
result.append(item['String']['sval'])
|
|
54
|
+
return result
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _name(value):
|
|
58
|
+
return isinstance(value, str) and 0 < len(value.encode('utf-8')) <= 63 and '\x00' not in value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Check:
|
|
62
|
+
def __init__(self, policy):
|
|
63
|
+
_object(policy, {'profile', 'schema', 'tables', 'indexes', 'roles'}, '/policy')
|
|
64
|
+
if policy.get('profile') != PROFILE or not _name(policy.get('schema')):
|
|
65
|
+
_fail('SQL_POLICY', '/policy')
|
|
66
|
+
if policy['schema'].startswith('pg_') or policy['schema'] in {'public', 'information_schema'}:
|
|
67
|
+
_fail('SQL_POLICY', '/policy/schema')
|
|
68
|
+
self.schema = policy['schema']
|
|
69
|
+
for kind in ('tables', 'indexes', 'roles'):
|
|
70
|
+
items = policy.get(kind)
|
|
71
|
+
if (not isinstance(items, list) or len(items) > 1000
|
|
72
|
+
or any(not _name(x) for x in items) or len(set(items)) != len(items)):
|
|
73
|
+
_fail('SQL_POLICY', '/policy/' + kind)
|
|
74
|
+
setattr(self, kind, set(items))
|
|
75
|
+
self.references = set()
|
|
76
|
+
self.nodes = 0
|
|
77
|
+
|
|
78
|
+
def relation(self, value, path, ctes=frozenset(), *, target=False):
|
|
79
|
+
_object(value, {'catalogname', 'schemaname', 'relname', 'inh', 'relpersistence', 'alias', 'location'}, path)
|
|
80
|
+
if value.get('catalogname') or value.get('relpersistence', 'p') != 'p':
|
|
81
|
+
_fail('SQL_RELATION', path, value)
|
|
82
|
+
schema, table = value.get('schemaname'), value.get('relname')
|
|
83
|
+
if schema is None and not target and table in ctes:
|
|
84
|
+
pass
|
|
85
|
+
elif schema != self.schema or table not in self.tables:
|
|
86
|
+
_fail('SQL_OBJECT_OUTSIDE_INVENTORY', path, value)
|
|
87
|
+
else:
|
|
88
|
+
self.references.add((schema, table))
|
|
89
|
+
if 'alias' in value:
|
|
90
|
+
alias = _object(value['alias'], {'aliasname', 'colnames'}, path + '/alias')
|
|
91
|
+
if not _name(alias.get('aliasname')) or alias.get('colnames'):
|
|
92
|
+
_fail('SQL_ALIAS', path + '/alias')
|
|
93
|
+
|
|
94
|
+
def type_name(self, value, path):
|
|
95
|
+
_object(value, {'names', 'typemod', 'typmods', 'location'}, path)
|
|
96
|
+
names = _strings(value.get('names'), path + '/names')
|
|
97
|
+
if len(names) != 2 or names[0] != 'pg_catalog' or names[1] not in {
|
|
98
|
+
'bool', 'int2', 'int4', 'int8', 'numeric', 'float4', 'float8', 'text', 'varchar',
|
|
99
|
+
'bpchar', 'uuid', 'date', 'timestamp', 'timestamptz', 'time', 'timetz', 'bytea'}:
|
|
100
|
+
_fail('SQL_TYPE_OUTSIDE_INVENTORY', path, value)
|
|
101
|
+
if value.get('typemod', -1) != -1:
|
|
102
|
+
_fail('SQL_TYPE_MODIFIER', path, value)
|
|
103
|
+
for i, item in enumerate(value.get('typmods', [])):
|
|
104
|
+
self.node(item, path + '/typmods/' + str(i), 1, frozenset())
|
|
105
|
+
|
|
106
|
+
def node(self, node, path, depth=0, ctes=frozenset()):
|
|
107
|
+
self.nodes += 1
|
|
108
|
+
if self.nodes > MAX_NODES or depth > MAX_DEPTH:
|
|
109
|
+
_fail('SQL_AST_LIMIT', path)
|
|
110
|
+
if not isinstance(node, dict) or len(node) != 1:
|
|
111
|
+
_fail('SQL_AST_NODE', path)
|
|
112
|
+
tag, value = next(iter(node.items()))
|
|
113
|
+
if not isinstance(value, dict):
|
|
114
|
+
_fail('SQL_AST_NODE', path)
|
|
115
|
+
p = path + '/' + tag
|
|
116
|
+
|
|
117
|
+
def fields(*keys):
|
|
118
|
+
return _object(value, keys, p)
|
|
119
|
+
|
|
120
|
+
def child(key, scope=ctes):
|
|
121
|
+
if key in value:
|
|
122
|
+
self.node(value[key], p + '/' + key, depth + 1, scope)
|
|
123
|
+
|
|
124
|
+
def children(key, scope=ctes):
|
|
125
|
+
if key not in value:
|
|
126
|
+
return
|
|
127
|
+
if not isinstance(value[key], list):
|
|
128
|
+
_fail('SQL_AST_NODE', p + '/' + key)
|
|
129
|
+
for i, item in enumerate(value[key]):
|
|
130
|
+
self.node(item, p + '/' + key + '/' + str(i), depth + 1, scope)
|
|
131
|
+
|
|
132
|
+
if tag in {'SelectStmt', 'UpdateStmt', 'DeleteStmt', 'InsertStmt'}:
|
|
133
|
+
keys = {
|
|
134
|
+
'SelectStmt': ('targetList', 'fromClause', 'whereClause', 'groupClause', 'havingClause', 'sortClause', 'limitOffset', 'limitCount', 'limitOption', 'op', 'all', 'withClause', 'valuesLists'),
|
|
135
|
+
'UpdateStmt': ('relation', 'targetList', 'whereClause', 'fromClause', 'returningList', 'withClause'),
|
|
136
|
+
'DeleteStmt': ('relation', 'whereClause', 'usingClause', 'returningList', 'withClause'),
|
|
137
|
+
'InsertStmt': ('relation', 'cols', 'selectStmt', 'returningList', 'override', 'withClause'),
|
|
138
|
+
}[tag]
|
|
139
|
+
fields(*keys)
|
|
140
|
+
if value.get('op', 'SETOP_NONE') != 'SETOP_NONE' or value.get('all', False):
|
|
141
|
+
_fail('SQL_UNSUPPORTED_SET_OPERATION', p)
|
|
142
|
+
if value.get('limitOption', 'LIMIT_OPTION_DEFAULT') not in {'LIMIT_OPTION_DEFAULT', 'LIMIT_OPTION_COUNT'}:
|
|
143
|
+
_fail('SQL_UNSUPPORTED_LIMIT', p)
|
|
144
|
+
if value.get('override', 'OVERRIDING_NOT_SET') != 'OVERRIDING_NOT_SET':
|
|
145
|
+
_fail('SQL_UNSUPPORTED_OVERRIDE', p)
|
|
146
|
+
scope = set(ctes)
|
|
147
|
+
if 'withClause' in value:
|
|
148
|
+
clause = _object(value['withClause'], {'ctes', 'location', 'recursive'}, p + '/withClause')
|
|
149
|
+
if clause.get('recursive') or not isinstance(clause.get('ctes'), list):
|
|
150
|
+
_fail('SQL_UNSUPPORTED_CTE', p + '/withClause')
|
|
151
|
+
for i, item in enumerate(clause['ctes']):
|
|
152
|
+
q = p + '/withClause/ctes/' + str(i)
|
|
153
|
+
if not isinstance(item, dict) or set(item) != {'CommonTableExpr'}:
|
|
154
|
+
_fail('SQL_UNSUPPORTED_CTE', q)
|
|
155
|
+
cte = _object(item['CommonTableExpr'], {'ctename', 'ctematerialized', 'ctequery', 'location'}, q)
|
|
156
|
+
name = cte.get('ctename')
|
|
157
|
+
if not _name(name) or name in scope or name in self.tables or set(cte.get('ctequery', {})) != {'SelectStmt'}:
|
|
158
|
+
_fail('SQL_UNSUPPORTED_CTE', q)
|
|
159
|
+
if cte.get('ctematerialized', 'CTEMaterializeDefault') not in {'CTEMaterializeDefault', 'CTEMaterializeAlways', 'CTEMaterializeNever'}:
|
|
160
|
+
_fail('SQL_UNSUPPORTED_CTE', q)
|
|
161
|
+
self.node(cte['ctequery'], q + '/ctequery', depth + 1, frozenset(scope))
|
|
162
|
+
scope.add(name)
|
|
163
|
+
scope = frozenset(scope)
|
|
164
|
+
if 'relation' in value:
|
|
165
|
+
self.relation(value['relation'], p + '/relation', target=True)
|
|
166
|
+
for key in ('targetList', 'fromClause', 'groupClause', 'sortClause', 'returningList', 'usingClause', 'cols'):
|
|
167
|
+
children(key, scope)
|
|
168
|
+
for key in ('whereClause', 'havingClause', 'limitOffset', 'limitCount', 'selectStmt'):
|
|
169
|
+
child(key, scope)
|
|
170
|
+
for i, row in enumerate(value.get('valuesLists', [])):
|
|
171
|
+
if not isinstance(row, dict) or set(row) != {'List'}:
|
|
172
|
+
_fail('SQL_AST_NODE', p + '/valuesLists')
|
|
173
|
+
items = _object(row['List'], {'items'}, p + '/valuesLists/' + str(i)).get('items')
|
|
174
|
+
if not isinstance(items, list):
|
|
175
|
+
_fail('SQL_AST_NODE', p + '/valuesLists')
|
|
176
|
+
for j, item in enumerate(items):
|
|
177
|
+
self.node(item, p + '/valuesLists/' + str(i) + '/' + str(j), depth + 1, scope)
|
|
178
|
+
elif tag == 'RangeVar':
|
|
179
|
+
self.relation(value, p, ctes)
|
|
180
|
+
elif tag == 'RangeSubselect':
|
|
181
|
+
fields('subquery', 'alias', 'lateral')
|
|
182
|
+
if value.get('lateral'):
|
|
183
|
+
_fail('SQL_UNSUPPORTED_LATERAL', p)
|
|
184
|
+
if set(value.get('subquery', {})) != {'SelectStmt'}:
|
|
185
|
+
_fail('SQL_UNSUPPORTED_SUBQUERY', p)
|
|
186
|
+
child('subquery')
|
|
187
|
+
alias = _object(value.get('alias'), {'aliasname'}, p + '/alias')
|
|
188
|
+
if not _name(alias.get('aliasname')):
|
|
189
|
+
_fail('SQL_ALIAS', p)
|
|
190
|
+
elif tag == 'ResTarget':
|
|
191
|
+
fields('name', 'val', 'location')
|
|
192
|
+
if 'name' in value and not _name(value['name']):
|
|
193
|
+
_fail('SQL_IDENTIFIER', p)
|
|
194
|
+
child('val')
|
|
195
|
+
elif tag == 'ColumnRef':
|
|
196
|
+
fields('fields', 'location')
|
|
197
|
+
names = value.get('fields')
|
|
198
|
+
if names == [{'A_Star': {}}]:
|
|
199
|
+
return
|
|
200
|
+
names = _strings(names, p + '/fields')
|
|
201
|
+
if len(names) > 3 or len(names) == 3 and names[0] != self.schema:
|
|
202
|
+
_fail('SQL_COLUMN_REFERENCE', p, value)
|
|
203
|
+
elif tag == 'A_Const':
|
|
204
|
+
fields('ival', 'fval', 'sval', 'boolval', 'isnull', 'location')
|
|
205
|
+
if len(set(value) - {'location'}) != 1:
|
|
206
|
+
_fail('SQL_CONSTANT', p)
|
|
207
|
+
for key, scalar_key, scalar_type in [('ival', 'ival', int), ('fval', 'fval', str), ('sval', 'sval', str), ('boolval', 'boolval', bool)]:
|
|
208
|
+
if key in value:
|
|
209
|
+
_object(value[key], {scalar_key}, p + '/' + key)
|
|
210
|
+
if scalar_key in value[key] and type(value[key][scalar_key]) is not scalar_type:
|
|
211
|
+
_fail('SQL_CONSTANT', p)
|
|
212
|
+
if 'isnull' in value and value['isnull'] is not True:
|
|
213
|
+
_fail('SQL_CONSTANT', p)
|
|
214
|
+
elif tag == 'NullTest':
|
|
215
|
+
fields('arg', 'nulltesttype', 'argisrow', 'location')
|
|
216
|
+
if value.get('nulltesttype') not in {'IS_NULL', 'IS_NOT_NULL'} or value.get('argisrow'):
|
|
217
|
+
_fail('SQL_EXPRESSION', p)
|
|
218
|
+
child('arg')
|
|
219
|
+
elif tag == 'BoolExpr':
|
|
220
|
+
fields('boolop', 'args', 'location')
|
|
221
|
+
if value.get('boolop') not in {'AND_EXPR', 'OR_EXPR', 'NOT_EXPR'}:
|
|
222
|
+
_fail('SQL_EXPRESSION', p)
|
|
223
|
+
children('args')
|
|
224
|
+
elif tag == 'A_Expr':
|
|
225
|
+
fields('kind', 'name', 'lexpr', 'rexpr', 'location')
|
|
226
|
+
names = _strings(value.get('name'), p + '/name')
|
|
227
|
+
# No search-path-dependent operator lookup in this first profile.
|
|
228
|
+
if (value.get('kind') != 'AEXPR_OP' or len(names) != 2 or names[0] != 'pg_catalog'
|
|
229
|
+
or names[1] not in {'=', '<>', '<', '<=', '>', '>='}):
|
|
230
|
+
_fail('SQL_OPERATOR_OUTSIDE_INVENTORY', p, value)
|
|
231
|
+
child('lexpr'); child('rexpr')
|
|
232
|
+
elif tag == 'TypeCast':
|
|
233
|
+
fields('arg', 'typeName', 'location')
|
|
234
|
+
child('arg'); self.type_name(value.get('typeName'), p + '/typeName')
|
|
235
|
+
elif tag == 'FuncCall':
|
|
236
|
+
# Raw syntax cannot establish argument type, overload or volatility.
|
|
237
|
+
_fail('SQL_CALLABLE_UNRESOLVED', p, value)
|
|
238
|
+
elif tag == 'SortBy':
|
|
239
|
+
fields('node', 'sortby_dir', 'sortby_nulls', 'location')
|
|
240
|
+
if value.get('sortby_dir') not in {'SORTBY_DEFAULT', 'SORTBY_ASC', 'SORTBY_DESC'} or value.get('sortby_nulls') not in {'SORTBY_NULLS_DEFAULT', 'SORTBY_NULLS_FIRST', 'SORTBY_NULLS_LAST'}:
|
|
241
|
+
_fail('SQL_SORT', p)
|
|
242
|
+
child('node')
|
|
243
|
+
elif tag == 'CreateStmt':
|
|
244
|
+
fields('relation', 'tableElts', 'constraints', 'oncommit', 'if_not_exists')
|
|
245
|
+
self.relation(value.get('relation'), p + '/relation', target=True)
|
|
246
|
+
if value.get('oncommit', 'ONCOMMIT_NOOP') != 'ONCOMMIT_NOOP':
|
|
247
|
+
_fail('SQL_TABLE_OPTIONS', p)
|
|
248
|
+
children('tableElts'); children('constraints')
|
|
249
|
+
elif tag == 'ColumnDef':
|
|
250
|
+
fields('colname', 'typeName', 'is_local', 'constraints', 'location')
|
|
251
|
+
if not _name(value.get('colname')):
|
|
252
|
+
_fail('SQL_IDENTIFIER', p)
|
|
253
|
+
self.type_name(value.get('typeName'), p + '/typeName'); children('constraints')
|
|
254
|
+
elif tag == 'Constraint':
|
|
255
|
+
fields('contype', 'conname', 'location', 'raw_expr', 'initially_valid', 'skip_validation', 'keys', 'pktable', 'fk_attrs', 'pk_attrs', 'fk_matchtype', 'fk_upd_action', 'fk_del_action', 'deferrable', 'initdeferred')
|
|
256
|
+
if value.get('contype') not in {'CONSTR_NOTNULL', 'CONSTR_NULL', 'CONSTR_DEFAULT', 'CONSTR_CHECK', 'CONSTR_PRIMARY', 'CONSTR_UNIQUE', 'CONSTR_FOREIGN'}:
|
|
257
|
+
_fail('SQL_CONSTRAINT', p, value)
|
|
258
|
+
if value.get('deferrable') or value.get('initdeferred'):
|
|
259
|
+
_fail('SQL_CONSTRAINT', p)
|
|
260
|
+
if 'conname' in value and not _name(value['conname']):
|
|
261
|
+
_fail('SQL_IDENTIFIER', p)
|
|
262
|
+
for key in ('keys', 'fk_attrs', 'pk_attrs'):
|
|
263
|
+
if key in value:
|
|
264
|
+
_strings(value[key], p + '/' + key)
|
|
265
|
+
if 'pktable' in value:
|
|
266
|
+
self.relation(value['pktable'], p + '/pktable', target=True)
|
|
267
|
+
child('raw_expr')
|
|
268
|
+
elif tag == 'AlterTableStmt':
|
|
269
|
+
fields('relation', 'cmds', 'objtype', 'missing_ok')
|
|
270
|
+
if value.get('objtype') != 'OBJECT_TABLE':
|
|
271
|
+
_fail('SQL_ALTER_OBJECT', p)
|
|
272
|
+
self.relation(value.get('relation'), p + '/relation', target=True); children('cmds')
|
|
273
|
+
elif tag == 'AlterTableCmd':
|
|
274
|
+
fields('subtype', 'name', 'def', 'behavior', 'missing_ok')
|
|
275
|
+
if value.get('subtype') not in {'AT_AddColumn', 'AT_AddConstraint', 'AT_ValidateConstraint', 'AT_SetNotNull', 'AT_DropNotNull', 'AT_DropColumn', 'AT_DropConstraint', 'AT_ColumnDefault'} or value.get('behavior', 'DROP_RESTRICT') != 'DROP_RESTRICT':
|
|
276
|
+
_fail('SQL_ALTER_OPERATION', p, value)
|
|
277
|
+
child('def')
|
|
278
|
+
elif tag == 'IndexStmt':
|
|
279
|
+
fields('idxname', 'relation', 'accessMethod', 'indexParams', 'indexIncludingParams', 'whereClause', 'unique', 'concurrent', 'if_not_exists', 'nulls_not_distinct')
|
|
280
|
+
if value.get('idxname') not in self.indexes or value.get('accessMethod', 'btree') != 'btree':
|
|
281
|
+
_fail('SQL_INDEX_OUTSIDE_INVENTORY', p)
|
|
282
|
+
self.relation(value.get('relation'), p + '/relation', target=True)
|
|
283
|
+
children('indexParams'); children('indexIncludingParams'); child('whereClause')
|
|
284
|
+
elif tag == 'IndexElem':
|
|
285
|
+
fields('name', 'ordering', 'nulls_ordering')
|
|
286
|
+
if not _name(value.get('name')) or value.get('ordering') not in {'SORTBY_DEFAULT', 'SORTBY_ASC', 'SORTBY_DESC'} or value.get('nulls_ordering') not in {'SORTBY_NULLS_DEFAULT', 'SORTBY_NULLS_FIRST', 'SORTBY_NULLS_LAST'}:
|
|
287
|
+
_fail('SQL_INDEX_EXPRESSION', p)
|
|
288
|
+
elif tag == 'CommentStmt':
|
|
289
|
+
fields('objtype', 'object', 'comment')
|
|
290
|
+
if value.get('objtype') not in {'OBJECT_TABLE', 'OBJECT_COLUMN'} or set(value.get('object', {})) != {'List'}:
|
|
291
|
+
_fail('SQL_COMMENT_OBJECT', p)
|
|
292
|
+
obj = _object(value['object']['List'], {'items'}, p + '/object/List')
|
|
293
|
+
parts = _strings(obj.get('items'), p + '/object')
|
|
294
|
+
if len(parts) != (3 if value['objtype'] == 'OBJECT_COLUMN' else 2) or parts[0] != self.schema or parts[1] not in self.tables:
|
|
295
|
+
_fail('SQL_OBJECT_OUTSIDE_INVENTORY', p)
|
|
296
|
+
elif tag == 'GrantStmt':
|
|
297
|
+
fields('is_grant', 'targtype', 'objtype', 'objects', 'privileges', 'grantees', 'behavior', 'grant_option')
|
|
298
|
+
if value.get('targtype') != 'ACL_TARGET_OBJECT' or value.get('objtype') != 'OBJECT_TABLE' or value.get('grant_option') or value.get('behavior', 'DROP_RESTRICT') != 'DROP_RESTRICT':
|
|
299
|
+
_fail('SQL_GRANT', p)
|
|
300
|
+
children('objects'); children('privileges'); children('grantees')
|
|
301
|
+
if not value.get('privileges') or not value.get('grantees'):
|
|
302
|
+
_fail('SQL_GRANT', p)
|
|
303
|
+
elif tag == 'AccessPriv':
|
|
304
|
+
fields('priv_name')
|
|
305
|
+
if value.get('priv_name') not in {'select', 'insert', 'update', 'delete'}:
|
|
306
|
+
_fail('SQL_GRANT', p)
|
|
307
|
+
elif tag == 'RoleSpec':
|
|
308
|
+
fields('roletype', 'rolename', 'location')
|
|
309
|
+
if value.get('roletype') != 'ROLESPEC_CSTRING' or value.get('rolename') not in self.roles:
|
|
310
|
+
_fail('SQL_ROLE_OUTSIDE_INVENTORY', p, value)
|
|
311
|
+
else:
|
|
312
|
+
_fail('SQL_UNSUPPORTED_NODE', p, value)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def check_sql_containment(source: str, policy: dict, parser: SqlParser) -> dict:
|
|
316
|
+
"""Check every statement; retain exact SQL, return no executable plan.
|
|
317
|
+
|
|
318
|
+
Only trusted host-supplied parser implementations are admitted. This syntax
|
|
319
|
+
profile requires explicit schema/type/operator resolution, refuses all
|
|
320
|
+
function calls and unknown syntax, and cannot prove native catalog safety.
|
|
321
|
+
"""
|
|
322
|
+
result = {'profile': PROFILE, 'status': 'blocked', 'source': source, 'executionAuthorized': False}
|
|
323
|
+
try:
|
|
324
|
+
if not isinstance(source, str):
|
|
325
|
+
_fail('SQL_SOURCE', '/source')
|
|
326
|
+
raw = source.encode('utf-8')
|
|
327
|
+
if not raw or len(raw) > MAX_BYTES or b'\x00' in raw:
|
|
328
|
+
_fail('SQL_SOURCE_LIMIT', '/source')
|
|
329
|
+
result['sourceSha256'] = hashlib.sha256(raw).hexdigest()
|
|
330
|
+
checker = _Check(policy)
|
|
331
|
+
if getattr(parser, 'identity', None) != PARSER:
|
|
332
|
+
_fail('SQL_PARSER_PROFILE', '/parser')
|
|
333
|
+
try:
|
|
334
|
+
parsed = parser.parse_json(source)
|
|
335
|
+
if not isinstance(parsed, str) or len(parsed.encode('utf-8')) > MAX_BYTES * 32:
|
|
336
|
+
_fail('SQL_AST_LIMIT', '/ast')
|
|
337
|
+
tree = json.loads(parsed)
|
|
338
|
+
except ContainmentRefused:
|
|
339
|
+
raise
|
|
340
|
+
except Exception: # noqa: BLE001 -- optional parser boundary; no native exception text escapes
|
|
341
|
+
_fail('SQL_PARSE_FAILED', '/source')
|
|
342
|
+
_object(tree, {'version', 'stmts'}, '/ast')
|
|
343
|
+
if tree.get('version') != 170007 or not isinstance(tree.get('stmts'), list):
|
|
344
|
+
_fail('SQL_PARSER_PROFILE', '/ast')
|
|
345
|
+
if not 1 <= len(tree['stmts']) <= MAX_STATEMENTS:
|
|
346
|
+
_fail('SQL_STATEMENT_LIMIT', '/ast/stmts')
|
|
347
|
+
for i, stmt in enumerate(tree['stmts']):
|
|
348
|
+
path = '/ast/stmts/' + str(i)
|
|
349
|
+
_object(stmt, {'stmt', 'stmt_location', 'stmt_len'}, path)
|
|
350
|
+
checker.node(stmt.get('stmt'), path + '/stmt')
|
|
351
|
+
result.update(status='checked', parser=PARSER, statements=len(tree['stmts']),
|
|
352
|
+
references=[{'schema': s, 'table': t} for s, t in sorted(checker.references)],
|
|
353
|
+
nativeCatalogVerified=False)
|
|
354
|
+
except ContainmentRefused as error:
|
|
355
|
+
result['diagnostics'] = [{'code': error.code, 'path': error.path, 'offset': error.offset}]
|
|
356
|
+
except (ValueError, TypeError, UnicodeError, RecursionError):
|
|
357
|
+
result['diagnostics'] = [{'code': 'SQL_INPUT_INVALID', 'path': '/source', 'offset': None}]
|
|
358
|
+
return result
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Offline administrative containment check. Never opens a database connection."""
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .sql_containment import MAX_BYTES, check_sql_containment
|
|
9
|
+
from .sql_containment_parser import PglastParser
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None):
|
|
13
|
+
parser = argparse.ArgumentParser(prog='umf-sql-check', allow_abbrev=False)
|
|
14
|
+
parser.add_argument('--sql', required=True, type=Path)
|
|
15
|
+
parser.add_argument('--policy', required=True, type=Path)
|
|
16
|
+
args = parser.parse_args(argv)
|
|
17
|
+
try:
|
|
18
|
+
with args.sql.open('rb') as handle:
|
|
19
|
+
source = handle.read(MAX_BYTES + 1).decode('utf-8')
|
|
20
|
+
with args.policy.open('rb') as handle:
|
|
21
|
+
raw_policy = handle.read(MAX_BYTES + 1)
|
|
22
|
+
if len(raw_policy) > MAX_BYTES:
|
|
23
|
+
raise ValueError('policy-limit')
|
|
24
|
+
result = check_sql_containment(source, json.loads(raw_policy), PglastParser())
|
|
25
|
+
except (OSError, ValueError, UnicodeError):
|
|
26
|
+
result = {'status': 'blocked', 'executionAuthorized': False,
|
|
27
|
+
'diagnostics': [{'code': 'SQL_INPUT_INVALID', 'path': '/input', 'offset': None}]}
|
|
28
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
29
|
+
return 0 if result['status'] == 'checked' else 1
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if __name__ == '__main__':
|
|
33
|
+
sys.exit(main())
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Explicit optional parser adapter; no import-time parser loading or SQL effects."""
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from .sql_containment import PARSER, ContainmentRefused
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PglastParser:
|
|
9
|
+
identity = PARSER
|
|
10
|
+
|
|
11
|
+
def parse_json(self, source: str) -> str:
|
|
12
|
+
try:
|
|
13
|
+
installed = version('pglast')
|
|
14
|
+
except PackageNotFoundError as error:
|
|
15
|
+
raise ContainmentRefused('SQL_PARSER_UNAVAILABLE', '/parser') from error
|
|
16
|
+
if installed != '7.20':
|
|
17
|
+
raise ContainmentRefused('SQL_PARSER_VERSION', '/parser')
|
|
18
|
+
from pglast.parser import parse_sql_json
|
|
19
|
+
|
|
20
|
+
return parse_sql_json(source)
|