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,144 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Schedule closed native-head checks through existing per-call session leases.
|
|
3
|
+
|
|
4
|
+
These observations never grant data-operation admission. No source plan SQL,
|
|
5
|
+
installer authority, process-global pool or caller-selected query is accepted.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from umf_access.lifecycle import (
|
|
13
|
+
CatalogError,
|
|
14
|
+
prepare_table_correspondence,
|
|
15
|
+
prepare_table_head,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from .session_async import AsyncSession
|
|
19
|
+
from .session_policy import SessionError, SessionIdentity
|
|
20
|
+
from .session_sync import SyncSession
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _prepare(session, identity, bundle, reference, correspondence=False):
|
|
24
|
+
session.policy.role(identity) # reject unregistered subjects before source work or leases
|
|
25
|
+
if not session.policy.catalog_only:
|
|
26
|
+
raise SessionError('head observation requires catalog-only session resolution')
|
|
27
|
+
options = {'statement_timeout_ms':session.policy.statement_timeout_ms,'lock_timeout_ms':session.policy.lock_timeout_ms}
|
|
28
|
+
if correspondence:
|
|
29
|
+
probe = prepare_table_correspondence(bundle,reference,principal_role=session.policy.role(identity),audience=identity.kind,**options)
|
|
30
|
+
else:
|
|
31
|
+
probe = prepare_table_head(bundle,reference,**options)
|
|
32
|
+
if probe.schema != session.policy.schema:
|
|
33
|
+
raise SessionError('head source differs from the isolated session schema')
|
|
34
|
+
return probe
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _check_principal(session, identity, result):
|
|
38
|
+
if result.get('observedPrincipal') != session.policy.role(identity) or result.get('lifecycleAdmission') is not False:
|
|
39
|
+
raise SessionError('head observation differs from the selected principal')
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _drive(session, native, steps):
|
|
44
|
+
try:
|
|
45
|
+
query = next(steps)
|
|
46
|
+
while True:
|
|
47
|
+
with session.control_cursor(native) as cursor:
|
|
48
|
+
cursor.execute(query.statement,query.parameters) if query.parameters or query.kind=='frame' else cursor.execute(query.statement)
|
|
49
|
+
if query.kind == 'one':
|
|
50
|
+
value = cursor.fetchone()
|
|
51
|
+
elif query.kind == 'all':
|
|
52
|
+
value = cursor.fetchall()
|
|
53
|
+
elif query.kind == 'execute':
|
|
54
|
+
value = None
|
|
55
|
+
elif query.kind == 'frame':
|
|
56
|
+
value = ([c[0] for c in cursor.description],cursor.fetchall())
|
|
57
|
+
else:
|
|
58
|
+
raise SessionError('unknown internal observation step')
|
|
59
|
+
query = steps.send(value)
|
|
60
|
+
except StopIteration as result:
|
|
61
|
+
return result.value
|
|
62
|
+
finally:
|
|
63
|
+
steps.close()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def _drive_async(session, native, steps):
|
|
67
|
+
try:
|
|
68
|
+
query = next(steps)
|
|
69
|
+
while True:
|
|
70
|
+
async with session.control_cursor(native) as cursor:
|
|
71
|
+
if query.parameters or query.kind=='frame':
|
|
72
|
+
await cursor.execute(query.statement,query.parameters)
|
|
73
|
+
else:
|
|
74
|
+
await cursor.execute(query.statement)
|
|
75
|
+
if query.kind == 'one':
|
|
76
|
+
value = await cursor.fetchone()
|
|
77
|
+
elif query.kind == 'all':
|
|
78
|
+
value = await cursor.fetchall()
|
|
79
|
+
elif query.kind == 'execute':
|
|
80
|
+
value = None
|
|
81
|
+
elif query.kind == 'frame':
|
|
82
|
+
value = ([c[0] for c in cursor.description],await cursor.fetchall())
|
|
83
|
+
else:
|
|
84
|
+
raise SessionError('unknown internal observation step')
|
|
85
|
+
query = steps.send(value)
|
|
86
|
+
except StopIteration as result:
|
|
87
|
+
return result.value
|
|
88
|
+
finally:
|
|
89
|
+
steps.close()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def observe_table_head(session: SyncSession, identity: SessionIdentity,
|
|
93
|
+
bundle: dict[str, object], reference: dict[str, object]) -> dict[str, Any]:
|
|
94
|
+
"""Use one authenticated sync lease, preserving its declared TX ownership."""
|
|
95
|
+
probe = _prepare(session,identity,bundle,reference)
|
|
96
|
+
try:
|
|
97
|
+
with session.open(identity,read_only=True) as native:
|
|
98
|
+
return _check_principal(session,identity,_drive(session,native,probe.steps()))
|
|
99
|
+
except (CatalogError,SessionError):
|
|
100
|
+
raise
|
|
101
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
102
|
+
raise SessionError('native head observation failed') from None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def observe_table_head_async(session: AsyncSession, identity: SessionIdentity,
|
|
106
|
+
bundle: dict[str, object], reference: dict[str, object]) -> dict[str, Any]:
|
|
107
|
+
"""Async counterpart; cancellation propagates after shielded lease cleanup."""
|
|
108
|
+
# The bounded embedded V8 verifier is synchronous and disallows its timeout
|
|
109
|
+
# API inside an event loop. Preparation has no driver/lease access; cancelled
|
|
110
|
+
# preparation cannot later acquire a connection. All database IO stays async.
|
|
111
|
+
probe = await asyncio.to_thread(_prepare,session,identity,bundle,reference)
|
|
112
|
+
try:
|
|
113
|
+
async with session.open(identity,read_only=True) as native:
|
|
114
|
+
return _check_principal(session,identity,await _drive_async(session,native,probe.steps()))
|
|
115
|
+
except (CatalogError,SessionError):
|
|
116
|
+
raise
|
|
117
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
118
|
+
raise SessionError('native head observation failed') from None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def verify_table_correspondence(session: SyncSession, identity: SessionIdentity,
|
|
122
|
+
bundle: dict[str, object], reference: dict[str, object]) -> dict[str, Any]:
|
|
123
|
+
"""Observe live roles/ACLs/table shape in one lease; never admit an operation."""
|
|
124
|
+
probe = _prepare(session,identity,bundle,reference,True)
|
|
125
|
+
try:
|
|
126
|
+
with session.open(identity,read_only=True) as native:
|
|
127
|
+
return _check_principal(session,identity,_drive(session,native,probe.steps()))
|
|
128
|
+
except (CatalogError,SessionError):
|
|
129
|
+
raise
|
|
130
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
131
|
+
raise SessionError('native table correspondence failed') from None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def verify_table_correspondence_async(session: AsyncSession, identity: SessionIdentity,
|
|
135
|
+
bundle: dict[str, object], reference: dict[str, object]) -> dict[str, Any]:
|
|
136
|
+
"""Async live correspondence using the same fixed checks and cleanup contract."""
|
|
137
|
+
probe = await asyncio.to_thread(_prepare,session,identity,bundle,reference,True)
|
|
138
|
+
try:
|
|
139
|
+
async with session.open(identity,read_only=True) as native:
|
|
140
|
+
return _check_principal(session,identity,await _drive_async(session,native,probe.steps()))
|
|
141
|
+
except (CatalogError,SessionError):
|
|
142
|
+
raise
|
|
143
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
144
|
+
raise SessionError('native table correspondence failed') from None
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Closed generated-module wire transport; authenticated identity stays outside it."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .operation_values import loads
|
|
9
|
+
from .session_async import AsyncSession
|
|
10
|
+
from .session_policy import SessionError, SessionIdentity
|
|
11
|
+
from .session_sync import SyncSession
|
|
12
|
+
from .table_reads import AsyncTableReader, SyncTableReader
|
|
13
|
+
from .table_writes import AsyncTableWriter, SyncTableWriter, WriteOutcomeUnknown
|
|
14
|
+
|
|
15
|
+
_REQUEST={'contract','schema','kind','module','operation','call','phase','mutation','idempotency_key'}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _reason(error):
|
|
19
|
+
if isinstance(error,WriteOutcomeUnknown):return 'WRITE_OUTCOME_UNKNOWN'
|
|
20
|
+
current=error;seen=set()
|
|
21
|
+
for _ in range(8):
|
|
22
|
+
if current is None or id(current) in seen:break
|
|
23
|
+
seen.add(id(current))
|
|
24
|
+
code=getattr(current,'sqlstate',None) or getattr(current,'pgcode',None)
|
|
25
|
+
if code=='42501':return 'DENIED'
|
|
26
|
+
if code in ('23505','23503'):return 'CONFLICT'
|
|
27
|
+
if code in ('23502','22001','22003','22P02'):return 'INVALID'
|
|
28
|
+
if code=='23514':return 'PRECONDITION_FAILED'
|
|
29
|
+
if code=='22012':return 'LIMIT_EXCEEDED'
|
|
30
|
+
message=str(current)
|
|
31
|
+
if 'cursor' in message:return 'INVALID_CURSOR'
|
|
32
|
+
if message in ('required row not found','native single-row cardinality exceeded'):return 'PRECONDITION_FAILED'
|
|
33
|
+
if message=='native result row bound exceeded':return 'TOO_MANY_ROWS'
|
|
34
|
+
if 'subject has no grant' in message:return 'DENIED'
|
|
35
|
+
if message.endswith('-mismatch') or message in ('native write authority changed during execution','native write authority changed while waiting'):
|
|
36
|
+
return 'SCHEMA_MISMATCH'
|
|
37
|
+
if message in ('declared read compilation refused','declared read source check refused','operation is not declared in this module','declared query result type differs','declared query description unavailable'):
|
|
38
|
+
return 'INVALID'
|
|
39
|
+
current=getattr(current,'orig',None) or getattr(current,'__cause__',None) or getattr(current,'__context__',None)
|
|
40
|
+
return 'BUSY'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _NativeBinding:
|
|
44
|
+
def __init__(self,session,bundle,reference,binding,*,cursor_secret: bytes,outcome_secret: bytes,target='postgresql18'):
|
|
45
|
+
expected=SyncSession if self._reader_type is SyncTableReader else AsyncSession
|
|
46
|
+
if not isinstance(session,expected):raise SessionError("native binding session mode mismatch")
|
|
47
|
+
self._reader=self._reader_type(session,bundle,reference,binding,cursor_secret=cursor_secret,target=target)
|
|
48
|
+
bundle=self._reader._bundle
|
|
49
|
+
self.schema=bundle['sourceDigest'];self.module=bundle['configuration']['module']
|
|
50
|
+
if bundle['source']['format']!='json':raise SessionError('native operation binding requires JSON source')
|
|
51
|
+
document=loads(bundle['source']['utf8'])
|
|
52
|
+
module=next(m for m in document['modules'] if m['id']==self.module)
|
|
53
|
+
self._operations={op['id']:op['body']['kind'] for op in module['extensions']['umf.tables']['commands']}
|
|
54
|
+
self._writer=self._writer_type(session,bundle,reference,binding,outcome_secret=outcome_secret,target=target,_source_owner=self._reader)
|
|
55
|
+
|
|
56
|
+
def _parse(self,request,identity):
|
|
57
|
+
self._reader._session.policy.role(identity)
|
|
58
|
+
if type(request) is not dict or set(request)!=_REQUEST or request['contract']!='umf.access/1' or request['kind']!='table':
|
|
59
|
+
raise SessionError('invalid generated table request')
|
|
60
|
+
if request['schema']!=self.schema or request['module']!=self.module:
|
|
61
|
+
raise SessionError('generated table schema-mismatch')
|
|
62
|
+
operation=self._operations.get(request['operation']) if type(request['operation']) is str else None
|
|
63
|
+
if operation is None:raise SessionError('operation is not declared in this module')
|
|
64
|
+
write=operation not in ('read','query')
|
|
65
|
+
if type(request['mutation']) is not bool or request['mutation']!=write or request['phase'] not in ('invoke','observe'):
|
|
66
|
+
raise SessionError('invalid generated table request')
|
|
67
|
+
call=request['call']
|
|
68
|
+
if type(call) is not dict or call.get('kind') not in ('single','batch'):
|
|
69
|
+
raise SessionError('invalid generated table request')
|
|
70
|
+
if write:
|
|
71
|
+
expected={'kind','inputs'} if call['kind']=='single' else {'kind','items'}
|
|
72
|
+
if set(call)!=expected or (call['kind']=='single' and type(call['inputs']) is not dict) or (call['kind']=='batch' and type(call['items']) is not list):
|
|
73
|
+
raise SessionError('invalid generated table request')
|
|
74
|
+
if request['phase']=='observe' and type(request['idempotency_key']) is not str:
|
|
75
|
+
raise SessionError('invalid generated table request')
|
|
76
|
+
elif (call['kind']!='single' or not {'kind','inputs'}<=set(call)<= {'kind','inputs','size','cursor'}
|
|
77
|
+
or type(call['inputs']) is not dict or request['phase']!='invoke' or request['idempotency_key'] is not None):
|
|
78
|
+
raise SessionError('invalid generated table request')
|
|
79
|
+
return write,call
|
|
80
|
+
|
|
81
|
+
def _error(self,error):
|
|
82
|
+
code='INVALID' if isinstance(error,SessionError) and str(error)=='invalid generated table request' else _reason(error)
|
|
83
|
+
return {'schema':self.schema,'error':{'code':code}}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class _SyncAuthenticated:
|
|
88
|
+
binding: SyncNativeTableBinding
|
|
89
|
+
identity: SessionIdentity
|
|
90
|
+
|
|
91
|
+
def execute(self,request: dict[str,Any]) -> dict[str,Any]:return self.binding.execute(request,identity=self.identity)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class _AsyncAuthenticated:
|
|
96
|
+
binding: NativeTableBinding
|
|
97
|
+
identity: SessionIdentity
|
|
98
|
+
|
|
99
|
+
async def execute(self,request: dict[str,Any]) -> dict[str,Any]:return await self.binding.execute(request,identity=self.identity)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class SyncNativeTableBinding(_NativeBinding):
|
|
103
|
+
"""One plugin module; factories and current identity are host-owned per call."""
|
|
104
|
+
_reader_type=SyncTableReader
|
|
105
|
+
_writer_type=SyncTableWriter
|
|
106
|
+
|
|
107
|
+
def for_identity(self,identity: SessionIdentity) -> _SyncAuthenticated:
|
|
108
|
+
self._reader._session.policy.role(identity)
|
|
109
|
+
return _SyncAuthenticated(self,identity)
|
|
110
|
+
|
|
111
|
+
def execute(self,request: dict[str,Any],*,identity: SessionIdentity) -> dict[str,Any]:
|
|
112
|
+
try:
|
|
113
|
+
write,call=self._parse(request,identity)
|
|
114
|
+
if not write:
|
|
115
|
+
value=self._reader.read(identity,request['operation'],call['inputs'],size=call.get('size'),cursor=call.get('cursor'))
|
|
116
|
+
else:
|
|
117
|
+
method=('observe' if request['phase']=='observe' else 'write')+('_batch' if call['kind']=='batch' else '')
|
|
118
|
+
value=getattr(self._writer,method)(identity,request['operation'],call.get('inputs',call.get('items')),key=request['idempotency_key'])
|
|
119
|
+
return {'schema':self.schema,'table':value}
|
|
120
|
+
except Exception as error: # noqa: BLE001 -- closed wire returns only fixed SDK error codes
|
|
121
|
+
return self._error(error)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class NativeTableBinding(_NativeBinding):
|
|
125
|
+
"""Async module wire transport; cancellation propagates after native cleanup."""
|
|
126
|
+
_reader_type=AsyncTableReader
|
|
127
|
+
_writer_type=AsyncTableWriter
|
|
128
|
+
|
|
129
|
+
def for_identity(self,identity: SessionIdentity) -> _AsyncAuthenticated:
|
|
130
|
+
self._reader._session.policy.role(identity)
|
|
131
|
+
return _AsyncAuthenticated(self,identity)
|
|
132
|
+
|
|
133
|
+
async def execute(self,request: dict[str,Any],*,identity: SessionIdentity) -> dict[str,Any]:
|
|
134
|
+
try:
|
|
135
|
+
write,call=self._parse(request,identity)
|
|
136
|
+
if not write:
|
|
137
|
+
value=await self._reader.read(identity,request['operation'],call['inputs'],size=call.get('size'),cursor=call.get('cursor'))
|
|
138
|
+
else:
|
|
139
|
+
method=('observe' if request['phase']=='observe' else 'write')+('_batch' if call['kind']=='batch' else '')
|
|
140
|
+
value=await getattr(self._writer,method)(identity,request['operation'],call.get('inputs',call.get('items')),key=request['idempotency_key'])
|
|
141
|
+
return {'schema':self.schema,'table':value}
|
|
142
|
+
except Exception as error: # noqa: BLE001 -- sanitize all native diagnostics; BaseException cancellation is preserved
|
|
143
|
+
return self._error(error)
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Exact native operation values, bounded frames and opaque page tokens."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
import struct
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
from decimal import Decimal, InvalidOperation
|
|
14
|
+
from uuid import UUID
|
|
15
|
+
|
|
16
|
+
from .session_policy import SessionError
|
|
17
|
+
|
|
18
|
+
MAX_FRAME=8*1024*1024
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def canonical(value):
|
|
22
|
+
return json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def bounded_size(value, limit=MAX_FRAME):
|
|
26
|
+
"""Stop before assembling a potentially huge repeated-key JSON frame."""
|
|
27
|
+
size=0
|
|
28
|
+
encoder=json.JSONEncoder(ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)
|
|
29
|
+
for chunk in encoder.iterencode(value):
|
|
30
|
+
size+=len(chunk.encode('utf-8'))
|
|
31
|
+
if size>limit:raise SessionError('native wire frame bound exceeded')
|
|
32
|
+
return size
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def digest(value):
|
|
36
|
+
return hashlib.sha256(canonical(value).encode('utf-8')).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unique(pairs):
|
|
40
|
+
result={}
|
|
41
|
+
for key,value in pairs:
|
|
42
|
+
if key in result:raise SessionError('invalid operation JSON')
|
|
43
|
+
result[key]=value
|
|
44
|
+
return result
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def loads(raw):
|
|
48
|
+
try:return json.loads(raw,object_pairs_hook=_unique,parse_constant=lambda _:(_ for _ in ()).throw(ValueError()))
|
|
49
|
+
except (ValueError,TypeError,RecursionError):raise SessionError('invalid operation JSON') from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def token_encode(secret,scope,after):
|
|
53
|
+
raw=canonical({'version':'umf.table-cursor/0.1','scope':scope,'after':after}).encode('utf-8')
|
|
54
|
+
encoded=base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
|
|
55
|
+
result=encoded+'.'+hmac.new(secret,encoded.encode('ascii'),hashlib.sha256).hexdigest()
|
|
56
|
+
if len(result)>16384:raise SessionError('cursor capacity exceeded')
|
|
57
|
+
return result
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def token_decode(secret,token):
|
|
61
|
+
if type(token) is not str or len(token)>16384:raise SessionError('invalid cursor')
|
|
62
|
+
try:
|
|
63
|
+
encoded,signature=token.split('.')
|
|
64
|
+
if not re.fullmatch('[A-Za-z0-9_-]+',encoded) or not re.fullmatch('[a-f0-9]{64}',signature):raise ValueError()
|
|
65
|
+
expected=hmac.new(secret,encoded.encode('ascii'),hashlib.sha256).hexdigest()
|
|
66
|
+
if not hmac.compare_digest(signature,expected):raise ValueError()
|
|
67
|
+
raw=base64.b64decode(encoded+'='*(-len(encoded)%4),altchars=b'-_',validate=True)
|
|
68
|
+
parsed=loads(raw)
|
|
69
|
+
if type(parsed) is not dict or set(parsed)!={'version','scope','after'} or parsed['version']!='umf.table-cursor/0.1' or type(parsed['scope']) is not dict or type(parsed['after']) is not list:raise ValueError()
|
|
70
|
+
return parsed
|
|
71
|
+
except (ValueError,TypeError,UnicodeError):raise SessionError('invalid cursor') from None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def native_arguments(program, item=0):
|
|
75
|
+
sources={slot['id']:slot['source'] for slot in program['parameterSources']}
|
|
76
|
+
result=[]
|
|
77
|
+
for name in program['dbapiParameterOrder']:
|
|
78
|
+
source=sources[name]
|
|
79
|
+
if source['kind']=='input':value=program['nativeInputs'][item][source['parameter']]
|
|
80
|
+
elif source['kind']=='after':value=program['nativeAfter'][source['index']]
|
|
81
|
+
elif source['kind']=='literal':value=source['nativeValue']
|
|
82
|
+
else:raise SessionError('unknown operation parameter source')
|
|
83
|
+
result.append(value)
|
|
84
|
+
return tuple(result)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def native_batch_arguments(program):
|
|
88
|
+
"""Serialize admitted input slots per item and fixed literal slots once."""
|
|
89
|
+
sources = {slot['id']: slot['source'] for slot in program['parameterSources']}
|
|
90
|
+
ordered = [sources[name] for name in program['parameterOrder']]
|
|
91
|
+
inputs = [source['parameter'] for source in ordered if source['kind'] == 'input']
|
|
92
|
+
literals = [source['nativeValue'] for source in ordered if source['kind'] == 'literal']
|
|
93
|
+
if any(source['kind'] not in ('input', 'literal') for source in ordered):
|
|
94
|
+
raise SessionError('unsupported batch parameter source')
|
|
95
|
+
values = {
|
|
96
|
+
'nativeRows': canonical([[row[name] for name in inputs] for row in program['nativeInputs']]),
|
|
97
|
+
'nativeLiterals': canonical(literals),
|
|
98
|
+
}
|
|
99
|
+
return tuple(values[name] for name in program['nativeBatch']['dbapiParameterOrder'])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def value_from_native(value,output):
|
|
103
|
+
if value is None:
|
|
104
|
+
if output['nullable']:return None
|
|
105
|
+
raise SessionError('native result omitted a required value')
|
|
106
|
+
kind=output['carrier']
|
|
107
|
+
if kind=='boolean' and type(value) is bool:return value
|
|
108
|
+
if type(value) is not str:raise SessionError('native result carrier differs')
|
|
109
|
+
value.encode('utf-8')
|
|
110
|
+
if kind=='string':return value
|
|
111
|
+
if kind=='date':
|
|
112
|
+
try:
|
|
113
|
+
if re.fullmatch('[0-9]{4}-[0-9]{2}-[0-9]{2}',value) and date.fromisoformat(value).isoformat()==value:return {'date':value}
|
|
114
|
+
except ValueError:pass
|
|
115
|
+
if kind=='timestamp':
|
|
116
|
+
try:
|
|
117
|
+
if re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}Z',value):
|
|
118
|
+
datetime.fromisoformat(value)
|
|
119
|
+
return {'timestamp':value}
|
|
120
|
+
except ValueError:pass
|
|
121
|
+
if kind=='integer' and re.fullmatch(r'-?(?:0|[1-9][0-9]*)',value):return {'integerToken':value}
|
|
122
|
+
if kind=='decimal' and re.fullmatch(r'-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?',value):
|
|
123
|
+
try:
|
|
124
|
+
if Decimal(value).is_finite():return {'decimalToken':value}
|
|
125
|
+
except InvalidOperation:pass
|
|
126
|
+
if kind=='float' and output.get('nativeEncoding')=='ieee754-binary64-hex':
|
|
127
|
+
if re.fullmatch('[0-9a-f]{16}',value):
|
|
128
|
+
number=struct.unpack('!d',bytes.fromhex(value))[0]
|
|
129
|
+
if math.isfinite(number):return {'floatToken':repr(number)}
|
|
130
|
+
raise SessionError('native result value differs from its declared carrier')
|
|
131
|
+
if kind=='float' and re.fullmatch(r'-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?',value):
|
|
132
|
+
try:
|
|
133
|
+
if math.isfinite(float(value)):return {'floatToken':value}
|
|
134
|
+
except ValueError:pass
|
|
135
|
+
if kind=='uuid':
|
|
136
|
+
try:
|
|
137
|
+
if str(UUID(value))==value:return {'uuid':value}
|
|
138
|
+
except ValueError:pass
|
|
139
|
+
if kind=='bits128' and re.fullmatch('[a-f0-9]{32}',value):return {'bits128Hex':value}
|
|
140
|
+
raise SessionError('native result value differs from its declared carrier')
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def key_literal(value,carrier):
|
|
144
|
+
if value is None:raise SessionError('native cursor key is absent')
|
|
145
|
+
if carrier=='string':return {'string':value}
|
|
146
|
+
if carrier=='boolean':return {'boolean':value}
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def result_frame(program,rows,scope,secret):
|
|
151
|
+
outputs=program['outputs'];result=program['result'];kind=result['kind'];bound=result['maxRows']
|
|
152
|
+
if kind=='count':
|
|
153
|
+
if len(rows)!=1 or len(rows[0])!=1:raise SessionError('native count cardinality differs')
|
|
154
|
+
count=value_from_native(rows[0][0],outputs[0])
|
|
155
|
+
if count['integerToken'].startswith('-'):raise SessionError('native count is negative')
|
|
156
|
+
response={'kind':'count','count':count}
|
|
157
|
+
else:
|
|
158
|
+
if any(len(row)!=len(outputs) for row in rows):raise SessionError('native result arity differs')
|
|
159
|
+
decoded=[{out['field']['element']:value_from_native(value,out) for out,value in zip(outputs,row)} for row in rows]
|
|
160
|
+
if kind=='one' and not decoded:raise SessionError('required row not found')
|
|
161
|
+
if kind in ('one','optional') and len(decoded)>1:raise SessionError('native single-row cardinality exceeded')
|
|
162
|
+
if kind=='many' and len(decoded)>bound:raise SessionError('native result row bound exceeded')
|
|
163
|
+
cursor=None
|
|
164
|
+
if kind=='page' and len(decoded)>bound:
|
|
165
|
+
if len(decoded)!=bound+1:raise SessionError('native page bound exceeded')
|
|
166
|
+
decoded=decoded[:bound];last=decoded[-1];by_field={canonical(o['field']):o for o in outputs}
|
|
167
|
+
after=[key_literal(last[ref['element']],by_field[canonical(ref)]['carrier']) for ref in result['cursor']['fields']]
|
|
168
|
+
cursor=token_encode(secret,scope,after)
|
|
169
|
+
response={'kind':kind,'rows':decoded,'cursor':cursor}
|
|
170
|
+
response.update({'version':'umf.table-read-result/0.1','module':program['module'],'operation':program['operation'],
|
|
171
|
+
'sourceDigest':program['binding']['modelSha256']})
|
|
172
|
+
bounded_size(response)
|
|
173
|
+
return response
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Authenticated effect receipts; historical business rows are never stored."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from .operation_values import canonical, digest, loads
|
|
10
|
+
from .session_policy import SessionError
|
|
11
|
+
|
|
12
|
+
_VERSION='umf.table-outcome/0.1'
|
|
13
|
+
_HEX=re.compile('[a-f0-9]{64}')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def outcome_invocation(secret, value):
|
|
17
|
+
"""Keep historical input fingerprints opaque to native receipt readers."""
|
|
18
|
+
return hmac.new(secret,b'umf.table-outcome/0.1\0invocation\0'+canonical(value).encode('utf-8'),hashlib.sha256).hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def outcome_slot(identity, principal_oid, context, operation, key):
|
|
22
|
+
if type(key) is not str or not 1<=len(key.encode('utf-8'))<=256 or '\0' in key:
|
|
23
|
+
raise SessionError('outcome key must contain1..256 UTF8 bytes')
|
|
24
|
+
# The slot is independent of secret rotation, inputs and deployment. A
|
|
25
|
+
# changed verifier or invocation must refuse the occupied slot, never miss
|
|
26
|
+
# it and execute a second write. Native current-role RLS protects its scope.
|
|
27
|
+
return digest([_VERSION,context['schema'],context['module'],identity.kind,
|
|
28
|
+
identity.subject,principal_oid,operation,key])
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _signature(secret, principal_oid, key_digest, row):
|
|
32
|
+
if type(secret) is not bytes or len(secret)<32:
|
|
33
|
+
raise ValueError('outcome root secret requires at least256 bits')
|
|
34
|
+
key=hmac.new(secret,b'umf.table-outcome/0.1\0receipt-authentication',hashlib.sha256).digest()
|
|
35
|
+
body={'version':_VERSION,'principalOid':principal_oid,'keyDigest':key_digest,
|
|
36
|
+
**{k:row[k] for k in ('invocationDigest','scopeDigest','payload')}}
|
|
37
|
+
return hmac.new(key,canonical(body).encode('utf-8'),hashlib.sha256).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def outcome_record(secret, principal_oid, key_digest, metadata, effects, response):
|
|
41
|
+
payload={'version':_VERSION,**metadata,'effects':[{'integerToken':str(n)} for n in effects],
|
|
42
|
+
'responseDigest':hmac.new(secret,b'umf.table-outcome/0.1\0response\0'+canonical(response).encode('utf-8'),hashlib.sha256).hexdigest()}
|
|
43
|
+
row={'invocationDigest':metadata['invocationDigest'],'scopeDigest':metadata['scopeDigest'],
|
|
44
|
+
'payload':canonical(payload)}
|
|
45
|
+
if len(row['payload'].encode('utf-8'))>131072:
|
|
46
|
+
raise SessionError('outcome receipt capacity exceeded')
|
|
47
|
+
row['signature']=_signature(secret,principal_oid,key_digest,row)
|
|
48
|
+
return row
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def outcome_from_record(secret, principal_oid, key_digest, stored, metadata, *, items, max_rows):
|
|
52
|
+
if type(stored) not in (tuple,list) or len(stored)!=4 or any(type(v) is not str for v in stored):
|
|
53
|
+
raise SessionError('stored outcome is invalid')
|
|
54
|
+
invocation,scope,payload,signature=stored
|
|
55
|
+
if (any(_HEX.fullmatch(v) is None for v in (invocation,scope,signature))
|
|
56
|
+
or len(payload.encode('utf-8'))>131072):
|
|
57
|
+
raise SessionError('stored outcome is invalid')
|
|
58
|
+
row={'invocationDigest':invocation,'scopeDigest':scope,'payload':payload}
|
|
59
|
+
if not hmac.compare_digest(signature,_signature(secret,principal_oid,key_digest,row)):
|
|
60
|
+
raise SessionError('stored outcome cannot be authenticated')
|
|
61
|
+
value=loads(payload)
|
|
62
|
+
expected={'version':_VERSION,**metadata}
|
|
63
|
+
if (type(value) is not dict or set(value)!={*expected,'effects','responseDigest'}
|
|
64
|
+
or any(value.get(k)!=v for k,v in expected.items())
|
|
65
|
+
or invocation!=metadata['invocationDigest'] or scope!=metadata['scopeDigest']):
|
|
66
|
+
raise SessionError('stored outcome differs from this invocation or authority')
|
|
67
|
+
effects=value['effects']
|
|
68
|
+
if (type(value['responseDigest']) is not str or _HEX.fullmatch(value['responseDigest']) is None
|
|
69
|
+
or type(effects) is not list or len(effects)!=items):
|
|
70
|
+
raise SessionError('stored outcome is invalid')
|
|
71
|
+
for count in effects:
|
|
72
|
+
if (type(count) is not dict or set(count)!={'integerToken'} or type(count['integerToken']) is not str
|
|
73
|
+
or re.fullmatch('0|[1-9][0-9]{0,4}',count['integerToken']) is None
|
|
74
|
+
or int(count['integerToken'])>max_rows):
|
|
75
|
+
raise SessionError('stored outcome count differs from the declared bound')
|
|
76
|
+
return value
|