31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326 | @required_conformance(
r"http://www.opengis.net/spec/cql2/1.0/conf/basic-cql2",
r"http://www.opengis.net/spec/cql2/1.0/conf/cql2-text",
r"http://www.opengis.net/spec/cql2/1.0/conf/cql2-json",
)
@dataclass
class Cql2ValidateTransactionMiddleware:
"""Middleware to validate transaction requests against a CQL2 filter."""
app: ASGIApp
upstream_url: str
state_key: str = "cql2_filter"
_client: httpx.AsyncClient = field(init=False)
# Transaction endpoint patterns
items_pattern = r"^/collections/([^/]+)/(items|bulk_items)(?:/([^/]+))?$"
collections_pattern = r"^/collections(?:/([^/]+))?$"
def __post_init__(self):
"""Initialize the HTTP client."""
self._client = httpx.AsyncClient(base_url=self.upstream_url)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""Validate transaction requests against the CQL2 filter."""
if scope["type"] != "http":
return await self.app(scope, receive, send)
request = Request(scope)
cql2_filter: Optional[Expr] = getattr(request.state, self.state_key, None)
if not cql2_filter:
return await self.app(scope, receive, send)
path = request.url.path
method = request.method
# Match items endpoints: /collections/{id}/items, /collections/{id}/bulk_items, /collections/{id}/items/{id}
if re.match(self.items_pattern, path):
if method == "POST":
if "/bulk_items" in path:
return await self._handle_bulk_create(
scope, receive, send, cql2_filter
)
return await self._handle_create(scope, receive, send, cql2_filter)
if method in ("PUT", "PATCH"):
return await self._handle_update(
scope, receive, send, cql2_filter, path, method
)
if method == "DELETE":
return await self._handle_delete(
scope, receive, send, cql2_filter, path
)
# Match collections endpoints: /collections, /collections/{id}
if re.match(self.collections_pattern, path):
if method == "POST":
return await self._handle_create(scope, receive, send, cql2_filter)
if method in ("PUT", "PATCH"):
return await self._handle_update(
scope, receive, send, cql2_filter, path, method
)
if method == "DELETE":
return await self._handle_delete(
scope, receive, send, cql2_filter, path
)
# Not a transaction endpoint, pass through
return await self.app(scope, receive, send)
async def _read_body(self, receive: Receive) -> bytes:
"""Read the full request body."""
body = b""
more_body = True
while more_body:
message = await receive()
if message["type"] == "http.request":
body += message.get("body", b"")
more_body = message.get("more_body", False)
return body
def _make_receive(self, body: bytes) -> Receive:
"""Create a new receive callable that returns the given body."""
async def new_receive():
return {
"type": "http.request",
"body": body,
"more_body": False,
}
return new_receive
async def _fetch_existing(self, path: str) -> Optional[dict]:
"""Fetch the existing record from upstream."""
response = await self._client.get(path)
if response.status_code == 404:
return None
response.raise_for_status()
return response.json()
async def _handle_create(
self,
scope: Scope,
receive: Receive,
send: Send,
cql2_filter: Expr,
) -> None:
"""Validate create requests."""
body = await self._read_body(receive)
try:
body_json = json.loads(body) if body else {}
except json.JSONDecodeError:
response = JSONResponse(
{
"code": "ParseError",
"description": "Request body must be valid JSON.",
},
status_code=400,
)
return await response(scope, receive, send)
if not cql2_filter.matches(body_json):
response = JSONResponse(
{
"code": "ForbiddenError",
"description": "Resource does not match access filter.",
},
status_code=403,
)
return await response(scope, receive, send)
# Reconstruct receive and forward
scope = dict(scope)
await self.app(scope, self._make_receive(body), send)
async def _handle_bulk_create(
self,
scope: Scope,
receive: Receive,
send: Send,
cql2_filter: Expr,
) -> None:
"""Validate bulk item create requests."""
body = await self._read_body(receive)
try:
body_json = json.loads(body) if body else {}
except json.JSONDecodeError:
response = JSONResponse(
{
"code": "ParseError",
"description": "Request body must be valid JSON.",
},
status_code=400,
)
return await response(scope, receive, send)
items = body_json.get("items", {})
if not isinstance(items, dict):
response = JSONResponse(
{
"code": "ParseError",
"description": "Bulk items body must contain an 'items' object.",
},
status_code=400,
)
return await response(scope, receive, send)
failed = [
item_id for item_id, item in items.items() if not cql2_filter.matches(item)
]
if failed:
response = JSONResponse(
{
"code": "ForbiddenError",
"description": f"Items do not match access filter: {', '.join(failed)}",
},
status_code=403,
)
return await response(scope, receive, send)
# Reconstruct receive and forward
scope = dict(scope)
await self.app(scope, self._make_receive(body), send)
async def _handle_update(
self,
scope: Scope,
receive: Receive,
send: Send,
cql2_filter: Expr,
path: str,
method: str,
) -> None:
"""Validate update requests."""
body = await self._read_body(receive)
try:
body_json = json.loads(body) if body else {}
except json.JSONDecodeError:
response = JSONResponse(
{
"code": "ParseError",
"description": "Request body must be valid JSON.",
},
status_code=400,
)
return await response(scope, receive, send)
# Fetch existing record
try:
existing = await self._fetch_existing(path)
except httpx.HTTPError:
response = JSONResponse(
{
"code": "UpstreamError",
"description": "Failed to fetch record from upstream.",
},
status_code=502,
)
return await response(scope, receive, send)
if existing is None:
response = JSONResponse(
{"code": "NotFoundError", "description": "Record not found."},
status_code=404,
)
return await response(scope, receive, send)
# Validate existing record matches filter
if not cql2_filter.matches(existing):
response = JSONResponse(
{"code": "NotFoundError", "description": "Record not found."},
status_code=404,
)
return await response(scope, receive, send)
# Merge for validation
if method == "PATCH":
merged = _deep_merge(existing, body_json)
else:
merged = body_json
# Validate merged result matches filter
if not cql2_filter.matches(merged):
response = JSONResponse(
{
"code": "ForbiddenError",
"description": "Updated resource does not match access filter.",
},
status_code=403,
)
return await response(scope, receive, send)
# Forward
scope = dict(scope)
await self.app(scope, self._make_receive(body), send)
async def _handle_delete(
self,
scope: Scope,
receive: Receive,
send: Send,
cql2_filter: Expr,
path: str,
) -> None:
"""Validate delete requests."""
try:
existing = await self._fetch_existing(path)
except httpx.HTTPError:
response = JSONResponse(
{
"code": "UpstreamError",
"description": "Failed to fetch record from upstream.",
},
status_code=502,
)
return await response(scope, receive, send)
if existing is None:
response = JSONResponse(
{"code": "NotFoundError", "description": "Record not found."},
status_code=404,
)
return await response(scope, receive, send)
if not cql2_filter.matches(existing):
response = JSONResponse(
{"code": "NotFoundError", "description": "Record not found."},
status_code=404,
)
return await response(scope, receive, send)
await self.app(scope, receive, send)
|