askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_server.py · 664.7 KB · 13896 lines
| 1 | """Minimal ASGI app for DBBASIC Object Server. |
| 2 | |
| 3 | This is the first public server slice. Source writes are disabled by default |
| 4 | while the production auth and mutation paths are extracted. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import asyncio |
| 10 | import dataclasses |
| 11 | import contextlib |
| 12 | import base64 |
| 13 | import binascii |
| 14 | import hashlib |
| 15 | import hmac |
| 16 | import html |
| 17 | import json |
| 18 | import mimetypes |
| 19 | import logging |
| 20 | import os |
| 21 | import re |
| 22 | import shutil |
| 23 | import sys |
| 24 | import tarfile |
| 25 | import tempfile |
| 26 | import threading |
| 27 | import time |
| 28 | import urllib.error |
| 29 | import urllib.parse |
| 30 | import urllib.request |
| 31 | from collections import Counter, deque |
| 32 | from datetime import datetime, timezone |
| 33 | from importlib import metadata as importlib_metadata |
| 34 | from pathlib import Path, PurePosixPath |
| 35 | from typing import Any, Callable, Mapping |
| 36 | |
| 37 | import http_api_contract |
| 38 | import object_access |
| 39 | import object_activity |
| 40 | import object_backup |
| 41 | import object_analytics |
| 42 | import object_api_keys |
| 43 | import object_signup |
| 44 | import object_setup |
| 45 | import object_webdav |
| 46 | import object_collections |
| 47 | import object_correlation |
| 48 | import object_credentials |
| 49 | import object_daemon_control |
| 50 | import object_daemon_status |
| 51 | import object_events |
| 52 | import object_execution |
| 53 | import object_field_permissions |
| 54 | import object_file_changes |
| 55 | import object_files |
| 56 | import object_handlers |
| 57 | import object_identity |
| 58 | import object_identity_sources |
| 59 | import object_ids |
| 60 | import object_logs |
| 61 | import object_mcp |
| 62 | import object_metadata |
| 63 | import object_metrics_history |
| 64 | import object_multipart |
| 65 | import object_ops_log |
| 66 | import object_package_changes |
| 67 | import object_permission_audit |
| 68 | import object_permission_store |
| 69 | import object_permission_status |
| 70 | import object_permissions |
| 71 | import object_policy_diff |
| 72 | import object_packages |
| 73 | import object_rate_limit |
| 74 | import object_reader |
| 75 | import object_reconciles |
| 76 | import object_record_changes |
| 77 | import object_finance |
| 78 | import object_records |
| 79 | import object_schema_versions |
| 80 | import object_stock |
| 81 | import object_ai |
| 82 | import object_backup_index |
| 83 | import object_backup_schedule |
| 84 | import object_realtime |
| 85 | import object_schemas |
| 86 | import object_search |
| 87 | import object_service_keys |
| 88 | import object_stt |
| 89 | import object_tts |
| 90 | import object_user_files |
| 91 | import object_site_routes |
| 92 | import object_source |
| 93 | import object_source_changes |
| 94 | import object_state |
| 95 | import object_versions |
| 96 | import object_worker_pool |
| 97 | import object_sandbox |
| 98 | import object_schedule |
| 99 | import object_namespace |
| 100 | import object_user_access |
| 101 | from object_namespace import ( |
| 102 | get_base_object_roots, |
| 103 | get_object_roots, |
| 104 | get_override_root, |
| 105 | iter_object_sources, |
| 106 | parse_user_object_id, |
| 107 | resolve_object_id, |
| 108 | validate_object_id, |
| 109 | ) |
| 110 | from object_versions import InvalidObjectIdError |
| 111 | from python_object_runtime import MethodNotSupportedError, PythonObjectRuntime |
| 112 | |
| 113 | SOURCE_WRITES_ENV = "DBBASIC_ENABLE_SOURCE_WRITES" |
| 114 | # Non-admin users writing source into their own u_<id>_ namespace. Separate |
| 115 | # from SOURCE_WRITES_ENV (the operator's switch) on purpose: user code is |
| 116 | # untrusted code. Refused anyway where user objects can't run sandboxed -- |
| 117 | # see _user_code_isolation_error. |
| 118 | USER_SOURCE_WRITES_ENV = "DBBASIC_ENABLE_USER_SOURCE_WRITES" |
| 119 | FILE_WRITES_ENV = "DBBASIC_ENABLE_FILE_WRITES" |
| 120 | ADMIN_TOKEN_ENV = "DBBASIC_ADMIN_TOKEN" |
| 121 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 122 | MAX_REQUEST_BYTES_ENV = "DBBASIC_MAX_REQUEST_BYTES" |
| 123 | MAX_OBJECT_FILE_BYTES_ENV = "DBBASIC_MAX_OBJECT_FILE_BYTES" |
| 124 | MAX_CONCURRENT_REQUESTS_ENV = "DBBASIC_MAX_CONCURRENT_REQUESTS" |
| 125 | MAX_CONCURRENT_EXECUTIONS_ENV = "DBBASIC_MAX_CONCURRENT_EXECUTIONS" |
| 126 | MAX_CONCURRENT_EXECUTIONS_PER_USER_ENV = "DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER" |
| 127 | RATE_LIMIT_REQUESTS_ENV = "DBBASIC_RATE_LIMIT_REQUESTS" |
| 128 | RATE_LIMIT_WINDOW_SECONDS_ENV = "DBBASIC_RATE_LIMIT_WINDOW_SECONDS" |
| 129 | RATE_LIMIT_TRUST_PROXY_HEADERS_ENV = "DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS" |
| 130 | OBJECT_TIMEOUT_SECONDS_ENV = "DBBASIC_OBJECT_TIMEOUT_SECONDS" |
| 131 | TRUSTED_IN_PROCESS_OBJECTS_ENV = "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS" |
| 132 | PERMISSION_ENFORCEMENT_ENV = object_access.PERMISSION_ENFORCEMENT_ENV |
| 133 | PERMISSION_UNREADY_ENFORCEMENT_ENV = "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT" |
| 134 | # Explicit "yes, start even though the enforcement I asked for is blocked". |
| 135 | ALLOW_BLOCKED_ENFORCEMENT_START_ENV = "DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT" |
| 136 | # A hosted, multi-user box sets this so it can never come up with enforcement off. |
| 137 | REQUIRE_PERMISSION_ENFORCEMENT_ENV = "DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT" |
| 138 | PERMISSION_AUDIT_ENV = "DBBASIC_ENABLE_PERMISSION_AUDIT" |
| 139 | PERMISSION_TRUST_HEADERS_ENV = "DBBASIC_PERMISSION_TRUST_HEADERS" |
| 140 | REQUIRE_KNOWN_IDENTITY_USERS_ENV = "DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS" |
| 141 | SESSION_LOGIN_ENV = "DBBASIC_ENABLE_SESSION_LOGIN" |
| 142 | SESSION_LOGIN_TOKEN_ENV = "DBBASIC_SESSION_LOGIN_TOKEN" |
| 143 | SESSION_ADMIN_GATES_ENV = "DBBASIC_ENABLE_SESSION_ADMIN_GATES" |
| 144 | PASSWORD_LOGIN_ENV = "DBBASIC_ENABLE_PASSWORD_LOGIN" |
| 145 | PASSWORD_LOGIN_FAILURE_DELAY_SECONDS = 0.5 |
| 146 | LOGIN_LOCKOUT_ATTEMPTS_ENV = "DBBASIC_LOGIN_LOCKOUT_ATTEMPTS" |
| 147 | LOGIN_LOCKOUT_WINDOW_SECONDS_ENV = "DBBASIC_LOGIN_LOCKOUT_WINDOW_SECONDS" |
| 148 | DEFAULT_LOGIN_LOCKOUT_ATTEMPTS = 5 |
| 149 | DEFAULT_LOGIN_LOCKOUT_WINDOW_SECONDS = 900 |
| 150 | LOGIN_LOCKED_MESSAGE = "Too many failed attempts. Try again later." |
| 151 | LANDING_PATH_ENV = "DBBASIC_AUTH_LANDING_PATH" |
| 152 | SIGNUP_ATTEMPTS_PER_HOUR_PER_IP = 5 |
| 153 | RESET_ATTEMPTS_PER_HOUR_PER_IP = 10 |
| 154 | # A wrong setup code is a guess at 100 bits, so these only keep the form from being a free hash oracle. |
| 155 | SETUP_ATTEMPTS_PER_HOUR_PER_IP = 10 |
| 156 | SETUP_ATTEMPTS_PER_HOUR = 100 |
| 157 | EMAILS_PER_HOUR_PER_ADDRESS = 3 |
| 158 | SESSION_COOKIE_NAME = "dbbasic_session" |
| 159 | COOKIE_SECURE_ENV = "DBBASIC_COOKIE_SECURE" |
| 160 | SITE_ROUTES_ENV = "DBBASIC_ENABLE_SITE_ROUTES" |
| 161 | METRICS_SNAPSHOT_SECONDS_ENV = "DBBASIC_METRICS_SNAPSHOT_SECONDS" |
| 162 | DEFAULT_METRICS_SNAPSHOT_SECONDS = 60 |
| 163 | RECORD_EVENTS_ENV = "DBBASIC_ENABLE_RECORD_EVENTS" |
| 164 | EVENT_KEEP_COUNT_ENV = "DBBASIC_EVENT_KEEP_COUNT" |
| 165 | EVENT_KEEP_SECONDS_ENV = "DBBASIC_EVENT_KEEP_SECONDS" |
| 166 | # 58's <block>_enabled kill switch, default ON: field-filter query params are |
| 167 | # read and applied unless explicitly disabled. Off degrades to "ignore the |
| 168 | # filter params" (unfiltered, same as before this feature), never to a 400 -- |
| 169 | # see _handle_collection_records_get and 58's Degradation section. |
| 170 | FILTERING_ENABLED_ENV = "DBBASIC_ENABLE_FILTERING" |
| 171 | # 63 optimistic concurrency: gates whether an update's If-Match/expected_rev |
| 172 | # precondition is honored. Default on; flipping it off makes writes carrying |
| 173 | # a precondition behave as last-write-wins rather than turning a working |
| 174 | # write path into an error path under brownout (same posture as filtering). |
| 175 | CONCURRENCY_ENABLED_ENV = "DBBASIC_ENABLE_CONCURRENCY" |
| 176 | # 64 (feed): the <block>_enabled kill switch for GET /api/feed and the |
| 177 | # get_feed MCP verb. Default on; off degrades to an empty, non-error |
| 178 | # response (spec's Degradation section) -- `follows` itself, and the |
| 179 | # follow button, are untouched by this flag, only the composed read is. |
| 180 | FEED_ENABLED_ENV = "DBBASIC_ENABLE_FEED" |
| 181 | # Row-filter pushdown: off | shadow | on, default OFF. With enforcement on, |
| 182 | # a permission-filtered list runs the engine on every row of the collection; |
| 183 | # `on` runs it only on the rows object_permissions.plan_row_filter says could |
| 184 | # be allowed, found through a per-field index (object_records). `shadow` |
| 185 | # computes both, serves the full scan, and records any difference in the ops |
| 186 | # log. See _read_records_for_row_filter and docs/permissions-model.md. |
| 187 | ROW_FILTER_INDEX_ENV = "DBBASIC_ROW_FILTER_INDEX" |
| 188 | ROW_FILTER_INDEX_OFF = "off" |
| 189 | ROW_FILTER_INDEX_SHADOW = "shadow" |
| 190 | ROW_FILTER_INDEX_ON = "on" |
| 191 | # Bounds on what shadow mode may write to the ops log, per process: one row |
| 192 | # per collection per interval, and a lifetime cap. The ops log is capped at |
| 193 | # 5000 rows already, but the login lockout counts failures out of that same |
| 194 | # window, so "bounded" is not enough -- a planner that is wrong on every |
| 195 | # request must not be able to evict login failures. 200 rows a process is |
| 196 | # plenty of evidence that the index disagrees; the counters keep counting. |
| 197 | ROW_FILTER_SHADOW_MIN_INTERVAL_SECONDS = 60.0 |
| 198 | ROW_FILTER_SHADOW_MAX_EVENTS = 200 |
| 199 | ROW_FILTER_SHADOW_MAX_IDS = 5 |
| 200 | # Query params the collection-records GET route reserves for pagination/ |
| 201 | # sort/search rather than treating as a field filter (58's Encoding |
| 202 | # section); every other param is a `field` or `field.op` filter condition. |
| 203 | FILTER_RESERVED_PARAMS = frozenset({"limit", "offset", "sort", "q"}) |
| 204 | # `field.in=a,b,c,...` cap (58's Open Questions: bound the list so `in` |
| 205 | # can't become an unbounded OR by the back door). |
| 206 | FILTER_IN_MAX_VALUES = 50 |
| 207 | PACKAGES_DIR_ENV = "DBBASIC_PACKAGES_DIR" |
| 208 | PRIVATE_PACKAGES_DIR_ENV = "DBBASIC_PRIVATE_PACKAGES_DIR" |
| 209 | DEFAULT_PRIVATE_PACKAGES_DIR = "packages-private" |
| 210 | PACKAGE_INSTALLS_ENABLED_ENV = "DBBASIC_ENABLE_PACKAGE_INSTALLS" |
| 211 | PACKAGE_RESTORE_ENABLED_ENV = "DBBASIC_ENABLE_PACKAGE_RESTORE" |
| 212 | DEFAULT_MAX_REQUEST_BYTES = 1_048_576 |
| 213 | DEFAULT_MAX_OBJECT_FILE_BYTES = DEFAULT_MAX_REQUEST_BYTES |
| 214 | DEFAULT_MAX_CONCURRENT_REQUESTS = 64 |
| 215 | DEFAULT_MAX_CONCURRENT_EXECUTIONS = 8 |
| 216 | # 3 of the default 8: three users can saturate the pool, one cannot. A single |
| 217 | # customer rarely needs more than a few overlapping requests to their own code. |
| 218 | DEFAULT_MAX_CONCURRENT_EXECUTIONS_PER_USER = 3 |
| 219 | USER_EXECUTION_RETRY_AFTER_SECONDS = 1 |
| 220 | DEFAULT_RATE_LIMIT_REQUESTS = 0 |
| 221 | DEFAULT_RATE_LIMIT_WINDOW_SECONDS = 60 |
| 222 | DEFAULT_OBJECT_TIMEOUT_SECONDS = 0.0 |
| 223 | TRUE_VALUES = {"1", "true", "yes", "on"} |
| 224 | SENSITIVE_GET_FLAGS = { |
| 225 | "source", |
| 226 | "source_changes", |
| 227 | "changes", |
| 228 | "state", |
| 229 | "logs", |
| 230 | "metadata", |
| 231 | "versions", |
| 232 | "files", |
| 233 | "file", |
| 234 | "schedules", |
| 235 | } |
| 236 | RECORD_EVENT_TYPES = { |
| 237 | "create": "collection.record.created", |
| 238 | "update": "collection.record.updated", |
| 239 | "delete": "collection.record.deleted", |
| 240 | } |
| 241 | ADMIN_CHANGE_KINDS = frozenset({"source", "file", "record", "package"}) |
| 242 | |
| 243 | REALTIME_ENABLED_ENV = "DBBASIC_ENABLE_REALTIME" |
| 244 | REALTIME_QUEUE_MAX_ENV = "DBBASIC_REALTIME_QUEUE_MAX" |
| 245 | WEBSOCKET_PATH = "/ws" |
| 246 | MAX_WS_SUBSCRIPTIONS = 64 |
| 247 | _realtime_hub = object_realtime.RealtimeHub() |
| 248 | |
| 249 | _runtime = PythonObjectRuntime() |
| 250 | |
| 251 | |
| 252 | class RequestMetrics: |
| 253 | """Thread-safe, in-process request metrics for health and Scroll.""" |
| 254 | |
| 255 | def __init__(self) -> None: |
| 256 | self._lock = threading.Lock() |
| 257 | self._start_time = time.time() |
| 258 | self._total_requests = 0 |
| 259 | self._total_errors = 0 |
| 260 | self._total_4xx = 0 |
| 261 | self._response_times_ms: deque[float] = deque(maxlen=1000) |
| 262 | self._methods: Counter[str] = Counter() |
| 263 | self._status_codes: Counter[int] = Counter() |
| 264 | self._paths: Counter[str] = Counter() |
| 265 | self._path_errors: Counter[str] = Counter() |
| 266 | self._recent_errors: deque[dict[str, Any]] = deque(maxlen=50) |
| 267 | |
| 268 | def record_request(self, method: str, path: str, status: int, duration_ms: float) -> None: |
| 269 | with self._lock: |
| 270 | self._total_requests += 1 |
| 271 | self._methods[method] += 1 |
| 272 | self._status_codes[status] += 1 |
| 273 | self._paths[path] += 1 |
| 274 | self._response_times_ms.append(duration_ms) |
| 275 | |
| 276 | if status >= 500: |
| 277 | self._total_errors += 1 |
| 278 | self._path_errors[path] += 1 |
| 279 | if 400 <= status < 500: |
| 280 | self._total_4xx += 1 |
| 281 | self._path_errors[path] += 1 |
| 282 | if status >= 400: |
| 283 | self._recent_errors.append( |
| 284 | { |
| 285 | "timestamp": _utc_timestamp(), |
| 286 | "method": method, |
| 287 | "path": path, |
| 288 | "status": status, |
| 289 | "duration_ms": round(duration_ms, 2), |
| 290 | } |
| 291 | ) |
| 292 | |
| 293 | def snapshot(self) -> dict[str, Any]: |
| 294 | with self._lock: |
| 295 | uptime_seconds = max(time.time() - self._start_time, 0.001) |
| 296 | response_times = list(self._response_times_ms) |
| 297 | total_requests = self._total_requests |
| 298 | total_errors = self._total_errors |
| 299 | total_4xx = self._total_4xx |
| 300 | methods = dict(self._methods) |
| 301 | status_codes = {str(code): count for code, count in self._status_codes.items()} |
| 302 | top_paths = [ |
| 303 | { |
| 304 | "path": path, |
| 305 | "requests": count, |
| 306 | "errors": self._path_errors.get(path, 0), |
| 307 | } |
| 308 | for path, count in self._paths.most_common(10) |
| 309 | ] |
| 310 | recent_errors = list(self._recent_errors) |
| 311 | |
| 312 | return { |
| 313 | "uptime_seconds": round(uptime_seconds, 3), |
| 314 | "uptime_human": _human_duration(uptime_seconds), |
| 315 | "total_requests": total_requests, |
| 316 | "total_errors": total_errors, |
| 317 | "total_4xx": total_4xx, |
| 318 | "requests_per_second": round(total_requests / uptime_seconds, 2), |
| 319 | "error_rate": round((total_errors / total_requests * 100) if total_requests else 0, 2), |
| 320 | "response_time_ms": _response_time_summary(response_times), |
| 321 | "methods": methods, |
| 322 | "status_codes": status_codes, |
| 323 | "top_paths": top_paths, |
| 324 | "recent_errors": recent_errors, |
| 325 | } |
| 326 | |
| 327 | |
| 328 | class RequestBodyTooLargeError(ValueError): |
| 329 | """Raised when an inbound HTTP request body exceeds the configured cap.""" |
| 330 | |
| 331 | def __init__(self, *, max_bytes: int, actual_bytes: int): |
| 332 | self.max_bytes = max_bytes |
| 333 | self.actual_bytes = actual_bytes |
| 334 | super().__init__("Request body too large") |
| 335 | |
| 336 | |
| 337 | class ConcurrencyToken: |
| 338 | """Release handle for a claimed concurrency slot.""" |
| 339 | |
| 340 | def __init__(self, limiter: "ConcurrencyLimiter | None"): |
| 341 | self._limiter = limiter |
| 342 | self._released = False |
| 343 | |
| 344 | def release(self) -> None: |
| 345 | if self._released: |
| 346 | return |
| 347 | |
| 348 | self._released = True |
| 349 | if self._limiter is not None: |
| 350 | self._limiter.release() |
| 351 | |
| 352 | |
| 353 | class ConcurrencyLimiter: |
| 354 | """Small per-process non-queueing concurrency limiter.""" |
| 355 | |
| 356 | def __init__(self) -> None: |
| 357 | self._lock = threading.Lock() |
| 358 | self._in_flight = 0 |
| 359 | |
| 360 | def try_acquire(self, limit: int) -> ConcurrencyToken | None: |
| 361 | if limit <= 0: |
| 362 | return ConcurrencyToken(None) |
| 363 | |
| 364 | with self._lock: |
| 365 | if self._in_flight >= limit: |
| 366 | return None |
| 367 | self._in_flight += 1 |
| 368 | |
| 369 | return ConcurrencyToken(self) |
| 370 | |
| 371 | def release(self) -> None: |
| 372 | with self._lock: |
| 373 | if self._in_flight > 0: |
| 374 | self._in_flight -= 1 |
| 375 | |
| 376 | def snapshot(self, limit: int) -> dict[str, Any]: |
| 377 | with self._lock: |
| 378 | in_flight = self._in_flight |
| 379 | |
| 380 | if limit <= 0: |
| 381 | return { |
| 382 | "in_flight": in_flight, |
| 383 | "max": limit, |
| 384 | "available": None, |
| 385 | "limited": False, |
| 386 | } |
| 387 | |
| 388 | return { |
| 389 | "in_flight": in_flight, |
| 390 | "max": limit, |
| 391 | "available": max(limit - in_flight, 0), |
| 392 | "limited": True, |
| 393 | } |
| 394 | |
| 395 | |
| 396 | class KeyedConcurrencyLimiter: |
| 397 | """Per-key (per-user) non-queueing concurrency cap. |
| 398 | |
| 399 | The global execution cap is a shared pool: one customer's slow requests |
| 400 | could fill all of it and every other customer got "Server is busy". This |
| 401 | caps what one user may hold, so the pool is only ever exhausted by many |
| 402 | users, not by one. |
| 403 | """ |
| 404 | |
| 405 | def __init__(self) -> None: |
| 406 | self._lock = threading.Lock() |
| 407 | self._in_flight: dict[str, int] = {} |
| 408 | |
| 409 | def try_acquire(self, key: str, limit: int) -> "KeyedToken | None": |
| 410 | if limit <= 0: |
| 411 | return KeyedToken(None, key) |
| 412 | with self._lock: |
| 413 | if self._in_flight.get(key, 0) >= limit: |
| 414 | return None |
| 415 | self._in_flight[key] = self._in_flight.get(key, 0) + 1 |
| 416 | return KeyedToken(self, key) |
| 417 | |
| 418 | def release(self, key: str) -> None: |
| 419 | with self._lock: |
| 420 | count = self._in_flight.get(key, 0) - 1 |
| 421 | if count > 0: |
| 422 | self._in_flight[key] = count |
| 423 | else: |
| 424 | self._in_flight.pop(key, None) |
| 425 | |
| 426 | def snapshot(self) -> dict[str, int]: |
| 427 | with self._lock: |
| 428 | return dict(self._in_flight) |
| 429 | |
| 430 | |
| 431 | class KeyedToken: |
| 432 | def __init__(self, limiter: KeyedConcurrencyLimiter | None, key: str) -> None: |
| 433 | self._limiter = limiter |
| 434 | self._key = key |
| 435 | self._released = False |
| 436 | |
| 437 | def release(self) -> None: |
| 438 | if self._released: |
| 439 | return |
| 440 | self._released = True |
| 441 | if self._limiter is not None: |
| 442 | self._limiter.release(self._key) |
| 443 | |
| 444 | |
| 445 | _request_limiter = ConcurrencyLimiter() |
| 446 | _execution_limiter = ConcurrencyLimiter() |
| 447 | _user_execution_limiter = KeyedConcurrencyLimiter() |
| 448 | _LOG = logging.getLogger("dbbasic.object_server") |
| 449 | _metrics = RequestMetrics() |
| 450 | |
| 451 | _worker_pool: object_worker_pool.WorkerPool | None = None |
| 452 | _worker_pool_size_used: int = 0 |
| 453 | _worker_pool_lock = asyncio.Lock() |
| 454 | |
| 455 | |
| 456 | async def app(scope: dict[str, Any], receive, send) -> None: |
| 457 | """ASGI application entry point.""" |
| 458 | if scope["type"] == "lifespan": |
| 459 | await _handle_lifespan(receive, send) |
| 460 | return |
| 461 | |
| 462 | if scope["type"] == "websocket": |
| 463 | await _handle_websocket(scope, receive, send) |
| 464 | return |
| 465 | |
| 466 | if scope["type"] != "http": |
| 467 | return |
| 468 | |
| 469 | method = scope.get("method", "GET").upper() |
| 470 | path = scope.get("path", "/") |
| 471 | status_code = 500 |
| 472 | started_at = time.perf_counter() |
| 473 | request_headers = _parse_headers(scope.get("headers", [])) |
| 474 | correlation_id = object_correlation.ensure_correlation_id( |
| 475 | request_headers.get(object_correlation.CORRELATION_ID_HEADER) |
| 476 | ) |
| 477 | correlation_token = object_correlation.set_current_correlation_id(correlation_id) |
| 478 | # Why this request changes what it changes, when the caller says |
| 479 | # (object_record_changes: the history records it as the entry message). |
| 480 | reason_token = object_record_changes.set_change_reason( |
| 481 | request_headers.get(object_record_changes.CHANGE_REASON_HEADER)) |
| 482 | minted_visitor_token = _mint_visitor_token(path, request_headers) |
| 483 | |
| 484 | response_started = False |
| 485 | |
| 486 | async def send_with_metrics(message): |
| 487 | nonlocal status_code, response_started |
| 488 | if message["type"] == "http.response.start": |
| 489 | response_started = True |
| 490 | status_code = int(message.get("status", status_code)) |
| 491 | headers = list(message.get("headers", [])) |
| 492 | if not any( |
| 493 | name.lower() == object_correlation.CORRELATION_ID_HEADER.encode("latin-1") |
| 494 | for name, _value in headers |
| 495 | ): |
| 496 | headers.append( |
| 497 | ( |
| 498 | object_correlation.CORRELATION_ID_HEADER.encode("latin-1"), |
| 499 | correlation_id.encode("latin-1"), |
| 500 | ) |
| 501 | ) |
| 502 | if minted_visitor_token: |
| 503 | headers.append(( |
| 504 | b"set-cookie", |
| 505 | object_analytics.visitor_cookie_header( |
| 506 | minted_visitor_token, |
| 507 | secure=_cookie_secure_enabled(), |
| 508 | ).encode("latin-1"), |
| 509 | )) |
| 510 | message = {**message, "headers": headers} |
| 511 | await send(message) |
| 512 | |
| 513 | try: |
| 514 | try: |
| 515 | await _handle_http(scope, receive, send_with_metrics) |
| 516 | except IdentityStoreUnavailable: |
| 517 | if response_started: |
| 518 | raise |
| 519 | await _send_identity_store_unavailable(send_with_metrics) |
| 520 | except AccountUnusable: |
| 521 | if response_started: |
| 522 | raise |
| 523 | await _send_account_unusable(send_with_metrics) |
| 524 | finally: |
| 525 | object_record_changes.reset_change_reason(reason_token) |
| 526 | object_correlation.reset_current_correlation_id(correlation_token) |
| 527 | duration_ms = (time.perf_counter() - started_at) * 1000 |
| 528 | _metrics.record_request(method, path, status_code, duration_ms) |
| 529 | await _capture_page_view(scope, method, path, status_code, request_headers, |
| 530 | minted_visitor_token=minted_visitor_token) |
| 531 | |
| 532 | |
| 533 | def _mint_visitor_token(path: str, headers: dict[str, str]) -> str: |
| 534 | """A new anonymous visitor token for this response, or "" for none. |
| 535 | |
| 536 | Decided ONCE per request, before the response starts, because the same |
| 537 | answer is needed in two places: the `set-cookie` header on the way out |
| 538 | and the `page_views.session_id` stamp on the row that request writes. |
| 539 | Minting it twice would give a visitor a cookie whose value never |
| 540 | appears in the log. |
| 541 | |
| 542 | Every refusal (analytics off, DNT, Sec-GPC, an existing cookie, a |
| 543 | non-page path) lives in object_analytics.should_set_visitor_cookie, |
| 544 | which is pure and tested; this function is the wiring and nothing |
| 545 | else. Best-effort like the rest of the analytics path: a visitor |
| 546 | counter may never be the reason a response fails. |
| 547 | """ |
| 548 | try: |
| 549 | if not object_analytics.should_set_visitor_cookie(path, headers): |
| 550 | return "" |
| 551 | return object_analytics.new_visitor_token() |
| 552 | except Exception: # noqa: BLE001 -- analytics must never break a response |
| 553 | return "" |
| 554 | |
| 555 | |
| 556 | async def _capture_page_view( |
| 557 | scope: dict[str, Any], method: str, path: str, status_code: int, |
| 558 | headers: dict[str, str], *, minted_visitor_token: str = "", |
| 559 | ) -> None: |
| 560 | """Append one page_views row for this request (analytics). Off unless |
| 561 | DBBASIC_ANALYTICS is set; skips asset/infra paths; the file write is |
| 562 | offloaded to a thread so it never blocks the event loop under load; and the |
| 563 | whole thing is best-effort -- analytics must NEVER break a response (a |
| 564 | missing page_views collection, a full disk, anything, is swallowed).""" |
| 565 | try: |
| 566 | if not object_analytics.analytics_enabled() or not object_analytics.should_capture(path): |
| 567 | return |
| 568 | record = object_analytics.build_page_view( |
| 569 | path=path, method=method, status=status_code, |
| 570 | ip=_client_ip(scope, headers), headers=headers, |
| 571 | owners=object_analytics.owner_ips(), |
| 572 | # The operator's own automation is not visitor traffic. This is a |
| 573 | # constant-time env compare, not an auth lookup -- the hot path |
| 574 | # stays cheap, and a signed-in member browsing is deliberately |
| 575 | # still counted as the real traffic it is. |
| 576 | is_operator=_request_is_operator(headers), |
| 577 | # The cookie this response is setting. The browser cannot have |
| 578 | # sent it back yet, so without it the first page of every visit |
| 579 | # is threadless and every funnel starts one step late. |
| 580 | minted_visitor_token=minted_visitor_token, |
| 581 | ) |
| 582 | base_dir = _data_dir() |
| 583 | |
| 584 | def _write() -> None: |
| 585 | try: |
| 586 | # write-path: server-authored analytics row, no caller values written |
| 587 | object_records.create_collection_record( |
| 588 | object_analytics.PAGE_VIEWS_COLLECTION, record, |
| 589 | base_dir=base_dir, actor="server:analytics", |
| 590 | ) |
| 591 | except Exception: # noqa: BLE001 -- never surface an analytics write error |
| 592 | pass |
| 593 | |
| 594 | await asyncio.to_thread(_write) |
| 595 | except Exception: # noqa: BLE001 -- belt and suspenders on the hot path |
| 596 | pass |
| 597 | |
| 598 | |
| 599 | def _secret_equals(given: str, secret: str) -> bool: |
| 600 | """Constant-time comparison of a presented credential with a configured one. |
| 601 | |
| 602 | On bytes: hmac.compare_digest refuses a str with non-ASCII characters |
| 603 | (TypeError), so a header like "Bearer \u00e9" answered 500 instead of |
| 604 | being an ordinary wrong token. |
| 605 | """ |
| 606 | return hmac.compare_digest(given.encode("utf-8"), secret.encode("utf-8")) |
| 607 | |
| 608 | |
| 609 | def _request_is_operator(headers: dict[str, str]) -> bool: |
| 610 | """True when this request carried the admin token. |
| 611 | |
| 612 | Deliberately only the token, and deliberately constant-time: this runs |
| 613 | on every request, so it may not touch disk, and it must not leak the |
| 614 | token through timing. A session cookie is NOT resolved here -- that |
| 615 | would be a per-request identity lookup on the hot path, and a signed-in |
| 616 | member is traffic worth measuring anyway. |
| 617 | """ |
| 618 | admin_token = os.environ.get(ADMIN_TOKEN_ENV, "") |
| 619 | if not admin_token: |
| 620 | return False |
| 621 | request_token = _authorization_token(headers) |
| 622 | if not request_token: |
| 623 | return False |
| 624 | return _secret_equals(request_token, admin_token) |
| 625 | |
| 626 | |
| 627 | def _realtime_enabled() -> bool: |
| 628 | value = os.environ.get(REALTIME_ENABLED_ENV) |
| 629 | if value is None: |
| 630 | return True |
| 631 | return value.strip().lower() in TRUE_VALUES |
| 632 | |
| 633 | |
| 634 | def _realtime_queue_max() -> int: |
| 635 | return _env_int(REALTIME_QUEUE_MAX_ENV, object_realtime.DEFAULT_QUEUE_MAX) |
| 636 | |
| 637 | |
| 638 | async def _handle_websocket(scope: dict[str, Any], receive, send) -> None: |
| 639 | """Live push transport: authenticated, permission-filtered record events. |
| 640 | |
| 641 | A client connects to /ws with its session (cookie or bearer), |
| 642 | subscribes to collections it is allowed to read, and receives a small |
| 643 | signal ({type: record, collection, record_id, action}) whenever a |
| 644 | matching record it can see changes — never the record body, so no |
| 645 | surface can leak fields. The client refetches through the normal |
| 646 | permission-enforced API. The durable event log stays as the poll-based |
| 647 | fallback for missed events and multi-worker deployments. |
| 648 | """ |
| 649 | headers = _parse_headers(scope.get("headers", [])) |
| 650 | |
| 651 | # Consume the connect frame first so we can accept or reject cleanly. |
| 652 | connect = await receive() |
| 653 | if connect.get("type") != "websocket.connect": |
| 654 | return |
| 655 | |
| 656 | if not _realtime_enabled() or scope.get("path") != WEBSOCKET_PATH: |
| 657 | await send({"type": "websocket.close", "code": 1008}) |
| 658 | return |
| 659 | |
| 660 | try: |
| 661 | subject = _permission_subject(headers) |
| 662 | except IdentityStoreUnavailable: |
| 663 | await send({"type": "websocket.close", "code": 1013}) # try again later |
| 664 | return |
| 665 | except AccountUnusable: |
| 666 | await send({"type": "websocket.close", "code": 1008}) |
| 667 | return |
| 668 | if subject.user_id is None and "admin" not in subject.roles: |
| 669 | await send({"type": "websocket.close", "code": 1008}) |
| 670 | return |
| 671 | |
| 672 | await send({"type": "websocket.accept"}) |
| 673 | queue: "asyncio.Queue[dict[str, Any]]" = asyncio.Queue(maxsize=_realtime_queue_max()) |
| 674 | subscriber = object_realtime.Subscriber(subject=subject, queue=queue) |
| 675 | _realtime_hub.add(subscriber) |
| 676 | await _ws_send(send, {"type": "welcome", "user": subject.user_id}) |
| 677 | |
| 678 | reader = asyncio.ensure_future(_ws_reader(receive, send, subscriber)) |
| 679 | writer = asyncio.ensure_future(_ws_writer(send, queue)) |
| 680 | try: |
| 681 | done, pending = await asyncio.wait( |
| 682 | {reader, writer}, return_when=asyncio.FIRST_COMPLETED |
| 683 | ) |
| 684 | for task in pending: |
| 685 | task.cancel() |
| 686 | for task in done: |
| 687 | with contextlib.suppress(Exception): |
| 688 | task.result() |
| 689 | finally: |
| 690 | _realtime_hub.remove(subscriber) |
| 691 | with contextlib.suppress(Exception): |
| 692 | await send({"type": "websocket.close"}) |
| 693 | |
| 694 | |
| 695 | async def _ws_reader(receive, send, subscriber) -> None: |
| 696 | while True: |
| 697 | message = await receive() |
| 698 | kind = message.get("type") |
| 699 | if kind == "websocket.disconnect": |
| 700 | return |
| 701 | if kind != "websocket.receive": |
| 702 | continue |
| 703 | text = message.get("text") |
| 704 | if not text: |
| 705 | continue |
| 706 | try: |
| 707 | data = json.loads(text) |
| 708 | except (ValueError, TypeError): |
| 709 | continue |
| 710 | if not isinstance(data, dict): |
| 711 | continue |
| 712 | action = data.get("action") |
| 713 | if action == "subscribe": |
| 714 | for collection in _ws_clean_collections(data.get("collections")): |
| 715 | if len(subscriber.collections) >= MAX_WS_SUBSCRIPTIONS: |
| 716 | break |
| 717 | if _ws_can_subscribe(subscriber.subject, collection): |
| 718 | subscriber.collections.add(collection) |
| 719 | await _ws_send( |
| 720 | send, {"type": "subscribed", "collections": sorted(subscriber.collections)} |
| 721 | ) |
| 722 | elif action == "unsubscribe": |
| 723 | for collection in _ws_clean_collections(data.get("collections")): |
| 724 | subscriber.collections.discard(collection) |
| 725 | await _ws_send( |
| 726 | send, {"type": "subscribed", "collections": sorted(subscriber.collections)} |
| 727 | ) |
| 728 | elif action == "ping": |
| 729 | await _ws_send(send, {"type": "pong"}) |
| 730 | |
| 731 | |
| 732 | async def _ws_writer(send, queue) -> None: |
| 733 | while True: |
| 734 | event = await queue.get() |
| 735 | await _ws_send(send, event) |
| 736 | |
| 737 | |
| 738 | async def _ws_send(send, payload: dict[str, Any]) -> None: |
| 739 | await send({"type": "websocket.send", "text": json.dumps(payload, default=str)}) |
| 740 | |
| 741 | |
| 742 | def _ws_clean_collections(value: Any) -> list[str]: |
| 743 | if not isinstance(value, list): |
| 744 | return [] |
| 745 | out: list[str] = [] |
| 746 | for item in value: |
| 747 | if isinstance(item, str) and object_collections.validate_collection_name(item): |
| 748 | out.append(item) |
| 749 | if len(out) >= MAX_WS_SUBSCRIPTIONS: |
| 750 | break |
| 751 | return out |
| 752 | |
| 753 | |
| 754 | def _ws_can_subscribe(subject, collection: str) -> bool: |
| 755 | """A subject may follow a collection only if it may read it.""" |
| 756 | if not _permission_checks_enabled() or not _permission_enforcement_enabled(): |
| 757 | return True |
| 758 | try: |
| 759 | policy = object_permission_store.load_policy(_data_dir()) |
| 760 | except (OSError, ValueError): |
| 761 | return False |
| 762 | decision = object_permissions.check_permission( |
| 763 | subject, object_permissions.READ, policy=policy, collection=collection |
| 764 | ) |
| 765 | return decision.allowed |
| 766 | |
| 767 | |
| 768 | def _realtime_publish(collection: str, record_id: str, action: str, record) -> None: |
| 769 | """Push a record-change signal to permitted live subscribers. |
| 770 | |
| 771 | Runs the same read decision as a GET: with enforcement on, a |
| 772 | subscriber only hears about a record its row filter would let it see. |
| 773 | Only the id and action travel — never the record body. |
| 774 | """ |
| 775 | if not _realtime_enabled() or not collection: |
| 776 | return |
| 777 | subscribers = _realtime_hub.wanting(collection) |
| 778 | if not subscribers: |
| 779 | return |
| 780 | |
| 781 | enforced = _permission_checks_enabled() and _permission_enforcement_enabled() |
| 782 | policy = None |
| 783 | if enforced: |
| 784 | try: |
| 785 | policy = object_permission_store.load_policy(_data_dir()) |
| 786 | except (OSError, ValueError): |
| 787 | return # cannot filter safely -> do not push |
| 788 | |
| 789 | event = { |
| 790 | "type": "record", |
| 791 | "collection": collection, |
| 792 | "record_id": record_id, |
| 793 | "action": action, |
| 794 | } |
| 795 | for subscriber in subscribers: |
| 796 | if enforced and record is not None: |
| 797 | decision = object_permissions.check_permission( |
| 798 | subscriber.subject, |
| 799 | object_permissions.READ, |
| 800 | policy=policy, |
| 801 | collection=collection, |
| 802 | record=record, |
| 803 | ) |
| 804 | if not decision.allowed: |
| 805 | continue |
| 806 | subscriber.deliver(dict(event)) |
| 807 | |
| 808 | |
| 809 | async def _handle_http(scope: dict[str, Any], receive, send) -> None: |
| 810 | method = scope.get("method", "GET").upper() |
| 811 | path = scope.get("path", "/") |
| 812 | query = _parse_query(scope.get("query_string", b"")) |
| 813 | raw_headers = scope.get("headers", []) |
| 814 | headers = _parse_headers(raw_headers) |
| 815 | correlation_id = object_correlation.current_correlation_id() |
| 816 | if correlation_id is not None: |
| 817 | headers[object_correlation.CORRELATION_ID_HEADER] = correlation_id |
| 818 | |
| 819 | # Two Authorization headers mean a proxy and this server could pick |
| 820 | # different ones. Refuse rather than guess (the parsed dict keeps the last). |
| 821 | if sum(1 for name, _ in raw_headers if name.lower() == b"authorization") > 1: |
| 822 | await _send_json( |
| 823 | send, |
| 824 | {"status": "error", "error": "Multiple Authorization headers are not allowed"}, |
| 825 | status=400, |
| 826 | ) |
| 827 | return |
| 828 | |
| 829 | _maybe_append_metrics_snapshot() |
| 830 | _permission_readiness_watch() |
| 831 | |
| 832 | if path == "/health": |
| 833 | if _is_detailed_health(query) and await _send_rate_limit_if_needed(scope, headers, send): |
| 834 | return |
| 835 | await _handle_health(send, query, headers) |
| 836 | return |
| 837 | |
| 838 | if await _send_rate_limit_if_needed(scope, headers, send): |
| 839 | return |
| 840 | |
| 841 | if not await _prewarm_identity_sources(headers): |
| 842 | await _send_json( |
| 843 | send, |
| 844 | { |
| 845 | "status": "error", |
| 846 | "error": "Identity verification is temporarily unavailable", |
| 847 | "retry_after": IDENTITY_UNAVAILABLE_RETRY_AFTER_SECONDS, |
| 848 | }, |
| 849 | status=503, |
| 850 | headers=[("retry-after", str(IDENTITY_UNAVAILABLE_RETRY_AFTER_SECONDS))], |
| 851 | ) |
| 852 | return |
| 853 | |
| 854 | # A one-click box with no owner yet answers nothing but /health and /setup (object_setup). The admin |
| 855 | # token still works: whoever holds it already has root on the box. |
| 856 | if ( |
| 857 | path != object_setup.SETUP_PATH |
| 858 | and object_setup.waiting(_data_dir()) |
| 859 | and _admin_token_gate_error(headers, "") is not None |
| 860 | ): |
| 861 | await _send_setup_waiting(send, method, headers) |
| 862 | return |
| 863 | |
| 864 | if ( |
| 865 | method not in {"GET", "HEAD", "OPTIONS"} |
| 866 | and _authorization_token(headers) is None |
| 867 | and _session_cookie_token(headers) is not None |
| 868 | and not _cookie_request_origin_allowed(headers) |
| 869 | ): |
| 870 | await _send_json( |
| 871 | send, |
| 872 | {"status": "error", "error": "Cross-origin cookie request rejected"}, |
| 873 | status=403, |
| 874 | ) |
| 875 | return |
| 876 | |
| 877 | request_limit = _max_concurrent_requests() |
| 878 | request_token = _request_limiter.try_acquire(request_limit) |
| 879 | if request_token is None: |
| 880 | await _send_capacity_error(send, limit_name="requests", max_concurrent=request_limit) |
| 881 | return |
| 882 | |
| 883 | try: |
| 884 | try: |
| 885 | body = await _read_body( |
| 886 | receive, headers=headers, max_bytes=_webdav_body_limit(method, path) |
| 887 | ) |
| 888 | except RequestBodyTooLargeError as exc: |
| 889 | await _send_request_too_large(send, exc) |
| 890 | return |
| 891 | |
| 892 | if path == http_api_contract.MCP_PATH: |
| 893 | await _handle_mcp(send, method, body, headers) |
| 894 | return |
| 895 | |
| 896 | webhooks_prefix = http_api_contract.WEBHOOKS_PATH + "/" |
| 897 | if path.startswith(webhooks_prefix): |
| 898 | await _handle_webhook(send, method, path.removeprefix(webhooks_prefix), |
| 899 | body, query, headers) |
| 900 | return |
| 901 | |
| 902 | if path == http_api_contract.EXCHANGE_PROFILE_PATH: |
| 903 | await _handle_exchange_profile(send, method, headers) |
| 904 | return |
| 905 | |
| 906 | if path == http_api_contract.SEARCH_PATH: |
| 907 | await _handle_search(send, method, query, headers) |
| 908 | return |
| 909 | |
| 910 | if path == http_api_contract.AI_CHAT_PATH: |
| 911 | await _handle_ai_chat(send, method, body, headers) |
| 912 | return |
| 913 | |
| 914 | if path == http_api_contract.TTS_PATH: |
| 915 | await _handle_tts(send, method, body, headers) |
| 916 | return |
| 917 | |
| 918 | if path == http_api_contract.STT_PATH: |
| 919 | await _handle_stt(send, method, body, headers) |
| 920 | return |
| 921 | |
| 922 | if path == http_api_contract.READ_PATH: |
| 923 | await _handle_read(send, method, body, headers) |
| 924 | return |
| 925 | |
| 926 | schema_meta_prefix = f"{http_api_contract.SCHEMA_META_PATH}/" |
| 927 | if path.startswith(schema_meta_prefix): |
| 928 | await _handle_schema_meta(send, method, path.removeprefix(schema_meta_prefix)) |
| 929 | return |
| 930 | |
| 931 | if path == http_api_contract.FLAGS_PATH: |
| 932 | await _handle_flags(send, method, headers) |
| 933 | return |
| 934 | |
| 935 | if path == http_api_contract.ACTIVITY_PATH: |
| 936 | await _handle_activity(send, method, query, headers) |
| 937 | return |
| 938 | |
| 939 | # 64 (feed): the composed follow-graph read. Lives at /api/feed, not |
| 940 | # bare /feed, because /feed is this feature's own PAGE route (site_feed, |
| 941 | # packages/app-feed), resolved further down by the site-route |
| 942 | # convention -- the same /api/{x} (data) vs /{x} (page) split |
| 943 | # /api/activity above already uses opposite site_activity, so the two |
| 944 | # surfaces never collide on one path. |
| 945 | if path == "/api/feed": |
| 946 | await _handle_feed(send, method, query, headers) |
| 947 | return |
| 948 | |
| 949 | # Stage 7 derived-read verbs: folded/computed data an agent can't get |
| 950 | # as a plain collection read. Owner-scoped (the caller's own books/ |
| 951 | # stock), thin wrappers over object_stock/object_finance's own pure |
| 952 | # fold functions -- the MCP get_stock_levels/get_finance_summary verbs |
| 953 | # route here. |
| 954 | if path == "/api/stock": |
| 955 | await _handle_stock_levels(send, method, headers) |
| 956 | return |
| 957 | if path == "/api/finance/summary": |
| 958 | await _handle_finance_summary(send, method, headers) |
| 959 | return |
| 960 | |
| 961 | if path == http_api_contract.PREFS_PATH: |
| 962 | await _handle_prefs(send, method, headers) |
| 963 | return |
| 964 | |
| 965 | prefs_prefix = http_api_contract.PREFS_PATH + "/" |
| 966 | if path.startswith(prefs_prefix): |
| 967 | await _handle_pref(send, method, path[len(prefs_prefix):], body, headers) |
| 968 | return |
| 969 | |
| 970 | if path == http_api_contract.WEBDAV_PATH or path.startswith(http_api_contract.WEBDAV_PATH + "/"): |
| 971 | await _handle_webdav(send, method, path, body, headers) |
| 972 | return |
| 973 | |
| 974 | if path == http_api_contract.USER_FILES_PATH: |
| 975 | await _handle_user_file_upload(send, method, body, headers) |
| 976 | return |
| 977 | |
| 978 | user_file_prefix = http_api_contract.USER_FILES_PATH + "/" |
| 979 | if path.startswith(user_file_prefix): |
| 980 | await _handle_user_file(send, method, path[len(user_file_prefix):], headers) |
| 981 | return |
| 982 | |
| 983 | if path == "/api/share": |
| 984 | await _handle_share(send, method, query, body, headers) |
| 985 | return |
| 986 | if path.startswith("/api/share/"): |
| 987 | await _handle_share_revoke(send, method, path[len("/api/share/"):], headers) |
| 988 | return |
| 989 | |
| 990 | if path == http_api_contract.LOGIN_PATH: |
| 991 | await _handle_login(send, method, query, body, headers) |
| 992 | return |
| 993 | |
| 994 | if path == http_api_contract.LOGOUT_PATH: |
| 995 | await _handle_logout(send, method, headers) |
| 996 | return |
| 997 | |
| 998 | if path == http_api_contract.SIGNUP_PATH: |
| 999 | await _handle_signup(scope, send, method, query, body, headers) |
| 1000 | return |
| 1001 | |
| 1002 | if path == object_setup.SETUP_PATH: |
| 1003 | await _handle_setup(scope, send, method, body, headers) |
| 1004 | return |
| 1005 | |
| 1006 | if path == http_api_contract.VERIFY_EMAIL_PATH: |
| 1007 | await _handle_verify_email(send, method, query, body, headers) |
| 1008 | return |
| 1009 | |
| 1010 | if path == http_api_contract.PASSWORD_RESET_PATH: |
| 1011 | await _handle_password_reset(scope, send, method, query, body, headers) |
| 1012 | return |
| 1013 | |
| 1014 | if path == http_api_contract.PASSWORD_RESET_CONFIRM_PATH: |
| 1015 | await _handle_password_reset_confirm(send, method, query, body, headers) |
| 1016 | return |
| 1017 | |
| 1018 | if path == http_api_contract.IDENTITY_ACCOUNTS_PATH: |
| 1019 | await _handle_identity_accounts(send, method, body, headers) |
| 1020 | return |
| 1021 | |
| 1022 | identity_account_prefix = http_api_contract.IDENTITY_ACCOUNTS_PATH + "/" |
| 1023 | if path.startswith(identity_account_prefix): |
| 1024 | account_id = path[len(identity_account_prefix):] |
| 1025 | await _handle_identity_account(send, method, account_id, headers, body) |
| 1026 | return |
| 1027 | |
| 1028 | if path == http_api_contract.IDENTITY_USERS_PATH: |
| 1029 | await _handle_identity_users(send, method, query, body, headers) |
| 1030 | return |
| 1031 | |
| 1032 | identity_user_prefix = http_api_contract.IDENTITY_USERS_PATH + "/" |
| 1033 | if path.startswith(identity_user_prefix): |
| 1034 | user_id = path[len(identity_user_prefix):] |
| 1035 | await _handle_identity_user(send, method, user_id, body, headers) |
| 1036 | return |
| 1037 | |
| 1038 | if path == http_api_contract.IDENTITY_SESSIONS_PATH: |
| 1039 | await _handle_identity_sessions(send, method, body, headers) |
| 1040 | return |
| 1041 | |
| 1042 | identity_session_prefix = http_api_contract.IDENTITY_SESSIONS_PATH + "/" |
| 1043 | if path.startswith(identity_session_prefix): |
| 1044 | session_id = path[len(identity_session_prefix):] |
| 1045 | await _handle_identity_session(send, method, session_id, headers) |
| 1046 | return |
| 1047 | |
| 1048 | if path == http_api_contract.IDENTITY_CURRENT_SESSION_PATH: |
| 1049 | await _handle_identity_current_session(send, method, body, headers) |
| 1050 | return |
| 1051 | |
| 1052 | if path == http_api_contract.IDENTITY_PATH: |
| 1053 | await _handle_identity(send, method, headers) |
| 1054 | return |
| 1055 | |
| 1056 | if path == http_api_contract.PERMISSIONS_POLICY_PATH: |
| 1057 | await _handle_permissions_policy(send, method, body, headers) |
| 1058 | return |
| 1059 | |
| 1060 | if path == http_api_contract.PERMISSIONS_STATUS_PATH: |
| 1061 | await _handle_permissions_status(send, method, headers) |
| 1062 | return |
| 1063 | |
| 1064 | if path == http_api_contract.PERMISSIONS_CHECK_PATH: |
| 1065 | await _handle_permissions_check(send, method, body, headers) |
| 1066 | return |
| 1067 | |
| 1068 | if path == http_api_contract.PERMISSIONS_AUDIT_PATH: |
| 1069 | await _handle_permissions_audit(send, method, query, headers) |
| 1070 | return |
| 1071 | |
| 1072 | if path == http_api_contract.PERMISSIONS_UNSHIPPED_PATH: |
| 1073 | await _handle_permissions_unshipped(send, method, headers) |
| 1074 | return |
| 1075 | |
| 1076 | if path == http_api_contract.EVENTS_PATH: |
| 1077 | await _handle_events(send, method, query, body, headers) |
| 1078 | return |
| 1079 | |
| 1080 | if path == http_api_contract.EVENT_DELIVERIES_PATH: |
| 1081 | await _handle_event_deliveries(send, method, query, headers) |
| 1082 | return |
| 1083 | |
| 1084 | if path == http_api_contract.EVENT_SUBSCRIPTIONS_PATH: |
| 1085 | await _handle_event_subscriptions(send, method, query, body, headers) |
| 1086 | return |
| 1087 | |
| 1088 | if path == http_api_contract.ADMIN_STATUS_PATH: |
| 1089 | await _handle_admin_status(send, method, headers) |
| 1090 | return |
| 1091 | |
| 1092 | if path == http_api_contract.ADMIN_STORAGE_PATH: |
| 1093 | await _handle_admin_storage(send, method, headers) |
| 1094 | return |
| 1095 | |
| 1096 | if path == http_api_contract.ADMIN_CHANGES_PATH: |
| 1097 | await _handle_admin_changes(send, method, query, headers) |
| 1098 | return |
| 1099 | |
| 1100 | if path == http_api_contract.ADMIN_OPS_PATH: |
| 1101 | await _handle_admin_ops(send, method, query, headers) |
| 1102 | return |
| 1103 | |
| 1104 | if path == http_api_contract.ADMIN_BACKUPS_PATH: |
| 1105 | await _handle_admin_backups(send, method, headers) |
| 1106 | return |
| 1107 | |
| 1108 | if path in (http_api_contract.ADMIN_SCHEDULED_BACKUPS_PATH, |
| 1109 | http_api_contract.ADMIN_SCHEDULED_BACKUPS_RUN_PATH, |
| 1110 | http_api_contract.ADMIN_SCHEDULED_BACKUPS_TEST_PATH): |
| 1111 | await _handle_admin_scheduled_backups(send, method, path, headers) |
| 1112 | return |
| 1113 | |
| 1114 | admin_backups_prefix = f"{http_api_contract.ADMIN_BACKUPS_PATH}/" |
| 1115 | if path.startswith(admin_backups_prefix): |
| 1116 | tail = path.removeprefix(admin_backups_prefix) |
| 1117 | if tail.endswith("/download"): |
| 1118 | backup_id = tail.removesuffix("/download") |
| 1119 | await _handle_admin_backup_download(send, method, backup_id, headers) |
| 1120 | return |
| 1121 | if tail.endswith("/preview"): |
| 1122 | backup_id = tail.removesuffix("/preview") |
| 1123 | await _handle_admin_backup_preview(send, method, backup_id, query, headers) |
| 1124 | return |
| 1125 | if tail.endswith("/record"): |
| 1126 | backup_id = tail.removesuffix("/record") |
| 1127 | await _handle_admin_backup_record(send, method, backup_id, query, headers) |
| 1128 | return |
| 1129 | await _send_json(send, {"status": "error", "error": "Not found"}, status=404) |
| 1130 | return |
| 1131 | |
| 1132 | if path == http_api_contract.ADMIN_FILES_PATH: |
| 1133 | await _handle_admin_files(send, method, query, headers) |
| 1134 | return |
| 1135 | |
| 1136 | admin_files_prefix = f"{http_api_contract.ADMIN_FILES_PATH}/" |
| 1137 | if path.startswith(admin_files_prefix): |
| 1138 | object_id = path.removeprefix(admin_files_prefix) |
| 1139 | await _handle_admin_object_files(send, method, object_id, query, body, headers) |
| 1140 | return |
| 1141 | |
| 1142 | if path == http_api_contract.ADMIN_RECONCILES_PATH: |
| 1143 | await _handle_admin_reconciles(send, method, query, headers) |
| 1144 | return |
| 1145 | |
| 1146 | admin_reconciles_prefix = f"{http_api_contract.ADMIN_RECONCILES_PATH}/" |
| 1147 | if path.startswith(admin_reconciles_prefix): |
| 1148 | reconcile_tail = path.removeprefix(admin_reconciles_prefix) |
| 1149 | if reconcile_tail.endswith("/resolve"): |
| 1150 | reconcile_id = reconcile_tail.removesuffix("/resolve") |
| 1151 | await _handle_admin_reconcile_resolve(send, method, reconcile_id, body, headers) |
| 1152 | else: |
| 1153 | await _handle_admin_reconcile(send, method, reconcile_tail, headers) |
| 1154 | return |
| 1155 | |
| 1156 | if path == http_api_contract.ADMIN_OBJECTS_PATH: |
| 1157 | await _handle_admin_objects(send, method, body, headers) |
| 1158 | return |
| 1159 | |
| 1160 | admin_objects_prefix = f"{http_api_contract.ADMIN_OBJECTS_PATH}/" |
| 1161 | if path.startswith(admin_objects_prefix): |
| 1162 | object_tail = path.removeprefix(admin_objects_prefix) |
| 1163 | if object_tail.endswith("/execute"): |
| 1164 | object_id = object_tail.removesuffix("/execute") |
| 1165 | await _handle_admin_object_execute(send, method, object_id, body, headers) |
| 1166 | return |
| 1167 | |
| 1168 | if object_tail.endswith("/override"): |
| 1169 | object_id = object_tail.removesuffix("/override") |
| 1170 | await _handle_admin_object_override(send, method, object_id, headers) |
| 1171 | return |
| 1172 | |
| 1173 | object_id = object_tail |
| 1174 | await _handle_admin_object(send, method, object_id, query, body, headers) |
| 1175 | return |
| 1176 | |
| 1177 | if path == http_api_contract.ADMIN_COLLECTIONS_PATH: |
| 1178 | await _handle_admin_collections(send, method, headers) |
| 1179 | return |
| 1180 | |
| 1181 | admin_collections_prefix = f"{http_api_contract.ADMIN_COLLECTIONS_PATH}/" |
| 1182 | if path.startswith(admin_collections_prefix): |
| 1183 | collection_tail = path.removeprefix(admin_collections_prefix) |
| 1184 | await _handle_admin_collection(send, method, collection_tail, query, body, headers) |
| 1185 | return |
| 1186 | |
| 1187 | if path == http_api_contract.ADMIN_SCHEMAS_PATH: |
| 1188 | await _handle_admin_schemas(send, method, headers) |
| 1189 | return |
| 1190 | |
| 1191 | admin_schemas_prefix = f"{http_api_contract.ADMIN_SCHEMAS_PATH}/" |
| 1192 | if path.startswith(admin_schemas_prefix): |
| 1193 | schema = path.removeprefix(admin_schemas_prefix) |
| 1194 | await _handle_admin_schema(send, method, schema, query, body, headers) |
| 1195 | return |
| 1196 | |
| 1197 | if path == http_api_contract.ADMIN_IDENTITY_ACCOUNTS_PATH: |
| 1198 | await _handle_admin_identity_accounts(send, method, headers) |
| 1199 | return |
| 1200 | |
| 1201 | admin_identity_accounts_prefix = f"{http_api_contract.ADMIN_IDENTITY_ACCOUNTS_PATH}/" |
| 1202 | if path.startswith(admin_identity_accounts_prefix): |
| 1203 | account_id = path.removeprefix(admin_identity_accounts_prefix) |
| 1204 | await _handle_admin_identity_account(send, method, account_id, headers) |
| 1205 | return |
| 1206 | |
| 1207 | if path == http_api_contract.ADMIN_IDENTITY_USERS_PATH: |
| 1208 | await _handle_admin_identity_users(send, method, query, headers) |
| 1209 | return |
| 1210 | |
| 1211 | admin_identity_users_prefix = f"{http_api_contract.ADMIN_IDENTITY_USERS_PATH}/" |
| 1212 | if path.startswith(admin_identity_users_prefix): |
| 1213 | user_id = path.removeprefix(admin_identity_users_prefix) |
| 1214 | await _handle_admin_identity_user(send, method, user_id, body, headers) |
| 1215 | return |
| 1216 | |
| 1217 | if path == http_api_contract.ADMIN_IDENTITY_SESSIONS_PATH: |
| 1218 | await _handle_admin_identity_sessions(send, method, headers) |
| 1219 | return |
| 1220 | |
| 1221 | admin_identity_sessions_prefix = f"{http_api_contract.ADMIN_IDENTITY_SESSIONS_PATH}/" |
| 1222 | if path.startswith(admin_identity_sessions_prefix): |
| 1223 | session_id = path.removeprefix(admin_identity_sessions_prefix) |
| 1224 | await _handle_admin_identity_session(send, method, session_id, headers) |
| 1225 | return |
| 1226 | |
| 1227 | if path == http_api_contract.ADMIN_IDENTITY_SOURCES_FORGET_PATH: |
| 1228 | await _handle_admin_identity_sources_forget(send, method, body, headers) |
| 1229 | return |
| 1230 | |
| 1231 | if path == http_api_contract.DAEMON_STATUS_PATH: |
| 1232 | await _handle_daemon_status(send, method, headers) |
| 1233 | return |
| 1234 | |
| 1235 | if path == http_api_contract.DAEMON_SCHEDULER_TASKS_PATH: |
| 1236 | await _handle_daemon_scheduler_tasks(send, method, query, body, headers) |
| 1237 | return |
| 1238 | |
| 1239 | daemon_scheduler_prefix = http_api_contract.DAEMON_SCHEDULER_TASKS_PATH + "/" |
| 1240 | if path.startswith(daemon_scheduler_prefix): |
| 1241 | task_id = path[len(daemon_scheduler_prefix):] |
| 1242 | await _handle_daemon_scheduler_task(send, method, task_id, body, headers) |
| 1243 | return |
| 1244 | |
| 1245 | if path == http_api_contract.DAEMON_QUEUE_MESSAGES_PATH: |
| 1246 | await _handle_daemon_queue_messages(send, method, query, body, headers) |
| 1247 | return |
| 1248 | |
| 1249 | daemon_queue_prefix = http_api_contract.DAEMON_QUEUE_MESSAGES_PATH + "/" |
| 1250 | if path.startswith(daemon_queue_prefix): |
| 1251 | message_id = path[len(daemon_queue_prefix):] |
| 1252 | await _handle_daemon_queue_message(send, method, message_id, body, headers) |
| 1253 | return |
| 1254 | |
| 1255 | if path == http_api_contract.PACKAGES_PATH: |
| 1256 | await _handle_packages(send, method, headers) |
| 1257 | return |
| 1258 | |
| 1259 | if path.startswith(f"{http_api_contract.PACKAGES_PATH}/"): |
| 1260 | package_tail = path.removeprefix(f"{http_api_contract.PACKAGES_PATH}/") |
| 1261 | package_parts = package_tail.split("/") |
| 1262 | if len(package_parts) == 2 and package_parts[1] == "install": |
| 1263 | await _handle_package_install(send, method, package_parts[0], body, headers) |
| 1264 | elif len(package_parts) == 2 and package_parts[1] == "restore": |
| 1265 | await _handle_package_restore(send, method, package_parts[0], body, headers) |
| 1266 | elif len(package_parts) == 2 and package_parts[1] == "changes": |
| 1267 | await _handle_package_changes(send, method, package_parts[0], query, headers) |
| 1268 | else: |
| 1269 | await _handle_package(send, method, package_tail, query, headers) |
| 1270 | return |
| 1271 | |
| 1272 | if path == http_api_contract.OBJECTS_PATH: |
| 1273 | if method == "GET": |
| 1274 | gate_error = _admin_token_gate_error( |
| 1275 | headers, |
| 1276 | f"Object listing requires {ADMIN_TOKEN_ENV}.", |
| 1277 | ) |
| 1278 | if gate_error is not None: |
| 1279 | # A signed-in user with a namespace sees their own |
| 1280 | # objects and the system ones; never another user's. |
| 1281 | list_user_id = _numeric_caller_user_id(headers) |
| 1282 | if list_user_id is not None: |
| 1283 | await _send_json(send, _list_objects_payload(owner_user_id=list_user_id)) |
| 1284 | return |
| 1285 | status, message = gate_error |
| 1286 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1287 | return |
| 1288 | |
| 1289 | await _send_json(send, _list_objects_payload()) |
| 1290 | return |
| 1291 | |
| 1292 | if method == "POST": |
| 1293 | await _handle_objects_post(send, body, headers) |
| 1294 | return |
| 1295 | |
| 1296 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1297 | return |
| 1298 | |
| 1299 | if path == http_api_contract.COLLECTIONS_PATH: |
| 1300 | await _handle_collections(send, method, headers) |
| 1301 | return |
| 1302 | |
| 1303 | if path.startswith(f"{http_api_contract.COLLECTIONS_PATH}/"): |
| 1304 | collection_path = path.removeprefix(f"{http_api_contract.COLLECTIONS_PATH}/") |
| 1305 | collection_parts = collection_path.split("/") |
| 1306 | if len(collection_parts) == 2 and collection_parts[1] == "changes": |
| 1307 | await _handle_collection_changes( |
| 1308 | send, |
| 1309 | method, |
| 1310 | collection_parts[0], |
| 1311 | query, |
| 1312 | headers, |
| 1313 | ) |
| 1314 | return |
| 1315 | |
| 1316 | if len(collection_parts) == 2 and collection_parts[1] == "records": |
| 1317 | await _handle_collection_records( |
| 1318 | send, |
| 1319 | method, |
| 1320 | collection_parts[0], |
| 1321 | query, |
| 1322 | body, |
| 1323 | headers, |
| 1324 | ) |
| 1325 | return |
| 1326 | |
| 1327 | if ( |
| 1328 | len(collection_parts) == 4 |
| 1329 | and collection_parts[1] == "records" |
| 1330 | and collection_parts[3] == "changes" |
| 1331 | ): |
| 1332 | await _handle_collection_record_changes( |
| 1333 | send, |
| 1334 | method, |
| 1335 | collection_parts[0], |
| 1336 | collection_parts[2], |
| 1337 | query, |
| 1338 | headers, |
| 1339 | ) |
| 1340 | return |
| 1341 | |
| 1342 | if len(collection_parts) == 3 and collection_parts[1] == "records": |
| 1343 | await _handle_collection_record( |
| 1344 | send, |
| 1345 | method, |
| 1346 | collection_parts[0], |
| 1347 | collection_parts[2], |
| 1348 | body, |
| 1349 | headers, |
| 1350 | ) |
| 1351 | return |
| 1352 | |
| 1353 | collection = collection_path |
| 1354 | await _handle_collection_get(send, method, collection, headers) |
| 1355 | return |
| 1356 | |
| 1357 | if path == http_api_contract.SCHEMAS_PATH: |
| 1358 | await _handle_schemas(send, method, headers) |
| 1359 | return |
| 1360 | |
| 1361 | if path.startswith(f"{http_api_contract.SCHEMAS_PATH}/"): |
| 1362 | schema = path.removeprefix(f"{http_api_contract.SCHEMAS_PATH}/") |
| 1363 | await _handle_schema(send, method, schema, query, body, headers) |
| 1364 | return |
| 1365 | |
| 1366 | if path.startswith(f"{http_api_contract.OBJECTS_PATH}/"): |
| 1367 | object_id = path.removeprefix(f"{http_api_contract.OBJECTS_PATH}/") |
| 1368 | if _foreign_user_object(object_id, headers): |
| 1369 | await _send_foreign_user_object_not_found(send, object_id) |
| 1370 | return |
| 1371 | if method == "GET": |
| 1372 | await _handle_object_get(send, object_id, query, headers) |
| 1373 | return |
| 1374 | |
| 1375 | if method == "POST": |
| 1376 | await _handle_object_post(send, object_id, body, query, headers) |
| 1377 | return |
| 1378 | |
| 1379 | if method == "PUT" and query.get("source") == "true": |
| 1380 | await _handle_object_source_put(send, object_id, body, headers) |
| 1381 | return |
| 1382 | |
| 1383 | if method == "PUT": |
| 1384 | await _handle_object_body_method(send, object_id, "PUT", body, query, headers) |
| 1385 | return |
| 1386 | |
| 1387 | if method == "DELETE" and query.get("destroy") == "true": |
| 1388 | await _handle_object_destroy(send, object_id, headers) |
| 1389 | return |
| 1390 | |
| 1391 | if method == "DELETE": |
| 1392 | await _handle_object_body_method(send, object_id, "DELETE", body, query, headers) |
| 1393 | return |
| 1394 | |
| 1395 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1396 | return |
| 1397 | |
| 1398 | if await _handle_site_route(send, method, path, query, body, headers): |
| 1399 | return |
| 1400 | |
| 1401 | await _send_json(send, {"status": "error", "error": "Not found"}, status=404) |
| 1402 | finally: |
| 1403 | request_token.release() |
| 1404 | |
| 1405 | |
| 1406 | async def _handle_site_route( |
| 1407 | send, |
| 1408 | method: str, |
| 1409 | path: str, |
| 1410 | query: dict[str, str], |
| 1411 | body: bytes, |
| 1412 | headers: dict[str, str], |
| 1413 | ) -> bool: |
| 1414 | """Serve clean public URLs by resolving them to objects. |
| 1415 | |
| 1416 | Runs only after every built-in route family has declined the path, so |
| 1417 | reserved surfaces can never be shadowed. Resolution order: convention |
| 1418 | (`/about` -> `site_about`), then `site_routes` records patterns, then the |
| 1419 | `site_404` object. The resolved object executes through the normal |
| 1420 | execution path, so permission policy, audit, timeouts, and correlation |
| 1421 | ids all apply. Returns False when site routing is disabled or nothing |
| 1422 | resolves, leaving the plain JSON 404. |
| 1423 | """ |
| 1424 | if not _env_enabled(SITE_ROUTES_ENV): |
| 1425 | return False |
| 1426 | |
| 1427 | if method not in {"GET", "POST", "PUT", "DELETE"}: |
| 1428 | return False |
| 1429 | |
| 1430 | site = object_site_routes.resolve_host(headers.get("host"), _site_host_records()) |
| 1431 | params: dict[str, str] = {} |
| 1432 | target_id = object_site_routes.convention_object_id( |
| 1433 | path, |
| 1434 | prefix=site["prefix"], |
| 1435 | home=site["home"], |
| 1436 | ) |
| 1437 | if target_id is None or resolve_object_id(target_id, get_object_roots()) is None: |
| 1438 | match = object_site_routes.match_records( |
| 1439 | path, |
| 1440 | _site_route_records(), |
| 1441 | host=site["host"], |
| 1442 | ) |
| 1443 | if match is not None: |
| 1444 | target_id, params = match |
| 1445 | elif resolve_object_id(site["not_found"], get_object_roots()) is not None: |
| 1446 | target_id = site["not_found"] |
| 1447 | params = {"path": path} |
| 1448 | elif ( |
| 1449 | site["not_found"] != object_site_routes.NOT_FOUND_OBJECT_ID |
| 1450 | and resolve_object_id(object_site_routes.NOT_FOUND_OBJECT_ID, get_object_roots()) |
| 1451 | is not None |
| 1452 | ): |
| 1453 | target_id = object_site_routes.NOT_FOUND_OBJECT_ID |
| 1454 | params = {"path": path} |
| 1455 | else: |
| 1456 | return False |
| 1457 | |
| 1458 | try: |
| 1459 | if method == "GET": |
| 1460 | payload: dict[str, Any] = dict(query) |
| 1461 | else: |
| 1462 | payload = _parse_post_payload(body, query, headers) |
| 1463 | except ValueError as exc: |
| 1464 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1465 | return True |
| 1466 | |
| 1467 | payload.update(params) |
| 1468 | # The raw matched path, so a routed object can resolve a capture-LESS |
| 1469 | # route (an index/list view like /entities, whose views.route has no |
| 1470 | # {param}) -- route captures alone can only identify detail views. A |
| 1471 | # reserved, underscore-prefixed key (like _identity); objects that don't |
| 1472 | # need it ignore it. See view_render._resolve_view_and_record. |
| 1473 | payload["_path"] = path |
| 1474 | # App cookies, minus the identity session -- see _object_visible_cookies. |
| 1475 | # Without this a public page has no way to recognise a returning visitor: |
| 1476 | # the shop minted a new basket on every GET because the `cart` cookie the |
| 1477 | # browser was faithfully sending never reached the object. |
| 1478 | payload["_cookies"] = _object_visible_cookies(headers) |
| 1479 | |
| 1480 | permission_action = object_permissions.EXECUTE |
| 1481 | if method == "PUT": |
| 1482 | permission_action = object_permissions.UPDATE |
| 1483 | elif method == "DELETE": |
| 1484 | permission_action = object_permissions.DELETE |
| 1485 | |
| 1486 | await _execute_object_method( |
| 1487 | send, |
| 1488 | target_id, |
| 1489 | method, |
| 1490 | payload, |
| 1491 | headers, |
| 1492 | permission_action=permission_action, |
| 1493 | ) |
| 1494 | return True |
| 1495 | |
| 1496 | |
| 1497 | def _site_route_records() -> list[dict[str, Any]]: |
| 1498 | try: |
| 1499 | return object_records.read_collection_records( |
| 1500 | object_site_routes.SITE_ROUTES_COLLECTION, |
| 1501 | base_dir=_data_dir(), |
| 1502 | ) |
| 1503 | except (ValueError, LookupError, OSError): |
| 1504 | return [] |
| 1505 | |
| 1506 | |
| 1507 | def _site_host_records() -> list[dict[str, Any]]: |
| 1508 | try: |
| 1509 | return object_records.read_collection_records( |
| 1510 | object_site_routes.SITE_HOSTS_COLLECTION, |
| 1511 | base_dir=_data_dir(), |
| 1512 | ) |
| 1513 | except (ValueError, LookupError, OSError): |
| 1514 | return [] |
| 1515 | |
| 1516 | |
| 1517 | async def _handle_health( |
| 1518 | send, |
| 1519 | query: dict[str, str], |
| 1520 | headers: dict[str, str], |
| 1521 | ) -> None: |
| 1522 | if not _is_detailed_health(query): |
| 1523 | await _send_json(send, {"status": "ok", **_installed_facts()}) |
| 1524 | return |
| 1525 | |
| 1526 | gate_error = _admin_token_gate_error( |
| 1527 | headers, |
| 1528 | f"Health capacity requires {ADMIN_TOKEN_ENV}.", |
| 1529 | ) |
| 1530 | if gate_error is not None: |
| 1531 | status, message = gate_error |
| 1532 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1533 | return |
| 1534 | |
| 1535 | payload = _health_payload(include_metrics=query.get("metrics") == "true") |
| 1536 | if query.get("metrics") == "true" and query.get("history") == "true": |
| 1537 | try: |
| 1538 | payload["history"] = object_metrics_history.read_history( |
| 1539 | base_dir=_data_dir(), |
| 1540 | limit=_query_int(query, "history_limit", default=360, minimum=1, maximum=2000), |
| 1541 | ) |
| 1542 | except (OSError, ValueError): |
| 1543 | payload["history"] = [] |
| 1544 | status_code = 503 if payload["status"] == "degraded" else 200 |
| 1545 | await _send_json(send, payload, status=status_code) |
| 1546 | |
| 1547 | |
| 1548 | def _is_detailed_health(query: dict[str, str]) -> bool: |
| 1549 | return query.get("capacity") == "true" or query.get("metrics") == "true" |
| 1550 | |
| 1551 | |
| 1552 | async def _handle_identity(send, method: str, headers: dict[str, str]) -> None: |
| 1553 | if method != "GET": |
| 1554 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1555 | return |
| 1556 | |
| 1557 | subject, auth_method = _permission_identity(headers) |
| 1558 | await _send_json( |
| 1559 | send, |
| 1560 | { |
| 1561 | "status": "ok", |
| 1562 | "subject": _permission_subject_payload(subject), |
| 1563 | "auth": { |
| 1564 | "method": auth_method, |
| 1565 | "trusted_headers_enabled": _env_enabled(PERMISSION_TRUST_HEADERS_ENV), |
| 1566 | "trusted_headers_present": _trusted_identity_headers_present(headers), |
| 1567 | }, |
| 1568 | "permissions": { |
| 1569 | "enforcement_enabled": _permission_enforcement_enabled(), |
| 1570 | "enforcement_requested": _permission_enforcement_requested(), |
| 1571 | "enforcement_blocked": _permission_enforcement_blocked(), |
| 1572 | "audit_enabled": _permission_audit_enabled(), |
| 1573 | "mode": _permission_mode(), |
| 1574 | }, |
| 1575 | }, |
| 1576 | ) |
| 1577 | |
| 1578 | |
| 1579 | async def _handle_identity_accounts( |
| 1580 | send, |
| 1581 | method: str, |
| 1582 | body: bytes, |
| 1583 | headers: dict[str, str], |
| 1584 | ) -> None: |
| 1585 | gate_error = _admin_token_gate_error(headers, f"Identity accounts require {ADMIN_TOKEN_ENV}.") |
| 1586 | if gate_error is not None: |
| 1587 | status, message = gate_error |
| 1588 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1589 | return |
| 1590 | |
| 1591 | if method == "GET": |
| 1592 | try: |
| 1593 | accounts = object_identity.list_accounts(base_dir=_data_dir()) |
| 1594 | except OSError as exc: |
| 1595 | await _send_identity_store_error(send, exc, headers) |
| 1596 | return |
| 1597 | await _send_json( |
| 1598 | send, |
| 1599 | { |
| 1600 | "status": "ok", |
| 1601 | "accounts": accounts, |
| 1602 | "count": len(accounts), |
| 1603 | }, |
| 1604 | ) |
| 1605 | return |
| 1606 | |
| 1607 | if method == "POST": |
| 1608 | try: |
| 1609 | payload = _parse_json_body(body) |
| 1610 | account = object_identity.create_account(payload, base_dir=_data_dir()) |
| 1611 | except ValueError as exc: |
| 1612 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1613 | return |
| 1614 | |
| 1615 | await _send_json(send, {"status": "ok", "account": account}, status=201) |
| 1616 | return |
| 1617 | |
| 1618 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1619 | |
| 1620 | |
| 1621 | async def _handle_identity_account( |
| 1622 | send, |
| 1623 | method: str, |
| 1624 | account_id: str, |
| 1625 | headers: dict[str, str], |
| 1626 | body: bytes = b"", |
| 1627 | ) -> None: |
| 1628 | gate_error = _admin_token_gate_error(headers, f"Identity accounts require {ADMIN_TOKEN_ENV}.") |
| 1629 | if gate_error is not None: |
| 1630 | status, message = gate_error |
| 1631 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1632 | return |
| 1633 | |
| 1634 | target_account_id, _, action = account_id.partition("/") |
| 1635 | if action == "status" and target_account_id: |
| 1636 | await _handle_identity_account_status(send, method, target_account_id, body, headers) |
| 1637 | return |
| 1638 | if action == "subscriptions" and target_account_id: |
| 1639 | await _handle_identity_account_subscriptions(send, method, target_account_id, body, headers) |
| 1640 | return |
| 1641 | |
| 1642 | if "/" in account_id or not account_id: |
| 1643 | await _send_json(send, {"status": "error", "error": "Invalid account id"}, status=400) |
| 1644 | return |
| 1645 | |
| 1646 | if method != "GET": |
| 1647 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1648 | return |
| 1649 | |
| 1650 | try: |
| 1651 | account = object_identity.get_account(account_id, base_dir=_data_dir()) |
| 1652 | except object_identity.InvalidIdentityPayloadError as exc: |
| 1653 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1654 | return |
| 1655 | except object_identity.AccountNotFoundError as exc: |
| 1656 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 1657 | return |
| 1658 | |
| 1659 | await _send_json(send, {"status": "ok", "account": account}) |
| 1660 | |
| 1661 | |
| 1662 | async def _handle_identity_account_status( |
| 1663 | send, |
| 1664 | method: str, |
| 1665 | account_id: str, |
| 1666 | body: bytes, |
| 1667 | headers: dict[str, str], |
| 1668 | ) -> None: |
| 1669 | """Disable or re-enable one account (object_identity.set_account_status). |
| 1670 | |
| 1671 | The caller has already passed the admin gate (_handle_identity_account). |
| 1672 | Shaped like the user status route: POST or PUT {"status": ...}, unknown |
| 1673 | fields refused, one ops `auth` line naming the account and the actor. If |
| 1674 | the account is disabled but its users' sessions cannot be ended, the |
| 1675 | answer is a 500 that says so (and its own ops line), never "ok". |
| 1676 | """ |
| 1677 | if method not in {"POST", "PUT"}: |
| 1678 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1679 | return |
| 1680 | if "/" in account_id: |
| 1681 | await _send_json(send, {"status": "error", "error": "Invalid account id"}, status=400) |
| 1682 | return |
| 1683 | actor_session = _current_identity_session(headers) |
| 1684 | actor = actor_session.user_id if actor_session is not None else "admin_token" |
| 1685 | actor_method = "admin_session" if actor_session is not None else "admin_token" |
| 1686 | try: |
| 1687 | payload = _parse_json_body(body) |
| 1688 | unsupported = sorted(set(payload) - {"status"}) |
| 1689 | if unsupported: |
| 1690 | raise object_identity.InvalidIdentityPayloadError( |
| 1691 | f"Unsupported fields: {', '.join(unsupported)}" |
| 1692 | ) |
| 1693 | result = object_identity.set_account_status( |
| 1694 | account_id, payload.get("status"), base_dir=_data_dir() |
| 1695 | ) |
| 1696 | except object_identity.AccountSessionsNotEndedError as exc: |
| 1697 | _append_ops_auth_event( |
| 1698 | "account_sessions_not_ended", |
| 1699 | identifier=exc.account_id, |
| 1700 | user_id=actor, |
| 1701 | method=actor_method, |
| 1702 | label="account disabled; ending its users' sessions failed", |
| 1703 | ) |
| 1704 | await _send_json( |
| 1705 | send, |
| 1706 | { |
| 1707 | "status": "error", |
| 1708 | "code": "account_sessions_not_ended", |
| 1709 | "error": str(exc), |
| 1710 | "account_id": exc.account_id, |
| 1711 | "account_disabled": True, |
| 1712 | }, |
| 1713 | status=500, |
| 1714 | ) |
| 1715 | return |
| 1716 | except object_identity.AccountNotFoundError as exc: |
| 1717 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 1718 | return |
| 1719 | except ValueError as exc: |
| 1720 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1721 | return |
| 1722 | except OSError as exc: |
| 1723 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 1724 | return |
| 1725 | |
| 1726 | _append_ops_auth_event( |
| 1727 | "account_status_set", |
| 1728 | identifier=result["account"]["account_id"], |
| 1729 | user_id=actor, |
| 1730 | method=actor_method, |
| 1731 | label=f"status={result['account']['status']} sessions_revoked={result['sessions_revoked']}", |
| 1732 | ) |
| 1733 | await _send_json(send, {"status": "ok", **result}) |
| 1734 | |
| 1735 | |
| 1736 | async def _handle_identity_account_subscriptions( |
| 1737 | send, |
| 1738 | method: str, |
| 1739 | account_id: str, |
| 1740 | body: bytes, |
| 1741 | headers: dict[str, str], |
| 1742 | ) -> None: |
| 1743 | """Replace one account's subscriptions (object_identity.set_account_subscriptions). |
| 1744 | |
| 1745 | The caller has already passed the admin gate (_handle_identity_account), |
| 1746 | the same gate as the status route. POST or PUT {"subscriptions": [...]}, |
| 1747 | the whole list; unknown fields refused. The function writes the |
| 1748 | account_subscriptions_set ops line (actor, before, after) itself. |
| 1749 | """ |
| 1750 | if method not in {"POST", "PUT"}: |
| 1751 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1752 | return |
| 1753 | if "/" in account_id: |
| 1754 | await _send_json(send, {"status": "error", "error": "Invalid account id"}, status=400) |
| 1755 | return |
| 1756 | actor_session = _current_identity_session(headers) |
| 1757 | actor = actor_session.user_id if actor_session is not None else "admin_token" |
| 1758 | actor_method = "admin_session" if actor_session is not None else "admin_token" |
| 1759 | try: |
| 1760 | payload = _parse_json_body(body) |
| 1761 | unsupported = sorted(set(payload) - {"subscriptions"}) |
| 1762 | if unsupported: |
| 1763 | raise object_identity.InvalidIdentityPayloadError( |
| 1764 | f"Unsupported fields: {', '.join(unsupported)}" |
| 1765 | ) |
| 1766 | if "subscriptions" not in payload: |
| 1767 | raise object_identity.InvalidIdentityPayloadError("subscriptions is required") |
| 1768 | result = object_identity.set_account_subscriptions( |
| 1769 | account_id, |
| 1770 | payload["subscriptions"], |
| 1771 | actor=actor, |
| 1772 | actor_method=actor_method, |
| 1773 | base_dir=_data_dir(), |
| 1774 | ) |
| 1775 | except object_identity.AccountNotFoundError as exc: |
| 1776 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 1777 | return |
| 1778 | except ValueError as exc: |
| 1779 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1780 | return |
| 1781 | except OSError as exc: |
| 1782 | await _send_identity_store_error(send, exc, headers) |
| 1783 | return |
| 1784 | await _send_json(send, {"status": "ok", **result}) |
| 1785 | |
| 1786 | |
| 1787 | async def _handle_identity_users( |
| 1788 | send, |
| 1789 | method: str, |
| 1790 | query: dict[str, str], |
| 1791 | body: bytes, |
| 1792 | headers: dict[str, str], |
| 1793 | ) -> None: |
| 1794 | gate_error = _admin_token_gate_error(headers, f"Identity users require {ADMIN_TOKEN_ENV}.") |
| 1795 | if gate_error is not None: |
| 1796 | status, message = gate_error |
| 1797 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1798 | return |
| 1799 | |
| 1800 | if method == "GET": |
| 1801 | try: |
| 1802 | users = object_identity.list_users( |
| 1803 | account_id=query.get("account_id"), |
| 1804 | base_dir=_data_dir(), |
| 1805 | ) |
| 1806 | except object_identity.InvalidIdentityPayloadError as exc: |
| 1807 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1808 | return |
| 1809 | except OSError as exc: |
| 1810 | await _send_identity_store_error(send, exc, headers) |
| 1811 | return |
| 1812 | |
| 1813 | await _send_json( |
| 1814 | send, |
| 1815 | { |
| 1816 | "status": "ok", |
| 1817 | "users": users, |
| 1818 | "count": len(users), |
| 1819 | }, |
| 1820 | ) |
| 1821 | return |
| 1822 | |
| 1823 | if method == "POST": |
| 1824 | try: |
| 1825 | payload = _parse_json_body(body) |
| 1826 | user = object_identity.create_user(payload, base_dir=_data_dir()) |
| 1827 | except object_identity.AccountNotFoundError as exc: |
| 1828 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 1829 | return |
| 1830 | except ValueError as exc: |
| 1831 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1832 | return |
| 1833 | except OSError as exc: |
| 1834 | # create_user reads credentials, sessions and API keys for leftovers under the new id |
| 1835 | await _send_identity_store_error(send, exc, headers) |
| 1836 | return |
| 1837 | |
| 1838 | await _send_json(send, {"status": "ok", "user": user}, status=201) |
| 1839 | return |
| 1840 | |
| 1841 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1842 | |
| 1843 | |
| 1844 | def _service_keys_route_parts(user_id: str) -> tuple[str | None, str | None]: |
| 1845 | """Split '{user}/service-keys[/{service}]' route tails; (None, None) otherwise.""" |
| 1846 | if "/service-keys" not in user_id: |
| 1847 | return None, None |
| 1848 | target, _, tail = user_id.partition("/service-keys") |
| 1849 | if "/" in target or not target: |
| 1850 | return None, None |
| 1851 | if tail == "": |
| 1852 | return target, None |
| 1853 | if tail.startswith("/") and tail.count("/") == 1 and len(tail) > 1: |
| 1854 | return target, tail[1:] |
| 1855 | return None, None |
| 1856 | |
| 1857 | |
| 1858 | def _api_keys_route_parts(user_id: str) -> tuple[str | None, str | None]: |
| 1859 | """Split '{user}/api-keys[/{key_id}]' route tails; (None, None) otherwise.""" |
| 1860 | if "/api-keys" not in user_id: |
| 1861 | return None, None |
| 1862 | target, _, tail = user_id.partition("/api-keys") |
| 1863 | if "/" in target or not target: |
| 1864 | return None, None |
| 1865 | if tail == "": |
| 1866 | return target, None |
| 1867 | if tail.startswith("/") and tail.count("/") == 1 and len(tail) > 1: |
| 1868 | return target, tail[1:] |
| 1869 | return None, None |
| 1870 | |
| 1871 | |
| 1872 | async def _handle_identity_user_api_keys( |
| 1873 | send, |
| 1874 | method: str, |
| 1875 | user_id: str, |
| 1876 | key_id: str | None, |
| 1877 | body: bytes, |
| 1878 | headers: dict[str, str], |
| 1879 | ) -> None: |
| 1880 | """Self-service per-user API keys: create (raw token returned ONCE), list |
| 1881 | status, revoke. The token never appears again -- only its hash is stored. |
| 1882 | A signed-in user manages their own; the admin gate covers operator use.""" |
| 1883 | session = _current_identity_session(headers) |
| 1884 | self_service = session is not None and session.user_id == user_id |
| 1885 | if not self_service: |
| 1886 | gate_error = _admin_token_gate_error( |
| 1887 | headers, "API keys require the account owner's session or the admin gate." |
| 1888 | ) |
| 1889 | if gate_error is not None: |
| 1890 | status, message = gate_error |
| 1891 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1892 | return |
| 1893 | |
| 1894 | # A cross-origin request that carries only the session cookie never gets |
| 1895 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 1896 | # request rejected") before any handler runs. |
| 1897 | |
| 1898 | if method == "GET" and key_id is None: |
| 1899 | try: |
| 1900 | keys = object_api_keys.list_api_keys(user_id, base_dir=_data_dir()) |
| 1901 | except object_api_keys.InvalidApiKeyError as exc: |
| 1902 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1903 | return |
| 1904 | except OSError as exc: |
| 1905 | await _send_identity_store_error(send, exc, headers) |
| 1906 | return |
| 1907 | await _send_json(send, {"status": "ok", "user_id": user_id, "keys": keys}) |
| 1908 | return |
| 1909 | |
| 1910 | if method in {"POST", "PUT"} and key_id is None: |
| 1911 | try: |
| 1912 | payload = _parse_json_body(body) |
| 1913 | except ValueError as exc: |
| 1914 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1915 | return |
| 1916 | try: |
| 1917 | meta, raw_token = object_api_keys.create_api_key( |
| 1918 | user_id, |
| 1919 | payload.get("name"), |
| 1920 | base_dir=_data_dir(), |
| 1921 | require_known_user=_env_enabled(REQUIRE_KNOWN_IDENTITY_USERS_ENV), |
| 1922 | ) |
| 1923 | except object_identity.UserNotFoundError as exc: |
| 1924 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 1925 | return |
| 1926 | except object_api_keys.InvalidApiKeyError as exc: |
| 1927 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1928 | return |
| 1929 | except object_identity.AccountUnusableError as exc: |
| 1930 | _log_account_unusable(exc, "api_key_mint") |
| 1931 | await _send_account_unusable(send, headers, exc) |
| 1932 | return |
| 1933 | _append_ops_auth_event(event="api_key_created", identifier=user_id, label=meta["key_id"]) |
| 1934 | # The ONLY time the raw token is ever returned. |
| 1935 | await _send_json(send, {"status": "ok", "token": raw_token, **meta}) |
| 1936 | return |
| 1937 | |
| 1938 | if method == "DELETE" and key_id is not None: |
| 1939 | try: |
| 1940 | deleted = object_api_keys.revoke_api_key(user_id, key_id, base_dir=_data_dir()) |
| 1941 | except object_api_keys.InvalidApiKeyError as exc: |
| 1942 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1943 | return |
| 1944 | if not deleted: |
| 1945 | await _send_json(send, {"status": "error", "error": "No such API key"}, status=404) |
| 1946 | return |
| 1947 | _append_ops_auth_event(event="api_key_revoked", identifier=user_id, label=key_id) |
| 1948 | await _send_json(send, {"status": "ok", "deleted": True, "key_id": key_id}) |
| 1949 | return |
| 1950 | |
| 1951 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 1952 | |
| 1953 | |
| 1954 | async def _handle_identity_user_service_keys( |
| 1955 | send, |
| 1956 | method: str, |
| 1957 | user_id: str, |
| 1958 | service: str | None, |
| 1959 | body: bytes, |
| 1960 | headers: dict[str, str], |
| 1961 | ) -> None: |
| 1962 | """Write-only per-user service keys: set, list status, delete — never read. |
| 1963 | |
| 1964 | A signed-in user manages their own keys; the admin gate covers operator |
| 1965 | use. Key material never appears in any response. |
| 1966 | """ |
| 1967 | session = _current_identity_session(headers) |
| 1968 | self_service = session is not None and session.user_id == user_id |
| 1969 | if not self_service: |
| 1970 | gate_error = _admin_token_gate_error( |
| 1971 | headers, "Service keys require the account owner's session or the admin gate." |
| 1972 | ) |
| 1973 | if gate_error is not None: |
| 1974 | status, message = gate_error |
| 1975 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 1976 | return |
| 1977 | |
| 1978 | # A cross-origin request that carries only the session cookie never gets |
| 1979 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 1980 | # request rejected") before any handler runs. |
| 1981 | |
| 1982 | if method == "GET" and service is None: |
| 1983 | try: |
| 1984 | statuses = object_service_keys.list_service_key_status( |
| 1985 | user_id, base_dir=_data_dir() |
| 1986 | ) |
| 1987 | except object_service_keys.InvalidServiceKeyError as exc: |
| 1988 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1989 | return |
| 1990 | await _send_json(send, {"status": "ok", "user_id": user_id, "services": statuses}) |
| 1991 | return |
| 1992 | |
| 1993 | if method in {"PUT", "POST"} and service is None: |
| 1994 | try: |
| 1995 | payload = _parse_json_body(body) |
| 1996 | except ValueError as exc: |
| 1997 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 1998 | return |
| 1999 | if object_service_keys.is_reserved_service(payload.get("service")): |
| 2000 | await _send_json( |
| 2001 | send, |
| 2002 | {"status": "error", "error": "That service name is reserved for platform-owned secrets."}, |
| 2003 | status=403, |
| 2004 | ) |
| 2005 | return |
| 2006 | try: |
| 2007 | result = object_service_keys.set_service_key( |
| 2008 | user_id, |
| 2009 | payload.get("service"), |
| 2010 | payload.get("key"), |
| 2011 | base_dir=_data_dir(), |
| 2012 | ) |
| 2013 | except object_service_keys.InvalidServiceKeyError as exc: |
| 2014 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2015 | return |
| 2016 | _append_ops_auth_event( |
| 2017 | event="service_key_set", |
| 2018 | identifier=user_id, |
| 2019 | label=result["service"], |
| 2020 | ) |
| 2021 | await _send_json(send, {"status": "ok", **result}) |
| 2022 | return |
| 2023 | |
| 2024 | if method == "DELETE" and service is not None: |
| 2025 | if object_service_keys.is_reserved_service(service): |
| 2026 | await _send_json( |
| 2027 | send, |
| 2028 | {"status": "error", "error": "That service name is reserved for platform-owned secrets."}, |
| 2029 | status=403, |
| 2030 | ) |
| 2031 | return |
| 2032 | try: |
| 2033 | deleted = object_service_keys.remove_service_key( |
| 2034 | user_id, service, base_dir=_data_dir() |
| 2035 | ) |
| 2036 | except object_service_keys.InvalidServiceKeyError as exc: |
| 2037 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2038 | return |
| 2039 | if not deleted: |
| 2040 | await _send_json( |
| 2041 | send, {"status": "error", "error": "No key stored for that service"}, status=404 |
| 2042 | ) |
| 2043 | return |
| 2044 | _append_ops_auth_event( |
| 2045 | event="service_key_removed", |
| 2046 | identifier=user_id, |
| 2047 | label=service, |
| 2048 | ) |
| 2049 | await _send_json(send, {"status": "ok", "deleted": True, "service": service}) |
| 2050 | return |
| 2051 | |
| 2052 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2053 | |
| 2054 | |
| 2055 | async def _handle_identity_user( |
| 2056 | send, |
| 2057 | method: str, |
| 2058 | user_id: str, |
| 2059 | body: bytes, |
| 2060 | headers: dict[str, str], |
| 2061 | ) -> None: |
| 2062 | service_keys_target, service_name = _service_keys_route_parts(user_id) |
| 2063 | if service_keys_target is not None: |
| 2064 | await _handle_identity_user_service_keys( |
| 2065 | send, method, service_keys_target, service_name, body, headers |
| 2066 | ) |
| 2067 | return |
| 2068 | |
| 2069 | api_keys_target, api_key_id = _api_keys_route_parts(user_id) |
| 2070 | if api_keys_target is not None: |
| 2071 | await _handle_identity_user_api_keys( |
| 2072 | send, method, api_keys_target, api_key_id, body, headers |
| 2073 | ) |
| 2074 | return |
| 2075 | |
| 2076 | gate_error = _admin_token_gate_error(headers, f"Identity users require {ADMIN_TOKEN_ENV}.") |
| 2077 | if gate_error is not None: |
| 2078 | status, message = gate_error |
| 2079 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 2080 | return |
| 2081 | |
| 2082 | if user_id.endswith("/password"): |
| 2083 | target_user_id = user_id.removesuffix("/password") |
| 2084 | if "/" in target_user_id or not target_user_id: |
| 2085 | await _send_json(send, {"status": "error", "error": "Invalid user id"}, status=400) |
| 2086 | return |
| 2087 | await _handle_identity_user_password(send, method, target_user_id, body, headers) |
| 2088 | return |
| 2089 | |
| 2090 | target_user_id, _, action = user_id.partition("/") |
| 2091 | if action in IDENTITY_USER_ADMIN_ACTIONS and target_user_id: |
| 2092 | await _handle_identity_user_admin_action(send, method, target_user_id, action, body, headers) |
| 2093 | return |
| 2094 | |
| 2095 | if "/" in user_id or not user_id: |
| 2096 | await _send_json(send, {"status": "error", "error": "Invalid user id"}, status=400) |
| 2097 | return |
| 2098 | |
| 2099 | if method != "GET": |
| 2100 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2101 | return |
| 2102 | |
| 2103 | try: |
| 2104 | user = object_identity.get_user(user_id, base_dir=_data_dir()) |
| 2105 | except object_identity.InvalidIdentityPayloadError as exc: |
| 2106 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2107 | return |
| 2108 | except object_identity.UserNotFoundError as exc: |
| 2109 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2110 | return |
| 2111 | except OSError as exc: |
| 2112 | await _send_identity_store_error(send, exc, headers) |
| 2113 | return |
| 2114 | |
| 2115 | await _send_json(send, {"status": "ok", "user": user}) |
| 2116 | |
| 2117 | |
| 2118 | IDENTITY_USER_ADMIN_ACTIONS = frozenset({"status", "roles", "offboard"}) |
| 2119 | _IDENTITY_USER_ACTION_FIELDS = { |
| 2120 | "status": {"status"}, |
| 2121 | "roles": {"roles"}, |
| 2122 | "offboard": {"clear_roles", "reason"}, |
| 2123 | } |
| 2124 | |
| 2125 | |
| 2126 | async def _handle_identity_user_admin_action( |
| 2127 | send, |
| 2128 | method: str, |
| 2129 | user_id: str, |
| 2130 | action: str, |
| 2131 | body: bytes, |
| 2132 | headers: dict[str, str], |
| 2133 | ) -> None: |
| 2134 | """Admin writes to one user: set status, set roles, offboard. |
| 2135 | |
| 2136 | The caller has already passed the admin gate (_handle_identity_user). |
| 2137 | These exist because there was no supported way to take access away: a |
| 2138 | tester offboarding someone had to edit users.tsv in-process, and the |
| 2139 | status they set did not even stop the user's keys (object_identity |
| 2140 | change_user_status). Each writes one ops `auth` line naming the target, |
| 2141 | the actor and what was revoked, so "who removed Bob, and when" has an |
| 2142 | answer in GET /admin/ops?kind=auth. |
| 2143 | |
| 2144 | Unknown body fields are refused rather than ignored: `{"role": [...]}` |
| 2145 | silently doing nothing is how an offboarding is believed done and is not. |
| 2146 | """ |
| 2147 | if method not in {"POST", "PUT"}: |
| 2148 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2149 | return |
| 2150 | if "/" in user_id: |
| 2151 | await _send_json(send, {"status": "error", "error": "Invalid user id"}, status=400) |
| 2152 | return |
| 2153 | try: |
| 2154 | payload = _parse_json_body(body) |
| 2155 | unsupported = sorted(set(payload) - _IDENTITY_USER_ACTION_FIELDS[action]) |
| 2156 | if unsupported: |
| 2157 | raise object_identity.InvalidIdentityPayloadError( |
| 2158 | f"Unsupported fields: {', '.join(unsupported)}" |
| 2159 | ) |
| 2160 | if action == "status": |
| 2161 | result = object_identity.change_user_status( |
| 2162 | user_id, payload.get("status"), base_dir=_data_dir() |
| 2163 | ) |
| 2164 | detail = f"status={result['user']['status']}" |
| 2165 | elif action == "roles": |
| 2166 | if "roles" not in payload: |
| 2167 | raise object_identity.InvalidIdentityPayloadError("roles is required") |
| 2168 | result = object_identity.set_user_roles( |
| 2169 | user_id, payload.get("roles"), base_dir=_data_dir() |
| 2170 | ) |
| 2171 | detail = f"roles={','.join(result['user']['roles'])}" |
| 2172 | else: |
| 2173 | clear_roles = payload.get("clear_roles", False) |
| 2174 | if not isinstance(clear_roles, bool): |
| 2175 | raise object_identity.InvalidIdentityPayloadError("clear_roles must be true or false") |
| 2176 | reason = payload.get("reason") |
| 2177 | if reason is not None and not isinstance(reason, str): |
| 2178 | raise object_identity.InvalidIdentityPayloadError("reason must be a string") |
| 2179 | result = object_identity.offboard_user( |
| 2180 | user_id, clear_roles=clear_roles, base_dir=_data_dir() |
| 2181 | ) |
| 2182 | detail = "status=disabled" |
| 2183 | if result["roles_cleared"]: |
| 2184 | detail += f" roles_cleared={','.join(result['roles_cleared'])}" |
| 2185 | if reason and reason.strip(): |
| 2186 | detail += f" reason={' '.join(reason.split())[:200]}" |
| 2187 | except object_identity.UserNotFoundError as exc: |
| 2188 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2189 | return |
| 2190 | except (ValueError, OSError) as exc: |
| 2191 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2192 | return |
| 2193 | |
| 2194 | actor_session = _current_identity_session(headers) |
| 2195 | actor = actor_session.user_id if actor_session is not None else "admin_token" |
| 2196 | counts = f"sessions_revoked={result.get('sessions_revoked', 0)}" |
| 2197 | if "api_keys_revoked" in result: |
| 2198 | counts += f" api_keys_revoked={result['api_keys_revoked']}" |
| 2199 | _append_ops_auth_event( |
| 2200 | event={"status": "user_status_set", "roles": "user_roles_set", "offboard": "user_offboarded"}[action], |
| 2201 | identifier=result["user"]["user_id"], |
| 2202 | user_id=actor, |
| 2203 | method="admin_session" if actor_session is not None else "admin_token", |
| 2204 | label=f"{detail} {counts}", |
| 2205 | ) |
| 2206 | await _send_json(send, {"status": "ok", **result}) |
| 2207 | |
| 2208 | |
| 2209 | async def _handle_identity_user_password( |
| 2210 | send, |
| 2211 | method: str, |
| 2212 | user_id: str, |
| 2213 | body: bytes, |
| 2214 | headers: dict[str, str], |
| 2215 | ) -> None: |
| 2216 | """Set (POST) or remove (DELETE) one user's password; admin only. |
| 2217 | |
| 2218 | Either ends the user's sessions (object_credentials does it, for every |
| 2219 | path that writes a password). The one exception: a signed-in admin |
| 2220 | changing their OWN password keeps the session the request came with, so |
| 2221 | the page they are on keeps working; every other session of theirs ends. |
| 2222 | With the admin token, or for another user, every session ends. API keys |
| 2223 | are not touched. If the password is written but the sessions cannot be |
| 2224 | ended the answer is a 500 saying exactly that, never "ok". |
| 2225 | """ |
| 2226 | actor_session = _current_identity_session(headers) |
| 2227 | actor = actor_session.user_id if actor_session is not None else "admin_token" |
| 2228 | try: |
| 2229 | user = object_identity.get_user(user_id, base_dir=_data_dir()) |
| 2230 | except object_identity.InvalidIdentityPayloadError as exc: |
| 2231 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2232 | return |
| 2233 | except object_identity.UserNotFoundError as exc: |
| 2234 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2235 | return |
| 2236 | |
| 2237 | if method == "POST": |
| 2238 | try: |
| 2239 | payload = _parse_json_body(body) |
| 2240 | password = payload.get("password") |
| 2241 | result = object_credentials.set_password( |
| 2242 | user["user_id"], |
| 2243 | password, |
| 2244 | base_dir=_data_dir(), |
| 2245 | keep_session_id=_own_session_id(actor_session, user["user_id"]), |
| 2246 | ) |
| 2247 | except object_credentials.SessionRevocationError as exc: |
| 2248 | await _send_password_sessions_not_ended(send, exc, user["user_id"], actor, "set") |
| 2249 | return |
| 2250 | except object_credentials.InvalidPasswordError as exc: |
| 2251 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2252 | return |
| 2253 | except ValueError as exc: |
| 2254 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2255 | return |
| 2256 | except OSError as exc: |
| 2257 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 2258 | return |
| 2259 | |
| 2260 | _append_ops_auth_event( |
| 2261 | "user_password_set", |
| 2262 | identifier=result["user_id"], |
| 2263 | user_id=actor, |
| 2264 | method="admin_session" if actor_session is not None else "admin_token", |
| 2265 | label=f"operation={result['operation']} sessions_revoked={result['sessions_revoked']}", |
| 2266 | ) |
| 2267 | await _send_json( |
| 2268 | send, |
| 2269 | { |
| 2270 | "status": "ok", |
| 2271 | "user_id": result["user_id"], |
| 2272 | "operation": result["operation"], |
| 2273 | "updated_at": result["updated_at"], |
| 2274 | "sessions_revoked": result["sessions_revoked"], |
| 2275 | }, |
| 2276 | ) |
| 2277 | return |
| 2278 | |
| 2279 | if method == "DELETE": |
| 2280 | try: |
| 2281 | removed = object_credentials.remove_password( |
| 2282 | user["user_id"], |
| 2283 | base_dir=_data_dir(), |
| 2284 | keep_session_id=_own_session_id(actor_session, user["user_id"]), |
| 2285 | ) |
| 2286 | except object_credentials.SessionRevocationError as exc: |
| 2287 | await _send_password_sessions_not_ended(send, exc, user["user_id"], actor, "removed") |
| 2288 | return |
| 2289 | except object_credentials.InvalidPasswordError as exc: |
| 2290 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2291 | return |
| 2292 | except OSError as exc: |
| 2293 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 2294 | return |
| 2295 | |
| 2296 | if removed: |
| 2297 | _append_ops_auth_event( |
| 2298 | "user_password_removed", |
| 2299 | identifier=user["user_id"], |
| 2300 | user_id=actor, |
| 2301 | method="admin_session" if actor_session is not None else "admin_token", |
| 2302 | ) |
| 2303 | await _send_json( |
| 2304 | send, |
| 2305 | { |
| 2306 | "status": "ok", |
| 2307 | "user_id": user["user_id"], |
| 2308 | "removed": removed, |
| 2309 | }, |
| 2310 | ) |
| 2311 | return |
| 2312 | |
| 2313 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2314 | |
| 2315 | |
| 2316 | def _own_session_id( |
| 2317 | actor_session: object_identity.IdentitySession | None, target_user_id: str |
| 2318 | ) -> str | None: |
| 2319 | """The caller's session id when they are changing their own password, else None.""" |
| 2320 | if actor_session is not None and actor_session.user_id == target_user_id: |
| 2321 | return actor_session.session_id |
| 2322 | return None |
| 2323 | |
| 2324 | |
| 2325 | async def _send_password_sessions_not_ended( |
| 2326 | send, exc: Exception, user_id: str, actor: str, operation: str |
| 2327 | ) -> None: |
| 2328 | _append_ops_auth_event( |
| 2329 | "user_password_sessions_not_ended", |
| 2330 | identifier=user_id, |
| 2331 | user_id=actor, |
| 2332 | label=f"password {operation}; revoking the user's sessions failed", |
| 2333 | ) |
| 2334 | await _send_json( |
| 2335 | send, |
| 2336 | { |
| 2337 | "status": "error", |
| 2338 | "code": "password_sessions_not_ended", |
| 2339 | "error": str(exc), |
| 2340 | "user_id": user_id, |
| 2341 | "password_changed": True, |
| 2342 | }, |
| 2343 | status=500, |
| 2344 | ) |
| 2345 | |
| 2346 | |
| 2347 | async def _handle_identity_sessions( |
| 2348 | send, |
| 2349 | method: str, |
| 2350 | body: bytes, |
| 2351 | headers: dict[str, str], |
| 2352 | ) -> None: |
| 2353 | gate_error = _admin_token_gate_error(headers, f"Identity sessions require {ADMIN_TOKEN_ENV}.") |
| 2354 | if gate_error is not None: |
| 2355 | status, message = gate_error |
| 2356 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 2357 | return |
| 2358 | |
| 2359 | if method == "GET": |
| 2360 | try: |
| 2361 | sessions = object_identity.list_sessions(base_dir=_data_dir()) |
| 2362 | except OSError as exc: |
| 2363 | await _send_identity_store_error(send, exc, headers) |
| 2364 | return |
| 2365 | await _send_json( |
| 2366 | send, |
| 2367 | { |
| 2368 | "status": "ok", |
| 2369 | "sessions": sessions, |
| 2370 | "count": len(sessions), |
| 2371 | }, |
| 2372 | ) |
| 2373 | return |
| 2374 | |
| 2375 | if method == "POST": |
| 2376 | try: |
| 2377 | payload = _parse_json_body(body) |
| 2378 | result = object_identity.create_session( |
| 2379 | payload, |
| 2380 | base_dir=_data_dir(), |
| 2381 | require_known_user=_env_enabled(REQUIRE_KNOWN_IDENTITY_USERS_ENV), |
| 2382 | ) |
| 2383 | except object_identity.UserNotFoundError as exc: |
| 2384 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2385 | return |
| 2386 | except object_identity.AccountNotFoundError as exc: |
| 2387 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2388 | return |
| 2389 | except object_identity.AccountUnusableError as exc: |
| 2390 | _log_account_unusable(exc, "admin_session_mint") |
| 2391 | await _send_account_unusable(send, headers, exc) |
| 2392 | return |
| 2393 | except ValueError as exc: |
| 2394 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2395 | return |
| 2396 | except OSError as exc: |
| 2397 | await _send_identity_store_error(send, exc, headers) |
| 2398 | return |
| 2399 | |
| 2400 | await _send_json(send, {"status": "ok", **result}, status=201) |
| 2401 | return |
| 2402 | |
| 2403 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2404 | |
| 2405 | |
| 2406 | async def _handle_identity_session( |
| 2407 | send, |
| 2408 | method: str, |
| 2409 | session_id: str, |
| 2410 | headers: dict[str, str], |
| 2411 | ) -> None: |
| 2412 | gate_error = _admin_token_gate_error(headers, f"Identity sessions require {ADMIN_TOKEN_ENV}.") |
| 2413 | if gate_error is not None: |
| 2414 | status, message = gate_error |
| 2415 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 2416 | return |
| 2417 | |
| 2418 | if "/" in session_id or not session_id: |
| 2419 | await _send_json(send, {"status": "error", "error": "Invalid session id"}, status=400) |
| 2420 | return |
| 2421 | |
| 2422 | if method == "GET": |
| 2423 | try: |
| 2424 | session = object_identity.get_session(session_id, base_dir=_data_dir()) |
| 2425 | except object_identity.InvalidSessionPayloadError as exc: |
| 2426 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2427 | return |
| 2428 | except object_identity.SessionNotFoundError as exc: |
| 2429 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2430 | return |
| 2431 | |
| 2432 | await _send_json(send, {"status": "ok", "session": session}) |
| 2433 | return |
| 2434 | |
| 2435 | if method == "DELETE": |
| 2436 | try: |
| 2437 | session = object_identity.revoke_session(session_id, base_dir=_data_dir()) |
| 2438 | except object_identity.InvalidSessionPayloadError as exc: |
| 2439 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2440 | return |
| 2441 | except object_identity.SessionNotFoundError as exc: |
| 2442 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2443 | return |
| 2444 | |
| 2445 | await _send_json(send, {"status": "ok", "session": session}) |
| 2446 | return |
| 2447 | |
| 2448 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2449 | |
| 2450 | |
| 2451 | async def _handle_identity_current_session( |
| 2452 | send, |
| 2453 | method: str, |
| 2454 | body: bytes, |
| 2455 | headers: dict[str, str], |
| 2456 | ) -> None: |
| 2457 | if method not in {"GET", "POST", "DELETE"}: |
| 2458 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2459 | return |
| 2460 | |
| 2461 | if method == "POST": |
| 2462 | try: |
| 2463 | peeked_payload = _parse_json_body(body) |
| 2464 | except ValueError: |
| 2465 | peeked_payload = None |
| 2466 | if isinstance(peeked_payload, dict) and "password" in peeked_payload: |
| 2467 | await _handle_identity_password_login(send, peeked_payload) |
| 2468 | return |
| 2469 | |
| 2470 | gate_error = _session_login_gate_error(headers) |
| 2471 | if gate_error is not None: |
| 2472 | status, message = gate_error |
| 2473 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 2474 | return |
| 2475 | |
| 2476 | try: |
| 2477 | payload = _parse_json_body(body) |
| 2478 | result = object_identity.create_session( |
| 2479 | _identity_session_login_payload(payload), |
| 2480 | base_dir=_data_dir(), |
| 2481 | require_known_user=True, |
| 2482 | ) |
| 2483 | except object_identity.UserNotFoundError as exc: |
| 2484 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2485 | return |
| 2486 | except object_identity.AccountNotFoundError as exc: |
| 2487 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2488 | return |
| 2489 | except object_identity.AccountUnusableError as exc: |
| 2490 | _log_account_unusable(exc, "session_login") |
| 2491 | await _send_account_unusable(send) |
| 2492 | return |
| 2493 | except ValueError as exc: |
| 2494 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2495 | return |
| 2496 | except OSError: |
| 2497 | await _send_identity_store_unavailable(send) |
| 2498 | return |
| 2499 | |
| 2500 | _append_ops_auth_event( |
| 2501 | "session_minted", |
| 2502 | user_id=result["session"]["user_id"], |
| 2503 | method="session_login", |
| 2504 | label=result["session"].get("label"), |
| 2505 | ) |
| 2506 | await _send_json(send, {"status": "ok", **result}, status=201) |
| 2507 | return |
| 2508 | |
| 2509 | session = _current_identity_session(headers) |
| 2510 | if session is None: |
| 2511 | await _send_json( |
| 2512 | send, |
| 2513 | {"status": "error", "error": "Active session token required"}, |
| 2514 | status=401, |
| 2515 | ) |
| 2516 | return |
| 2517 | |
| 2518 | if method == "GET": |
| 2519 | await _send_json(send, {"status": "ok", "session": session.public_payload()}) |
| 2520 | return |
| 2521 | |
| 2522 | try: |
| 2523 | revoked = object_identity.revoke_session(session.session_id, base_dir=_data_dir()) |
| 2524 | except (object_identity.InvalidSessionPayloadError, object_identity.SessionNotFoundError) as exc: |
| 2525 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 2526 | return |
| 2527 | |
| 2528 | await _send_json(send, {"status": "ok", "session": revoked}) |
| 2529 | |
| 2530 | |
| 2531 | async def _handle_identity_password_login( |
| 2532 | send, |
| 2533 | payload: dict[str, Any], |
| 2534 | ) -> None: |
| 2535 | if not _env_enabled(PASSWORD_LOGIN_ENV): |
| 2536 | await _send_json( |
| 2537 | send, |
| 2538 | { |
| 2539 | "status": "error", |
| 2540 | "error": f"Password login is disabled. Set {PASSWORD_LOGIN_ENV}=true.", |
| 2541 | }, |
| 2542 | status=403, |
| 2543 | ) |
| 2544 | return |
| 2545 | |
| 2546 | try: |
| 2547 | login = _identity_password_login_payload(payload) |
| 2548 | except ValueError as exc: |
| 2549 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 2550 | return |
| 2551 | |
| 2552 | attempted = login["user_id"] or login["email"] or "" |
| 2553 | if _login_locked(attempted): |
| 2554 | _append_ops_auth_event("login_locked", identifier=attempted, method="password") |
| 2555 | await _send_json( |
| 2556 | send, |
| 2557 | {"status": "error", "error": LOGIN_LOCKED_MESSAGE}, |
| 2558 | status=429, |
| 2559 | ) |
| 2560 | return |
| 2561 | |
| 2562 | user = _password_login_user(login) |
| 2563 | lookup_user_id = user["user_id"] if user is not None else "__unknown_password_login__" |
| 2564 | verified = object_credentials.verify_password( |
| 2565 | lookup_user_id, |
| 2566 | login["password"], |
| 2567 | base_dir=_data_dir(), |
| 2568 | ) |
| 2569 | |
| 2570 | if user is None or not verified: |
| 2571 | _append_ops_auth_event("login_failed", identifier=attempted, method="password") |
| 2572 | await asyncio.sleep(PASSWORD_LOGIN_FAILURE_DELAY_SECONDS) |
| 2573 | await _send_json(send, {"status": "error", "error": "Invalid credentials"}, status=401) |
| 2574 | return |
| 2575 | |
| 2576 | try: |
| 2577 | result = object_identity.create_session( |
| 2578 | { |
| 2579 | "user_id": user["user_id"], |
| 2580 | "label": login["label"], |
| 2581 | "ttl_seconds": login["ttl_seconds"], |
| 2582 | }, |
| 2583 | base_dir=_data_dir(), |
| 2584 | require_known_user=True, |
| 2585 | ) |
| 2586 | except object_identity.AccountUnusableError as exc: |
| 2587 | # Only after the right password: nobody learns of it without one. |
| 2588 | _log_account_unusable(exc, "password") |
| 2589 | await _send_account_unusable(send) |
| 2590 | return |
| 2591 | except OSError: |
| 2592 | await _send_identity_store_unavailable(send) |
| 2593 | return |
| 2594 | except ValueError: |
| 2595 | _append_ops_auth_event("login_failed", identifier=attempted, method="password") |
| 2596 | await asyncio.sleep(PASSWORD_LOGIN_FAILURE_DELAY_SECONDS) |
| 2597 | await _send_json(send, {"status": "error", "error": "Invalid credentials"}, status=401) |
| 2598 | return |
| 2599 | |
| 2600 | _append_ops_auth_event( |
| 2601 | "login_succeeded", |
| 2602 | identifier=attempted, |
| 2603 | user_id=user["user_id"], |
| 2604 | method="password", |
| 2605 | label=login["label"], |
| 2606 | ) |
| 2607 | await _send_json(send, {"status": "ok", **result}, status=201) |
| 2608 | |
| 2609 | |
| 2610 | def _identity_password_login_payload(payload: Mapping[str, Any]) -> dict[str, Any]: |
| 2611 | allowed_keys = {"user_id", "email", "password", "label", "ttl_seconds"} |
| 2612 | unexpected = sorted(set(payload) - allowed_keys) |
| 2613 | if unexpected: |
| 2614 | raise ValueError(f"Unsupported password login fields: {', '.join(unexpected)}") |
| 2615 | |
| 2616 | password = payload.get("password") |
| 2617 | if not isinstance(password, str) or not password: |
| 2618 | raise ValueError("password must be a non-empty string") |
| 2619 | |
| 2620 | user_id = payload.get("user_id") |
| 2621 | email = payload.get("email") |
| 2622 | if (user_id is None) == (email is None): |
| 2623 | raise ValueError("Provide exactly one of user_id or email") |
| 2624 | |
| 2625 | label = payload.get("label") |
| 2626 | if label is not None and not isinstance(label, str): |
| 2627 | raise ValueError("label must be a string") |
| 2628 | |
| 2629 | return { |
| 2630 | "user_id": user_id, |
| 2631 | "email": email, |
| 2632 | "password": password, |
| 2633 | "label": label or "password login", |
| 2634 | "ttl_seconds": payload.get("ttl_seconds"), |
| 2635 | } |
| 2636 | |
| 2637 | |
| 2638 | # Request headers a webhook object may see. A deliberate SAFELIST rather |
| 2639 | # than everything-minus-secrets: providers sign with headers like |
| 2640 | # stripe-signature / x-hub-signature-256, and content negotiation needs |
| 2641 | # content-type -- but authorization and cookie belong to OUR callers, and |
| 2642 | # handing them to package code would turn a webhook object into a |
| 2643 | # credential tap. Extending this list is a conscious act, not a default. |
| 2644 | _WEBHOOK_HEADER_SAFELIST = ( |
| 2645 | "content-type", |
| 2646 | "user-agent", |
| 2647 | "stripe-signature", |
| 2648 | "x-hub-signature-256", |
| 2649 | "x-signature", |
| 2650 | "x-request-id", |
| 2651 | "idempotency-key", |
| 2652 | ) |
| 2653 | |
| 2654 | |
| 2655 | async def _handle_webhook( |
| 2656 | send, |
| 2657 | method: str, |
| 2658 | name: str, |
| 2659 | body: bytes, |
| 2660 | query: dict[str, str], |
| 2661 | headers: dict[str, str], |
| 2662 | ) -> None: |
| 2663 | """POST /webhooks/{name} -> execute the `webhook_{name}` object with the |
| 2664 | RAW request body. |
| 2665 | |
| 2666 | The one thing webhook objects need that no other route provides: |
| 2667 | provider signatures (Stripe, GitHub, Twilio) are HMACs over the exact |
| 2668 | bytes on the wire, and every other path parses the body before the |
| 2669 | object runs, destroying the thing that must be verified. This endpoint |
| 2670 | is deliberately provider-neutral core plumbing -- it knows nothing |
| 2671 | about Stripe; it delivers bytes and safelisted headers to an object a |
| 2672 | package ships, and the object owns verification and meaning. |
| 2673 | |
| 2674 | Security posture: webhooks are unauthenticated BY NATURE (the caller |
| 2675 | is a payment processor, not a user), so authenticity comes from the |
| 2676 | object verifying a signature over the raw body -- which is exactly why |
| 2677 | the body must arrive unparsed. The object still needs an explicit |
| 2678 | public-execute permission rule (no rule, no execution), the body-size |
| 2679 | limit already applied upstream holds, and the response is always JSON |
| 2680 | with no reflection of the input. |
| 2681 | """ |
| 2682 | if method != "POST": |
| 2683 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2684 | return |
| 2685 | clean = name.strip("/") |
| 2686 | if not clean or "/" in clean or not clean.replace("-", "_").replace("_", "a").isalnum(): |
| 2687 | await _send_json(send, {"status": "error", "error": "Unknown webhook"}, status=404) |
| 2688 | return |
| 2689 | object_id = f"webhook_{clean.replace('-', '_')}" |
| 2690 | if resolve_object_id(object_id, get_object_roots()) is None: |
| 2691 | await _send_json(send, {"status": "error", "error": "Unknown webhook"}, status=404) |
| 2692 | return |
| 2693 | |
| 2694 | payload: dict[str, Any] = dict(query) |
| 2695 | payload["_raw_body"] = body.decode("utf-8", "replace") |
| 2696 | payload["_headers"] = { |
| 2697 | key: value for key, value in headers.items() |
| 2698 | if key.lower() in _WEBHOOK_HEADER_SAFELIST |
| 2699 | } |
| 2700 | await _execute_object_method( |
| 2701 | send, |
| 2702 | object_id, |
| 2703 | "POST", |
| 2704 | payload, |
| 2705 | headers, |
| 2706 | permission_action=object_permissions.EXECUTE, |
| 2707 | ) |
| 2708 | |
| 2709 | |
| 2710 | async def _handle_exchange_profile(send, method: str, headers: dict[str, str]) -> None: |
| 2711 | """GET /.well-known/dbbasic -> the box's public exchange profile. |
| 2712 | |
| 2713 | Box-to-box exchange (docs/box-to-box-exchange.md) identifies a company by |
| 2714 | its domain and publishes the keys partners pin at this well-known path. |
| 2715 | The core only routes it: the profile belongs to the app-exchange package |
| 2716 | (site_exchange_profile), and a box without that package answers 404, as |
| 2717 | a box without a webhook object does at /webhooks/{name}. The object |
| 2718 | still needs its public-execute rule, like any other. |
| 2719 | """ |
| 2720 | if method not in {"GET", "HEAD"}: |
| 2721 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2722 | return |
| 2723 | object_id = http_api_contract.EXCHANGE_PROFILE_OBJECT_ID |
| 2724 | if resolve_object_id(object_id, get_object_roots()) is None: |
| 2725 | await _send_json(send, {"status": "error", "error": "Not found"}, status=404) |
| 2726 | return |
| 2727 | await _execute_object_method( |
| 2728 | send, object_id, "GET", {}, headers, permission_action=object_permissions.EXECUTE) |
| 2729 | |
| 2730 | |
| 2731 | async def _handle_mcp( |
| 2732 | send, |
| 2733 | method: str, |
| 2734 | body: bytes, |
| 2735 | headers: dict[str, str], |
| 2736 | ) -> None: |
| 2737 | if method != "POST": |
| 2738 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2739 | return |
| 2740 | |
| 2741 | protocol_header = headers.get("mcp-protocol-version", "").strip() |
| 2742 | if protocol_header and protocol_header not in object_mcp.SUPPORTED_MCP_PROTOCOL_VERSIONS: |
| 2743 | await _send_json( |
| 2744 | send, |
| 2745 | object_mcp.jsonrpc_error( |
| 2746 | -32600, f"Unsupported MCP protocol version: {protocol_header}" |
| 2747 | ), |
| 2748 | status=400, |
| 2749 | ) |
| 2750 | return |
| 2751 | |
| 2752 | gate_error = _admin_token_gate_error(headers, f"MCP requires {ADMIN_TOKEN_ENV}.") |
| 2753 | if gate_error is not None: |
| 2754 | status, message = gate_error |
| 2755 | await _send_json(send, object_mcp.jsonrpc_error(-32000, message), status=status) |
| 2756 | return |
| 2757 | |
| 2758 | try: |
| 2759 | message = json.loads(body.decode("utf-8")) |
| 2760 | except (UnicodeDecodeError, json.JSONDecodeError): |
| 2761 | await _send_json(send, object_mcp.jsonrpc_error(-32700, "Parse error")) |
| 2762 | return |
| 2763 | |
| 2764 | if not isinstance(message, dict) or message.get("jsonrpc") != "2.0": |
| 2765 | await _send_json( |
| 2766 | send, |
| 2767 | object_mcp.jsonrpc_error(-32600, "Invalid Request: missing jsonrpc 2.0"), |
| 2768 | ) |
| 2769 | return |
| 2770 | |
| 2771 | rpc_method = message.get("method") |
| 2772 | params = message.get("params") or {} |
| 2773 | request_id = message.get("id") |
| 2774 | |
| 2775 | if not isinstance(rpc_method, str) or not rpc_method: |
| 2776 | await _send_json( |
| 2777 | send, |
| 2778 | object_mcp.jsonrpc_error(-32600, "Invalid Request: missing method", request_id), |
| 2779 | ) |
| 2780 | return |
| 2781 | |
| 2782 | if rpc_method.startswith("notifications/"): |
| 2783 | await _send_response(send, status=202, headers=[], body=b"") |
| 2784 | return |
| 2785 | |
| 2786 | if rpc_method == "initialize": |
| 2787 | session_id = headers.get("mcp-session-id", "").strip() or object_ids.new_uuid4() |
| 2788 | await _send_json( |
| 2789 | send, |
| 2790 | object_mcp.jsonrpc_response(object_mcp.handle_initialize(params), request_id), |
| 2791 | headers=[("mcp-session-id", session_id)], |
| 2792 | ) |
| 2793 | return |
| 2794 | |
| 2795 | if rpc_method == "tools/list": |
| 2796 | await _send_json( |
| 2797 | send, |
| 2798 | object_mcp.jsonrpc_response(object_mcp.handle_tools_list(), request_id), |
| 2799 | ) |
| 2800 | return |
| 2801 | |
| 2802 | if rpc_method == "tools/call": |
| 2803 | tool_name = params.get("name") |
| 2804 | arguments = params.get("arguments") or {} |
| 2805 | try: |
| 2806 | route_method, path, query_string, route_body = object_mcp.tool_route( |
| 2807 | tool_name, arguments |
| 2808 | ) |
| 2809 | except ValueError as exc: |
| 2810 | await _send_json( |
| 2811 | send, |
| 2812 | object_mcp.jsonrpc_response( |
| 2813 | { |
| 2814 | "content": [ |
| 2815 | {"type": "text", "text": json.dumps({"error": str(exc)})} |
| 2816 | ], |
| 2817 | "isError": True, |
| 2818 | }, |
| 2819 | request_id, |
| 2820 | ), |
| 2821 | ) |
| 2822 | return |
| 2823 | |
| 2824 | status, payload = await _internal_request( |
| 2825 | route_method, |
| 2826 | path, |
| 2827 | query_string, |
| 2828 | route_body, |
| 2829 | authorization=headers.get("authorization", ""), |
| 2830 | ) |
| 2831 | await _send_json( |
| 2832 | send, |
| 2833 | object_mcp.jsonrpc_response( |
| 2834 | object_mcp.tool_result_content(status, payload), request_id |
| 2835 | ), |
| 2836 | ) |
| 2837 | return |
| 2838 | |
| 2839 | await _send_json( |
| 2840 | send, |
| 2841 | object_mcp.jsonrpc_error(-32601, f"Method not found: {rpc_method}", request_id), |
| 2842 | ) |
| 2843 | |
| 2844 | |
| 2845 | async def _internal_request( |
| 2846 | method: str, |
| 2847 | path: str, |
| 2848 | query_string: str, |
| 2849 | body: bytes, |
| 2850 | *, |
| 2851 | authorization: str, |
| 2852 | ) -> tuple[int, Any]: |
| 2853 | """Dispatch one request through the server's own routing. |
| 2854 | |
| 2855 | Used by the MCP layer so tool calls hit the exact same gates, permission |
| 2856 | checks, audit trail, and correlation ids as external HTTP callers. |
| 2857 | """ |
| 2858 | messages: list[dict[str, Any]] = [] |
| 2859 | sent = False |
| 2860 | |
| 2861 | async def receive() -> dict[str, Any]: |
| 2862 | nonlocal sent |
| 2863 | if not sent: |
| 2864 | sent = True |
| 2865 | return {"type": "http.request", "body": body, "more_body": False} |
| 2866 | return {"type": "http.disconnect"} |
| 2867 | |
| 2868 | async def send(message: dict[str, Any]) -> None: |
| 2869 | messages.append(message) |
| 2870 | |
| 2871 | scope_headers = [(b"content-type", b"application/json")] |
| 2872 | if authorization: |
| 2873 | scope_headers.append((b"authorization", authorization.encode("latin-1"))) |
| 2874 | |
| 2875 | scope = { |
| 2876 | "type": "http", |
| 2877 | "method": method, |
| 2878 | "path": path, |
| 2879 | "query_string": query_string.encode("utf-8"), |
| 2880 | "headers": scope_headers, |
| 2881 | "client": ("127.0.0.1", 0), |
| 2882 | } |
| 2883 | await app(scope, receive, send) |
| 2884 | |
| 2885 | status = 500 |
| 2886 | for message in messages: |
| 2887 | if message["type"] == "http.response.start": |
| 2888 | status = message["status"] |
| 2889 | break |
| 2890 | raw = b"".join( |
| 2891 | message.get("body", b"") |
| 2892 | for message in messages |
| 2893 | if message["type"] == "http.response.body" |
| 2894 | ) |
| 2895 | try: |
| 2896 | payload: Any = json.loads(raw.decode("utf-8")) |
| 2897 | except (UnicodeDecodeError, json.JSONDecodeError): |
| 2898 | payload = raw.decode("utf-8", errors="replace") |
| 2899 | return status, payload |
| 2900 | |
| 2901 | |
| 2902 | async def _handle_login( |
| 2903 | send, |
| 2904 | method: str, |
| 2905 | query: dict[str, str], |
| 2906 | body: bytes, |
| 2907 | headers: dict[str, str], |
| 2908 | ) -> None: |
| 2909 | if method == "GET": |
| 2910 | if not _env_enabled(PASSWORD_LOGIN_ENV): |
| 2911 | await _send_login_page(send, error="Password login is disabled on this server.", status=403) |
| 2912 | return |
| 2913 | if _current_identity_session(headers) is not None: |
| 2914 | await _send_redirect(send, _safe_next_path(query.get("next"))) |
| 2915 | return |
| 2916 | error = None |
| 2917 | notice = None |
| 2918 | if query.get("error") == "locked": |
| 2919 | error = LOGIN_LOCKED_MESSAGE |
| 2920 | elif query.get("error") == "account": |
| 2921 | error = ACCOUNT_UNUSABLE_MESSAGE |
| 2922 | elif query.get("error"): |
| 2923 | error = "Invalid email or password." |
| 2924 | elif query.get("reset"): |
| 2925 | notice = "Your password was changed. Sign in with the new one." |
| 2926 | elif query.get("verified"): |
| 2927 | notice = "Your email address is confirmed. Sign in to continue." |
| 2928 | await _send_login_page(send, error=error, notice=notice, next_path=_safe_next_path(query.get("next"))) |
| 2929 | return |
| 2930 | |
| 2931 | if method != "POST": |
| 2932 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 2933 | return |
| 2934 | |
| 2935 | if not _env_enabled(PASSWORD_LOGIN_ENV): |
| 2936 | await _send_json( |
| 2937 | send, |
| 2938 | { |
| 2939 | "status": "error", |
| 2940 | "error": f"Password login is disabled. Set {PASSWORD_LOGIN_ENV}=true.", |
| 2941 | }, |
| 2942 | status=403, |
| 2943 | ) |
| 2944 | return |
| 2945 | |
| 2946 | form = _parse_form_body(body, headers) |
| 2947 | if form is None: |
| 2948 | await _send_json( |
| 2949 | send, |
| 2950 | { |
| 2951 | "status": "error", |
| 2952 | "error": "Login form must be application/x-www-form-urlencoded; JSON clients should use POST /identity/session.", |
| 2953 | }, |
| 2954 | status=400, |
| 2955 | ) |
| 2956 | return |
| 2957 | |
| 2958 | next_path = _safe_next_path(form.get("next")) |
| 2959 | email = (form.get("email") or "").strip() |
| 2960 | password = form.get("password") or "" |
| 2961 | failure_location = f"{http_api_contract.LOGIN_PATH}?error=1" |
| 2962 | if next_path != "/": |
| 2963 | failure_location += f"&next={urllib.parse.quote(next_path)}" |
| 2964 | |
| 2965 | if not email or not password: |
| 2966 | await _send_redirect(send, failure_location) |
| 2967 | return |
| 2968 | |
| 2969 | if _login_locked(email): |
| 2970 | _append_ops_auth_event("login_locked", identifier=email, method="password_form") |
| 2971 | locked_location = f"{http_api_contract.LOGIN_PATH}?error=locked" |
| 2972 | if next_path != "/": |
| 2973 | locked_location += f"&next={urllib.parse.quote(next_path)}" |
| 2974 | await _send_redirect(send, locked_location) |
| 2975 | return |
| 2976 | |
| 2977 | login = {"user_id": None, "email": email, "password": password} |
| 2978 | user = _password_login_user(login) |
| 2979 | lookup_user_id = user["user_id"] if user is not None else "__unknown_password_login__" |
| 2980 | verified = object_credentials.verify_password(lookup_user_id, password, base_dir=_data_dir()) |
| 2981 | |
| 2982 | if user is None or not verified: |
| 2983 | _append_ops_auth_event("login_failed", identifier=email, method="password_form") |
| 2984 | await asyncio.sleep(PASSWORD_LOGIN_FAILURE_DELAY_SECONDS) |
| 2985 | await _send_redirect(send, failure_location) |
| 2986 | return |
| 2987 | |
| 2988 | try: |
| 2989 | result = object_identity.create_session( |
| 2990 | {"user_id": user["user_id"], "label": "browser login"}, |
| 2991 | base_dir=_data_dir(), |
| 2992 | require_known_user=True, |
| 2993 | ) |
| 2994 | except object_identity.AccountUnusableError as exc: |
| 2995 | # Only after the right password: nobody learns of it without one. |
| 2996 | _log_account_unusable(exc, "password_form") |
| 2997 | account_location = f"{http_api_contract.LOGIN_PATH}?error=account" |
| 2998 | if next_path != "/": |
| 2999 | account_location += f"&next={urllib.parse.quote(next_path)}" |
| 3000 | await _send_redirect(send, account_location) |
| 3001 | return |
| 3002 | except OSError: |
| 3003 | await _send_identity_store_unavailable(send) |
| 3004 | return |
| 3005 | except ValueError: |
| 3006 | _append_ops_auth_event("login_failed", identifier=email, method="password_form") |
| 3007 | await asyncio.sleep(PASSWORD_LOGIN_FAILURE_DELAY_SECONDS) |
| 3008 | await _send_redirect(send, failure_location) |
| 3009 | return |
| 3010 | |
| 3011 | _append_ops_auth_event( |
| 3012 | "login_succeeded", |
| 3013 | identifier=email, |
| 3014 | user_id=user["user_id"], |
| 3015 | method="password_form", |
| 3016 | label="browser login", |
| 3017 | ) |
| 3018 | await _send_redirect( |
| 3019 | send, |
| 3020 | next_path if next_path != "/" else _landing_path(), |
| 3021 | extra_headers=[ |
| 3022 | _session_cookie_header( |
| 3023 | result["token"], |
| 3024 | max_age=object_identity.DEFAULT_SESSION_TTL_SECONDS, |
| 3025 | ) |
| 3026 | ], |
| 3027 | ) |
| 3028 | |
| 3029 | |
| 3030 | def _landing_path_blockers() -> list[str]: |
| 3031 | value = (os.environ.get(LANDING_PATH_ENV) or "").strip() |
| 3032 | if value and _safe_next_path(value) != value: |
| 3033 | return [f"{LANDING_PATH_ENV} must be a path on this site, starting with a single /; it is ignored and the homepage is used."] |
| 3034 | return [] |
| 3035 | |
| 3036 | |
| 3037 | def _signup_blockers() -> list[str]: |
| 3038 | try: |
| 3039 | policy = object_permission_store.load_policy(_data_dir()) |
| 3040 | except (OSError, ValueError): |
| 3041 | return ["The permission policy could not be read."] |
| 3042 | return _landing_path_blockers() + object_signup.signup_blockers( |
| 3043 | policy=policy, |
| 3044 | enforcement_enabled=_permission_enforcement_enabled(), |
| 3045 | password_login_enabled=_env_enabled(PASSWORD_LOGIN_ENV), |
| 3046 | base_dir=_data_dir(), |
| 3047 | ) |
| 3048 | |
| 3049 | |
| 3050 | def _password_reset_blockers() -> list[str]: |
| 3051 | return object_signup.reset_blockers( |
| 3052 | password_login_enabled=_env_enabled(PASSWORD_LOGIN_ENV), |
| 3053 | base_dir=_data_dir(), |
| 3054 | ) |
| 3055 | |
| 3056 | |
| 3057 | def _signup_available() -> bool: |
| 3058 | return object_signup.env_enabled(object_signup.SIGNUP_ENV) and not _signup_blockers() |
| 3059 | |
| 3060 | |
| 3061 | def _password_reset_available() -> bool: |
| 3062 | return object_signup.env_enabled(object_signup.PASSWORD_RESET_ENV) and not _password_reset_blockers() |
| 3063 | |
| 3064 | |
| 3065 | def _signup_rate_limited(identity: str, limit: int) -> bool: |
| 3066 | """One hourly bucket per identity; fails closed, as a public write should.""" |
| 3067 | result = object_rate_limit.check_rate_limit( |
| 3068 | directory=_rate_limit_dir(), |
| 3069 | identity=identity, |
| 3070 | limit=limit, |
| 3071 | window_seconds=3600, |
| 3072 | fail_closed=True, |
| 3073 | ) |
| 3074 | return not result.allowed |
| 3075 | |
| 3076 | |
| 3077 | def _email_address_rate_limited(email: str) -> bool: |
| 3078 | return _signup_rate_limited(f"signup-email:{object_identity.email_key(email)}", EMAILS_PER_HOUR_PER_ADDRESS) |
| 3079 | |
| 3080 | |
| 3081 | def _send_verification_link(user: Mapping[str, Any]) -> bool: |
| 3082 | """Email a fresh confirmation link; False when email can't go out or the address hit its hourly limit.""" |
| 3083 | email = user.get("email") or "" |
| 3084 | base_url = object_signup.public_url() |
| 3085 | if not email or base_url is None or object_signup.email_blockers(base_dir=_data_dir()): |
| 3086 | return False |
| 3087 | if _email_address_rate_limited(email): |
| 3088 | return False |
| 3089 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], email, base_dir=_data_dir()) |
| 3090 | object_signup.send(email, object_signup.verification_email(base_url, token), base_dir=_data_dir()) |
| 3091 | return True |
| 3092 | |
| 3093 | |
| 3094 | def _same_origin_form(headers: dict[str, str]) -> bool: |
| 3095 | """These forms sign a browser in or change a password, so a POST from |
| 3096 | another site is refused whether or not a session cookie is present.""" |
| 3097 | return _cookie_request_origin_allowed(headers) |
| 3098 | |
| 3099 | |
| 3100 | async def _send_signup_unavailable(send) -> None: |
| 3101 | inner = """<div class="panel"><h1>Sign up</h1> |
| 3102 | <p>New accounts can't be created on this server.</p> |
| 3103 | <p class="links"><a href="/login">Sign in</a></p></div>""" |
| 3104 | await _send_auth_page(send, "Sign up", inner, status=403) |
| 3105 | |
| 3106 | |
| 3107 | async def _send_signup_page(send, *, error: str | None = None, email: str = "", status: int = 200) -> None: |
| 3108 | inner = f"""<form method="post" action="{html.escape(http_api_contract.SIGNUP_PATH, quote=True)}"> |
| 3109 | <h1>Create an account</h1> |
| 3110 | {_message_block(error)} |
| 3111 | <label for="email">Email</label> |
| 3112 | <input id="email" name="email" type="email" autocomplete="email" required autofocus value="{html.escape(email, quote=True)}"> |
| 3113 | <p>We'll email you a link. You choose your password there, once the link shows the address is yours.</p> |
| 3114 | <button type="submit">Create account</button> |
| 3115 | <p class="links"><a href="{html.escape(http_api_contract.LOGIN_PATH, quote=True)}">Already have an account? Sign in</a></p> |
| 3116 | </form>""" |
| 3117 | await _send_auth_page(send, "Create an account", inner, status=status) |
| 3118 | |
| 3119 | |
| 3120 | async def _send_check_email_page(send, title: str, message: str) -> None: |
| 3121 | inner = f"""<div class="panel"><h1>{html.escape(title)}</h1> |
| 3122 | <p>{html.escape(message)}</p> |
| 3123 | <p>Nothing there? Check your spam folder. The link works once.</p> |
| 3124 | <p class="links"><a href="{html.escape(http_api_contract.LOGIN_PATH, quote=True)}">Back to sign in</a></p></div>""" |
| 3125 | await _send_auth_page(send, title, inner) |
| 3126 | |
| 3127 | |
| 3128 | async def _handle_signup(scope, send, method: str, query: dict[str, str], body: bytes, headers: dict[str, str]) -> None: |
| 3129 | if method not in ("GET", "POST"): |
| 3130 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3131 | return |
| 3132 | if not _signup_available(): |
| 3133 | await _send_signup_unavailable(send) |
| 3134 | return |
| 3135 | if method == "GET": |
| 3136 | if query.get("sent"): |
| 3137 | await _send_check_email_page( |
| 3138 | send, |
| 3139 | "Check your email", |
| 3140 | "We've sent a link to the address you gave. Open it to confirm the address and choose your password.", |
| 3141 | ) |
| 3142 | return |
| 3143 | await _send_signup_page(send) |
| 3144 | return |
| 3145 | |
| 3146 | form = _parse_form_body(body, headers) |
| 3147 | if form is None or not _same_origin_form(headers): |
| 3148 | await _send_signup_page(send, error="That form couldn't be read. Please try again.", status=400) |
| 3149 | return |
| 3150 | email = (form.get("email") or "").strip() |
| 3151 | |
| 3152 | if _signup_rate_limited(f"signup-ip:{_client_ip(scope, headers)}", SIGNUP_ATTEMPTS_PER_HOUR_PER_IP): |
| 3153 | await _send_signup_page(send, error="Too many sign-ups from here. Try again in an hour.", email=email, status=429) |
| 3154 | return |
| 3155 | try: |
| 3156 | result = object_signup.register(email, base_dir=_data_dir()) |
| 3157 | except object_signup.SignupError as exc: |
| 3158 | await _send_signup_page(send, error=str(exc), email=email, status=400) |
| 3159 | return |
| 3160 | |
| 3161 | user = result["user"] |
| 3162 | _append_ops_auth_event(f"signup_{result['outcome']}", identifier=email, user_id=user["user_id"], method="signup_form") |
| 3163 | # every outcome looks the same from here; only the mailbox learns which it was |
| 3164 | if result["outcome"] in ("created", "pending"): |
| 3165 | _send_verification_link(user) |
| 3166 | elif not _email_address_rate_limited(email): |
| 3167 | object_signup.send( |
| 3168 | user["email"], |
| 3169 | object_signup.already_registered_email(object_signup.public_url() or "", _password_reset_available()), |
| 3170 | base_dir=_data_dir(), |
| 3171 | ) |
| 3172 | await _send_redirect(send, f"{http_api_contract.SIGNUP_PATH}?sent=1") |
| 3173 | |
| 3174 | |
| 3175 | def _installed_facts() -> dict[str, str]: |
| 3176 | """What /health adds for an installer checking its work: the release and commit that |
| 3177 | scripts/install.sh wrote (data/installed.json), and whether setup is still waiting. Nothing |
| 3178 | when the server wasn't installed that way.""" |
| 3179 | facts: dict[str, str] = {} |
| 3180 | try: |
| 3181 | with open(os.path.join(_data_dir(), "installed.json"), encoding="utf-8") as handle: |
| 3182 | installed = json.load(handle) |
| 3183 | except (OSError, ValueError): |
| 3184 | installed = {} |
| 3185 | if isinstance(installed, dict): |
| 3186 | for key, pattern in (("release", r"[0-9A-Za-z._-]{1,64}"), ("commit", r"[0-9a-f]{40}")): |
| 3187 | value = installed.get(key) |
| 3188 | if isinstance(value, str) and re.fullmatch(pattern, value): |
| 3189 | facts[key] = value |
| 3190 | if object_setup.waiting(_data_dir()): |
| 3191 | facts["setup"] = "waiting" |
| 3192 | return facts |
| 3193 | |
| 3194 | |
| 3195 | async def _send_setup_waiting(send, method: str, headers: dict[str, str]) -> None: |
| 3196 | if method in ("GET", "HEAD") and "text/html" in headers.get("accept", ""): |
| 3197 | await _send_redirect(send, object_setup.SETUP_PATH) |
| 3198 | return |
| 3199 | await _send_json( |
| 3200 | send, |
| 3201 | {"status": "error", "error": "This server is waiting for its owner to finish setup.", |
| 3202 | "setup": object_setup.SETUP_PATH}, |
| 3203 | status=503, |
| 3204 | ) |
| 3205 | |
| 3206 | |
| 3207 | # Fills the code in from the address the installer gave (/setup#code=...), then takes it out of the |
| 3208 | # address bar and history. The part after # is never sent to any server, so the code stays out of logs. |
| 3209 | _SETUP_PAGE_SCRIPT = """<script> |
| 3210 | (function () { |
| 3211 | function take() { |
| 3212 | var m = /(?:^#|&)code=([0-9A-Za-z-]+)/.exec(location.hash || ""); |
| 3213 | if (!m) return; |
| 3214 | var box = document.getElementById("code"); |
| 3215 | if (box && !box.value) box.value = m[1]; |
| 3216 | history.replaceState(null, "", location.pathname); |
| 3217 | var next = document.getElementById("email"); |
| 3218 | if (next) next.focus(); |
| 3219 | } |
| 3220 | take(); |
| 3221 | // the link opened on this same page (only the part after # changed) loads nothing new: read it then too |
| 3222 | window.addEventListener("hashchange", take); |
| 3223 | })(); |
| 3224 | </script>""" |
| 3225 | |
| 3226 | |
| 3227 | async def _send_setup_page(send, *, error: str | None = None, code: str = "", email: str = "", |
| 3228 | display_name: str = "", status: int = 200) -> None: |
| 3229 | inner = f"""<form method="post" action="{html.escape(object_setup.SETUP_PATH, quote=True)}" autocomplete="off"> |
| 3230 | <h1>Set up your server</h1> |
| 3231 | {_message_block(error)} |
| 3232 | <p>You'll be its first admin. Choose the email and password you'll sign in with.</p> |
| 3233 | <label for="code">Setup code</label> |
| 3234 | <input id="code" name="code" type="text" required spellcheck="false" autocapitalize="characters" maxlength="40" value="{html.escape(code, quote=True)}"> |
| 3235 | <label for="email">Email</label> |
| 3236 | <input id="email" name="email" type="email" autocomplete="username" required value="{html.escape(email, quote=True)}"> |
| 3237 | <label for="display_name">Name <small>(optional)</small></label> |
| 3238 | <input id="display_name" name="display_name" type="text" autocomplete="name" maxlength="100" value="{html.escape(display_name, quote=True)}"> |
| 3239 | <label for="password">Password</label> |
| 3240 | <input id="password" name="password" type="password" autocomplete="new-password" minlength="{object_credentials.MIN_PASSWORD_LENGTH}" required> |
| 3241 | <button type="submit">Make me the admin</button> |
| 3242 | <p>The setup code came with your install. It works once.</p> |
| 3243 | </form>{_SETUP_PAGE_SCRIPT}""" |
| 3244 | await _send_auth_page(send, "Set up your server", inner, status=status) |
| 3245 | |
| 3246 | |
| 3247 | async def _handle_setup(scope, send, method: str, body: bytes, headers: dict[str, str]) -> None: |
| 3248 | """The first admin of a one-click box (object_setup has the why).""" |
| 3249 | if method not in ("GET", "POST"): |
| 3250 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3251 | return |
| 3252 | if not object_setup.waiting(_data_dir()): |
| 3253 | inner = """<div class="panel"><h1>Set up your server</h1> |
| 3254 | <p>This server is already set up.</p> |
| 3255 | <p class="links"><a href="/login">Sign in</a></p></div>""" |
| 3256 | await _send_auth_page(send, "Set up your server", inner, status=404) |
| 3257 | return |
| 3258 | if not _env_enabled(PASSWORD_LOGIN_ENV): |
| 3259 | inner = f"""<div class="panel"><h1>Set up your server</h1> |
| 3260 | <p class="error">Setup makes a password login, and password login is off here. Set {html.escape(PASSWORD_LOGIN_ENV)}=true and restart the server.</p></div>""" |
| 3261 | await _send_auth_page(send, "Set up your server", inner, status=409) |
| 3262 | return |
| 3263 | if method == "GET": |
| 3264 | await _send_setup_page(send) |
| 3265 | return |
| 3266 | |
| 3267 | form = _parse_form_body(body, headers) |
| 3268 | if form is None or not _same_origin_form(headers): |
| 3269 | await _send_setup_page(send, error="That form couldn't be read. Please try again.", status=400) |
| 3270 | return |
| 3271 | code, email = form.get("code") or "", (form.get("email") or "").strip() |
| 3272 | display_name = form.get("display_name") or "" |
| 3273 | if (_signup_rate_limited(f"setup-ip:{_client_ip(scope, headers)}", SETUP_ATTEMPTS_PER_HOUR_PER_IP) |
| 3274 | or _signup_rate_limited("setup-all", SETUP_ATTEMPTS_PER_HOUR)): |
| 3275 | await _send_setup_page(send, error="Too many tries. Wait an hour and try again.", code=code, |
| 3276 | email=email, display_name=display_name, status=429) |
| 3277 | return |
| 3278 | try: |
| 3279 | user = object_setup.complete(code, email, form.get("password"), display_name, base_dir=_data_dir()) |
| 3280 | except object_setup.SetupError as exc: |
| 3281 | await _send_setup_page(send, error=str(exc), code=code, email=email, display_name=display_name, status=400) |
| 3282 | return |
| 3283 | except object_credentials.SessionRevocationError as exc: |
| 3284 | # complete() took the password back and returned the code: nothing was made |
| 3285 | _append_ops_auth_event("setup_sessions_not_ended", identifier=email, user_id=exc.user_id, method="setup_form", |
| 3286 | label="setup undone; ending sessions under the new admin's id failed") |
| 3287 | await _send_setup_page(send, error="Something went wrong and nothing was set up. Your setup code still " |
| 3288 | "works: try again, and if it keeps failing tell the person who runs this server.", |
| 3289 | email=email, display_name=display_name, status=500) |
| 3290 | return |
| 3291 | if user is None: |
| 3292 | _append_ops_auth_event("setup_refused", identifier=email, method="setup_form") |
| 3293 | await asyncio.sleep(PASSWORD_LOGIN_FAILURE_DELAY_SECONDS) |
| 3294 | await _send_setup_page(send, error="That setup code isn't right.", email=email, |
| 3295 | display_name=display_name, status=400) |
| 3296 | return |
| 3297 | _append_ops_auth_event("setup_completed", identifier=email, user_id=user["user_id"], method="setup_form") |
| 3298 | try: |
| 3299 | result = object_identity.create_session( |
| 3300 | {"user_id": user["user_id"], "label": "setup"}, base_dir=_data_dir(), require_known_user=True) |
| 3301 | except ValueError: |
| 3302 | await _send_redirect(send, http_api_contract.LOGIN_PATH) |
| 3303 | return |
| 3304 | await _send_redirect( |
| 3305 | send, |
| 3306 | _landing_path(), |
| 3307 | extra_headers=[_session_cookie_header(result["token"], max_age=object_identity.DEFAULT_SESSION_TTL_SECONDS)], |
| 3308 | ) |
| 3309 | |
| 3310 | |
| 3311 | async def _send_link_problem_page( |
| 3312 | send, title: str, message: str, retry_path: str, retry_label: str, *, also: tuple[str, str] | None = None |
| 3313 | ) -> None: |
| 3314 | also_link = f' <a href="{html.escape(also[0], quote=True)}">{html.escape(also[1])}</a>' if also else "" |
| 3315 | inner = f"""<div class="panel"><h1>{html.escape(title)}</h1> |
| 3316 | <p class="error">{html.escape(message)}</p> |
| 3317 | <p class="links"><a href="{html.escape(retry_path, quote=True)}">{html.escape(retry_label)}</a>{also_link}</p></div>""" |
| 3318 | await _send_auth_page(send, title, inner, status=400) |
| 3319 | |
| 3320 | |
| 3321 | async def _send_confirm_page(send, token: str, *, error: str | None = None, display_name: str = "", status: int = 200) -> None: |
| 3322 | inner = f"""<form method="post" action="{html.escape(http_api_contract.VERIFY_EMAIL_PATH, quote=True)}"> |
| 3323 | <h1>Confirm your email</h1> |
| 3324 | {_message_block(error)} |
| 3325 | <p>One more step: choose a password to finish creating your account.</p> |
| 3326 | <input type="hidden" name="token" value="{html.escape(token, quote=True)}"> |
| 3327 | <label for="display_name">Name <small>(optional)</small></label> |
| 3328 | <input id="display_name" name="display_name" type="text" autocomplete="name" maxlength="{object_signup.MAX_DISPLAY_NAME_LENGTH}" value="{html.escape(display_name, quote=True)}"> |
| 3329 | <label for="password">Password</label> |
| 3330 | <input id="password" name="password" type="password" autocomplete="new-password" minlength="{object_credentials.MIN_PASSWORD_LENGTH}" required autofocus> |
| 3331 | <button type="submit">Confirm my email</button> |
| 3332 | </form>""" |
| 3333 | await _send_auth_page(send, "Confirm your email", inner, status=status) |
| 3334 | |
| 3335 | |
| 3336 | async def _send_confirm_link_problem(send, message: str) -> None: |
| 3337 | await _send_link_problem_page( |
| 3338 | send, "Confirm your email", message, |
| 3339 | http_api_contract.SIGNUP_PATH, "Sign up again for a new link", |
| 3340 | also=(http_api_contract.LOGIN_PATH, "Sign in"), |
| 3341 | ) |
| 3342 | |
| 3343 | |
| 3344 | async def _handle_verify_email(send, method: str, query: dict[str, str], body: bytes, headers: dict[str, str]) -> None: |
| 3345 | expired = "This link has expired or was already used. If you haven't finished creating your account, sign up again and we'll send a new link." |
| 3346 | if method == "GET": |
| 3347 | # the link only shows the form: mail scanners open links on their own, |
| 3348 | # and must not use the token up (or sign anyone in) |
| 3349 | token = query.get("token") or "" |
| 3350 | if object_signup.peek_token(token, object_signup.VERIFY_EMAIL, base_dir=_data_dir()) is None: |
| 3351 | await _send_confirm_link_problem(send, expired) |
| 3352 | return |
| 3353 | await _send_confirm_page(send, token) |
| 3354 | return |
| 3355 | if method != "POST": |
| 3356 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3357 | return |
| 3358 | |
| 3359 | form = _parse_form_body(body, headers) |
| 3360 | if form is None or not _same_origin_form(headers): |
| 3361 | await _send_confirm_link_problem(send, "That form couldn't be read. Open the link from the email again.") |
| 3362 | return |
| 3363 | token = form.get("token") or "" |
| 3364 | try: |
| 3365 | user = object_signup.confirm_signup(token, form.get("password"), form.get("display_name"), base_dir=_data_dir()) |
| 3366 | except object_signup.SignupError as exc: |
| 3367 | await _send_confirm_page(send, token, error=str(exc), display_name=form.get("display_name") or "", status=400) |
| 3368 | return |
| 3369 | except object_credentials.SessionRevocationError as exc: |
| 3370 | # A pending user has no session that works, but the sessions file |
| 3371 | # could not be written: report it, never a silent half-done signup. |
| 3372 | _append_ops_auth_event("password_set_sessions_not_ended", user_id=exc.user_id, method="verify_link", |
| 3373 | label="signup password set; revoking the user's sessions failed") |
| 3374 | inner = """<div class="panel"><h1>Confirm your email</h1> |
| 3375 | <p class="error">Something went wrong finishing your sign-up. Tell the person who runs this server.</p> |
| 3376 | <p class="links"><a href="/login">Sign in</a></p></div>""" |
| 3377 | await _send_auth_page(send, "Confirm your email", inner, status=500) |
| 3378 | return |
| 3379 | if user is None: |
| 3380 | await _send_confirm_link_problem(send, expired) |
| 3381 | return |
| 3382 | _append_ops_auth_event("email_verified", identifier=user.get("email"), user_id=user["user_id"], method="verify_link") |
| 3383 | try: |
| 3384 | result = object_identity.create_session( |
| 3385 | {"user_id": user["user_id"], "label": "email verified"}, |
| 3386 | base_dir=_data_dir(), |
| 3387 | require_known_user=True, |
| 3388 | ) |
| 3389 | except object_identity.AccountUnusableError as exc: |
| 3390 | _log_account_unusable(exc, "verify_link") |
| 3391 | await _send_redirect(send, f"{http_api_contract.LOGIN_PATH}?error=account") |
| 3392 | return |
| 3393 | except ValueError: |
| 3394 | await _send_redirect(send, f"{http_api_contract.LOGIN_PATH}?verified=1") |
| 3395 | return |
| 3396 | _append_ops_auth_event("session_minted", identifier=user.get("email"), user_id=user["user_id"], method="verify_link", label="email verified") |
| 3397 | await _send_redirect( |
| 3398 | send, |
| 3399 | _landing_path(), |
| 3400 | extra_headers=[_session_cookie_header(result["token"], max_age=object_identity.DEFAULT_SESSION_TTL_SECONDS)], |
| 3401 | ) |
| 3402 | |
| 3403 | |
| 3404 | async def _send_reset_request_page(send, *, error: str | None = None, email: str = "", status: int = 200) -> None: |
| 3405 | inner = f"""<form method="post" action="{html.escape(http_api_contract.PASSWORD_RESET_PATH, quote=True)}"> |
| 3406 | <h1>Reset your password</h1> |
| 3407 | {_message_block(error)} |
| 3408 | <p>Enter your account's email address and we'll send you a link to choose a new password.</p> |
| 3409 | <label for="email">Email</label> |
| 3410 | <input id="email" name="email" type="email" autocomplete="email" required autofocus value="{html.escape(email, quote=True)}"> |
| 3411 | <button type="submit">Send the link</button> |
| 3412 | <p class="links"><a href="{html.escape(http_api_contract.LOGIN_PATH, quote=True)}">Back to sign in</a></p> |
| 3413 | </form>""" |
| 3414 | await _send_auth_page(send, "Reset your password", inner, status=status) |
| 3415 | |
| 3416 | |
| 3417 | async def _handle_password_reset(scope, send, method: str, query: dict[str, str], body: bytes, headers: dict[str, str]) -> None: |
| 3418 | if method not in ("GET", "POST"): |
| 3419 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3420 | return |
| 3421 | if not _password_reset_available(): |
| 3422 | inner = """<div class="panel"><h1>Reset your password</h1> |
| 3423 | <p>Passwords can't be reset by email on this server. Ask the person who runs it.</p> |
| 3424 | <p class="links"><a href="/login">Sign in</a></p></div>""" |
| 3425 | await _send_auth_page(send, "Reset your password", inner, status=403) |
| 3426 | return |
| 3427 | if method == "GET": |
| 3428 | if query.get("sent"): |
| 3429 | await _send_check_email_page( |
| 3430 | send, |
| 3431 | "Check your email", |
| 3432 | "If that address has an account here, we've sent it a link to choose a new password. The link works for an hour.", |
| 3433 | ) |
| 3434 | return |
| 3435 | await _send_reset_request_page(send) |
| 3436 | return |
| 3437 | |
| 3438 | form = _parse_form_body(body, headers) |
| 3439 | if form is None or not _same_origin_form(headers): |
| 3440 | await _send_reset_request_page(send, error="That form couldn't be read. Please try again.", status=400) |
| 3441 | return |
| 3442 | email = (form.get("email") or "").strip() |
| 3443 | if _signup_rate_limited(f"reset-ip:{_client_ip(scope, headers)}", RESET_ATTEMPTS_PER_HOUR_PER_IP): |
| 3444 | await _send_reset_request_page(send, error="Too many requests from here. Try again in an hour.", email=email, status=429) |
| 3445 | return |
| 3446 | try: |
| 3447 | object_signup.normalize_email(email) |
| 3448 | except object_signup.SignupError as exc: |
| 3449 | await _send_reset_request_page(send, error=str(exc), email=email, status=400) |
| 3450 | return |
| 3451 | |
| 3452 | user = object_signup.reset_candidate(email, base_dir=_data_dir()) |
| 3453 | _append_ops_auth_event("password_reset_requested", identifier=email, user_id=user["user_id"] if user else None, method="reset_form") |
| 3454 | # The same answer, after the same work, whether or not the address may have a link: an address with |
| 3455 | # none uses up its hourly allowance, makes a token, hashes it and rewrites the token file like any other |
| 3456 | # (issue_decoy_token stores nothing), and the email is written out. Only queueing it differs, and that |
| 3457 | # happens after the answer has gone, so it can't be timed, and a failure there can't change the answer. |
| 3458 | message = None |
| 3459 | if not _email_address_rate_limited(email): |
| 3460 | if user is not None: |
| 3461 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=_data_dir()) |
| 3462 | else: |
| 3463 | token = object_signup.issue_decoy_token(object_signup.PASSWORD_RESET, base_dir=_data_dir()) |
| 3464 | message = object_signup.reset_email(object_signup.public_url() or "", token) |
| 3465 | await _send_redirect(send, f"{http_api_contract.PASSWORD_RESET_PATH}?sent=1") |
| 3466 | if user is not None and message is not None: |
| 3467 | try: |
| 3468 | object_signup.send(user["email"], message, base_dir=_data_dir()) |
| 3469 | except Exception as exc: # noqa: BLE001 -- the answer is sent; say what went wrong where the operator looks |
| 3470 | _LOG.warning("password reset email for user %s could not be queued: %s", user["user_id"], exc) |
| 3471 | _append_ops_auth_event("password_reset_mail_failed", identifier=email, user_id=user["user_id"], |
| 3472 | method="reset_form", label=f"{exc.__class__.__name__}: {exc}"[:200]) |
| 3473 | |
| 3474 | |
| 3475 | async def _send_new_password_page(send, token: str, *, error: str | None = None, status: int = 200) -> None: |
| 3476 | inner = f"""<form method="post" action="{html.escape(http_api_contract.PASSWORD_RESET_CONFIRM_PATH, quote=True)}"> |
| 3477 | <h1>Choose a new password</h1> |
| 3478 | {_message_block(error)} |
| 3479 | <input type="hidden" name="token" value="{html.escape(token, quote=True)}"> |
| 3480 | <label for="password">New password</label> |
| 3481 | <input id="password" name="password" type="password" autocomplete="new-password" minlength="{object_credentials.MIN_PASSWORD_LENGTH}" required autofocus> |
| 3482 | <button type="submit">Save the new password</button> |
| 3483 | <p>You'll be signed out everywhere else.</p> |
| 3484 | </form>""" |
| 3485 | await _send_auth_page(send, "Choose a new password", inner, status=status) |
| 3486 | |
| 3487 | |
| 3488 | async def _handle_password_reset_confirm(send, method: str, query: dict[str, str], body: bytes, headers: dict[str, str]) -> None: |
| 3489 | expired = "This link has expired or was already used. Ask for a new one." |
| 3490 | if method == "GET": |
| 3491 | token = query.get("token") or "" |
| 3492 | if object_signup.peek_token(token, object_signup.PASSWORD_RESET, base_dir=_data_dir()) is None: |
| 3493 | await _send_link_problem_page(send, "Choose a new password", expired, http_api_contract.PASSWORD_RESET_PATH, "Send a new link") |
| 3494 | return |
| 3495 | await _send_new_password_page(send, token) |
| 3496 | return |
| 3497 | if method != "POST": |
| 3498 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3499 | return |
| 3500 | |
| 3501 | form = _parse_form_body(body, headers) |
| 3502 | if form is None or not _same_origin_form(headers): |
| 3503 | await _send_link_problem_page(send, "Choose a new password", "That form couldn't be read. Open the link from the email again.", http_api_contract.PASSWORD_RESET_PATH, "Send a new link") |
| 3504 | return |
| 3505 | token = form.get("token") or "" |
| 3506 | try: |
| 3507 | user = object_signup.reset_password(token, form.get("password"), base_dir=_data_dir()) |
| 3508 | except object_signup.SignupError as exc: |
| 3509 | await _send_new_password_page(send, token, error=str(exc), status=400) |
| 3510 | return |
| 3511 | except object_credentials.SessionRevocationError as exc: |
| 3512 | # The new password is saved; the old sessions could not be ended. |
| 3513 | # Say so plainly (and log it) rather than "done" or a bare 500. |
| 3514 | _append_ops_auth_event("password_reset_sessions_not_ended", user_id=exc.user_id, method="reset_link", |
| 3515 | label="password reset; revoking the user's sessions failed") |
| 3516 | inner = """<div class="panel"><h1>Choose a new password</h1> |
| 3517 | <p class="error">Your new password is saved, but we couldn't sign you out of your other sessions. |
| 3518 | Anyone signed in with your old password may still be signed in. Tell the person who runs this server.</p> |
| 3519 | <p class="links"><a href="/login">Sign in</a></p></div>""" |
| 3520 | await _send_auth_page(send, "Choose a new password", inner, status=500) |
| 3521 | return |
| 3522 | if user is None: |
| 3523 | await _send_link_problem_page(send, "Choose a new password", expired, http_api_contract.PASSWORD_RESET_PATH, "Send a new link") |
| 3524 | return |
| 3525 | _append_ops_auth_event("password_reset", identifier=user.get("email"), user_id=user["user_id"], method="reset_link") |
| 3526 | await _send_redirect( |
| 3527 | send, |
| 3528 | f"{http_api_contract.LOGIN_PATH}?reset=1", |
| 3529 | extra_headers=[_session_cookie_header("", max_age=0)], |
| 3530 | ) |
| 3531 | |
| 3532 | |
| 3533 | async def _handle_logout(send, method: str, headers: dict[str, str]) -> None: |
| 3534 | if method != "POST": |
| 3535 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3536 | return |
| 3537 | |
| 3538 | session = _current_identity_session(headers) |
| 3539 | if session is not None: |
| 3540 | try: |
| 3541 | object_identity.revoke_session(session.session_id, base_dir=_data_dir()) |
| 3542 | except (OSError, ValueError, LookupError): |
| 3543 | pass |
| 3544 | _append_ops_auth_event("logout", user_id=session.user_id) |
| 3545 | |
| 3546 | await _send_redirect( |
| 3547 | send, |
| 3548 | http_api_contract.LOGIN_PATH, |
| 3549 | extra_headers=[_session_cookie_header("", max_age=0)], |
| 3550 | ) |
| 3551 | |
| 3552 | |
| 3553 | def _parse_form_body(body: bytes, headers: dict[str, str]) -> dict[str, str] | None: |
| 3554 | content_type = headers.get("content-type", "").split(";")[0].strip().lower() |
| 3555 | if content_type and content_type != "application/x-www-form-urlencoded": |
| 3556 | return None |
| 3557 | try: |
| 3558 | pairs = urllib.parse.parse_qsl(body.decode("utf-8"), keep_blank_values=True) |
| 3559 | except (UnicodeDecodeError, ValueError): |
| 3560 | return None |
| 3561 | return {name: value for name, value in pairs} |
| 3562 | |
| 3563 | |
| 3564 | def _safe_next_path(value: str | None) -> str: |
| 3565 | candidate = (value or "").strip() |
| 3566 | if ( |
| 3567 | not candidate.startswith("/") |
| 3568 | or candidate.startswith("//") |
| 3569 | or "\\" in candidate |
| 3570 | or any(ord(char) < 32 for char in candidate) |
| 3571 | ): |
| 3572 | return "/" |
| 3573 | return candidate |
| 3574 | |
| 3575 | |
| 3576 | def _landing_path() -> str: |
| 3577 | """Where a browser goes after confirming an email address: the site's own page for new accounts |
| 3578 | (DBBASIC_AUTH_LANDING_PATH, a local path), else the homepage.""" |
| 3579 | return _safe_next_path(os.environ.get(LANDING_PATH_ENV)) |
| 3580 | |
| 3581 | |
| 3582 | def _session_cookie_header(token: str, *, max_age: int) -> tuple[str, str]: |
| 3583 | attributes = [ |
| 3584 | f"{SESSION_COOKIE_NAME}={token}", |
| 3585 | "Path=/", |
| 3586 | "HttpOnly", |
| 3587 | "SameSite=Lax", |
| 3588 | f"Max-Age={max_age}", |
| 3589 | ] |
| 3590 | if _cookie_secure_enabled(): |
| 3591 | attributes.append("Secure") |
| 3592 | return ("set-cookie", "; ".join(attributes)) |
| 3593 | |
| 3594 | |
| 3595 | def _cookie_secure_enabled() -> bool: |
| 3596 | value = os.environ.get(COOKIE_SECURE_ENV, "").strip().lower() |
| 3597 | if not value: |
| 3598 | return True |
| 3599 | return value in TRUE_VALUES |
| 3600 | |
| 3601 | |
| 3602 | async def _send_redirect( |
| 3603 | send, |
| 3604 | location: str, |
| 3605 | *, |
| 3606 | extra_headers: list[tuple[str, str]] | None = None, |
| 3607 | ) -> None: |
| 3608 | headers = [ |
| 3609 | ("location", location), |
| 3610 | ("content-type", "text/html; charset=utf-8"), |
| 3611 | ] |
| 3612 | if extra_headers: |
| 3613 | headers.extend(extra_headers) |
| 3614 | body = f'<a href="{html.escape(location, quote=True)}">Continue</a>'.encode("utf-8") |
| 3615 | await _send_response(send, status=303, headers=headers, body=body) |
| 3616 | |
| 3617 | |
| 3618 | _AUTH_PAGE_STYLE = """ |
| 3619 | body { font-family: system-ui, sans-serif; background: #f5f5f4; margin: 0; |
| 3620 | display: flex; min-height: 100vh; align-items: center; justify-content: center; } |
| 3621 | form, .panel { background: #fff; border: 1px solid #d6d3d1; border-radius: 8px; |
| 3622 | padding: 2rem; width: 20rem; max-width: calc(100vw - 2rem); box-sizing: border-box; } |
| 3623 | h1 { font-size: 1.1rem; margin: 0 0 1rem; } |
| 3624 | label { display: block; font-size: 0.85rem; margin: 0.75rem 0 0.25rem; } |
| 3625 | input { width: 100%; box-sizing: border-box; padding: 0.5rem; font-size: 1rem; |
| 3626 | border: 1px solid #d6d3d1; border-radius: 4px; } |
| 3627 | button { margin-top: 1.25rem; width: 100%; padding: 0.6rem; border: 0; font-size: 1rem; |
| 3628 | border-radius: 4px; background: #1c1917; color: #fff; cursor: pointer; } |
| 3629 | p { font-size: 0.9rem; line-height: 1.4; } |
| 3630 | .error { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; |
| 3631 | border-radius: 4px; padding: 0.5rem; font-size: 0.85rem; } |
| 3632 | .notice { background: #f0fdf4; border: 1px solid #bbf7d0; color: #166534; |
| 3633 | border-radius: 4px; padding: 0.5rem; font-size: 0.85rem; } |
| 3634 | .links { margin: 1rem 0 0; font-size: 0.85rem; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 0.5rem 1rem; } |
| 3635 | .links a { white-space: nowrap; } |
| 3636 | a { color: #1c1917; } |
| 3637 | """ |
| 3638 | |
| 3639 | |
| 3640 | def _auth_page_html(title: str, inner: str) -> str: |
| 3641 | return f"""<!doctype html> |
| 3642 | <html lang="en"> |
| 3643 | <head> |
| 3644 | <meta charset="utf-8"> |
| 3645 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 3646 | <meta name="referrer" content="strict-origin"> |
| 3647 | <title>{html.escape(title)}</title> |
| 3648 | <style>{_AUTH_PAGE_STYLE}</style> |
| 3649 | </head> |
| 3650 | <body> |
| 3651 | {inner} |
| 3652 | </body> |
| 3653 | </html>""" |
| 3654 | |
| 3655 | |
| 3656 | async def _send_auth_page(send, title: str, inner: str, *, status: int = 200) -> None: |
| 3657 | await _send_response( |
| 3658 | send, |
| 3659 | status=status, |
| 3660 | headers=[ |
| 3661 | ("content-type", "text/html; charset=utf-8"), |
| 3662 | ("cache-control", "no-store"), |
| 3663 | ], |
| 3664 | body=_auth_page_html(title, inner).encode("utf-8"), |
| 3665 | ) |
| 3666 | |
| 3667 | |
| 3668 | def _message_block(error: str | None = None, notice: str | None = None) -> str: |
| 3669 | if error: |
| 3670 | return f'<p class="error">{html.escape(error)}</p>' |
| 3671 | if notice: |
| 3672 | return f'<p class="notice">{html.escape(notice)}</p>' |
| 3673 | return "" |
| 3674 | |
| 3675 | |
| 3676 | async def _send_login_page( |
| 3677 | send, |
| 3678 | *, |
| 3679 | error: str | None = None, |
| 3680 | notice: str | None = None, |
| 3681 | next_path: str = "/", |
| 3682 | status: int = 200, |
| 3683 | ) -> None: |
| 3684 | links = [] |
| 3685 | if _signup_available(): |
| 3686 | links.append(f'<a href="{html.escape(http_api_contract.SIGNUP_PATH, quote=True)}">Create an account</a>') |
| 3687 | if _password_reset_available(): |
| 3688 | links.append(f'<a href="{html.escape(http_api_contract.PASSWORD_RESET_PATH, quote=True)}">Forgot your password?</a>') |
| 3689 | links_block = f'<p class="links">{" ".join(links)}</p>' if links else "" |
| 3690 | if _signup_available(): |
| 3691 | links_block += "<p>Just signed up? Open the link we emailed you: you choose your password there.</p>" |
| 3692 | inner = f"""<form method="post" action="{html.escape(http_api_contract.LOGIN_PATH, quote=True)}"> |
| 3693 | <h1>Sign in</h1> |
| 3694 | {_message_block(error, notice)} |
| 3695 | <label for="email">Email</label> |
| 3696 | <input id="email" name="email" type="email" autocomplete="username" required autofocus> |
| 3697 | <label for="password">Password</label> |
| 3698 | <input id="password" name="password" type="password" autocomplete="current-password" required> |
| 3699 | <input type="hidden" name="next" value="{html.escape(next_path, quote=True)}"> |
| 3700 | <button type="submit">Sign in</button> |
| 3701 | {links_block} |
| 3702 | </form>""" |
| 3703 | await _send_auth_page(send, "Sign in", inner, status=status) |
| 3704 | |
| 3705 | |
| 3706 | def _password_login_user(login: Mapping[str, Any]) -> dict[str, Any] | None: |
| 3707 | if login["user_id"] is not None: |
| 3708 | if not isinstance(login["user_id"], str): |
| 3709 | return None |
| 3710 | try: |
| 3711 | user = object_identity.get_user(login["user_id"], base_dir=_data_dir()) |
| 3712 | except (ValueError, LookupError): |
| 3713 | return None |
| 3714 | return user if user.get("status") == "active" else None |
| 3715 | |
| 3716 | email = login["email"] |
| 3717 | if not isinstance(email, str) or not email.strip(): |
| 3718 | return None |
| 3719 | try: |
| 3720 | matches = object_identity.find_users_by_address( |
| 3721 | email, statuses=(object_identity.ACTIVE_STATUS,), base_dir=_data_dir()) |
| 3722 | except ValueError: |
| 3723 | return None |
| 3724 | if len(matches) != 1: |
| 3725 | return None |
| 3726 | return matches[0] |
| 3727 | |
| 3728 | |
| 3729 | async def _send_rate_limit_if_needed( |
| 3730 | scope: dict[str, Any], |
| 3731 | headers: dict[str, str], |
| 3732 | send, |
| 3733 | ) -> bool: |
| 3734 | limit = _rate_limit_requests() |
| 3735 | if limit <= 0: |
| 3736 | return False |
| 3737 | |
| 3738 | # This is the GLOBAL per-request DoS limiter, so it stays fail-open on |
| 3739 | # storage failure (fail_closed=False): a broken ratelimit dir must not |
| 3740 | # take the whole site down. But the degradation is no longer silent -- |
| 3741 | # check_rate_limit flags it and we log it, because an invisibly-degraded |
| 3742 | # limiter is a security hole. Public-write surfaces get their own check |
| 3743 | # with fail_closed=True (see object_rate_limit.check_rate_limit). |
| 3744 | result = object_rate_limit.check_rate_limit( |
| 3745 | directory=_rate_limit_dir(), |
| 3746 | identity=_rate_limit_identity(scope, headers), |
| 3747 | limit=limit, |
| 3748 | window_seconds=_rate_limit_window_seconds(), |
| 3749 | ) |
| 3750 | |
| 3751 | if result.degraded: |
| 3752 | try: |
| 3753 | object_logs.append_object_log( |
| 3754 | "object_rate_limit", |
| 3755 | "WARNING", |
| 3756 | "rate limiter degraded (storage unavailable); " |
| 3757 | f"failing {'open' if result.allowed else 'closed'} for this request", |
| 3758 | base_dir=_data_dir(), |
| 3759 | ) |
| 3760 | except Exception: |
| 3761 | pass |
| 3762 | |
| 3763 | if result.allowed: |
| 3764 | return False |
| 3765 | |
| 3766 | await _send_rate_limit_error(send, result) |
| 3767 | return True |
| 3768 | |
| 3769 | |
| 3770 | def _health_payload(*, include_metrics: bool) -> dict[str, Any]: |
| 3771 | metrics = _metrics.snapshot() |
| 3772 | storage_check = _storage_check() |
| 3773 | status = "ok" if storage_check["status"] == "ok" else "degraded" |
| 3774 | payload: dict[str, Any] = { |
| 3775 | "status": status, |
| 3776 | "timestamp": _utc_timestamp(), |
| 3777 | "version": _package_version(), |
| 3778 | "station_id": _station_id(), |
| 3779 | "pid": os.getpid(), |
| 3780 | "threads": _thread_count(), |
| 3781 | "uptime": metrics["uptime_human"], |
| 3782 | "uptime_seconds": metrics["uptime_seconds"], |
| 3783 | "requests": metrics["total_requests"], |
| 3784 | "errors": metrics["total_errors"], |
| 3785 | "rps": metrics["requests_per_second"], |
| 3786 | "error_rate": metrics["error_rate"], |
| 3787 | "response_time_ms": metrics["response_time_ms"], |
| 3788 | "objects": { |
| 3789 | "count": _object_count(), |
| 3790 | }, |
| 3791 | "capacity": { |
| 3792 | "requests": _request_limiter.snapshot(_max_concurrent_requests()), |
| 3793 | "object_executions": _execution_limiter.snapshot(_max_concurrent_executions()), |
| 3794 | "user_object_executions": { |
| 3795 | "max_per_user": _max_concurrent_executions_per_user(), |
| 3796 | "in_flight_by_user": _user_execution_limiter.snapshot(), |
| 3797 | }, |
| 3798 | }, |
| 3799 | "config": { |
| 3800 | "source_writes_enabled": _env_enabled(SOURCE_WRITES_ENV), |
| 3801 | "file_writes_enabled": _env_enabled(FILE_WRITES_ENV), |
| 3802 | "max_request_bytes": _max_request_bytes(), |
| 3803 | "max_object_file_bytes": _max_object_file_bytes(), |
| 3804 | "max_concurrent_requests": _max_concurrent_requests(), |
| 3805 | "max_concurrent_executions": _max_concurrent_executions(), |
| 3806 | "rate_limit_requests": _rate_limit_requests(), |
| 3807 | "rate_limit_window_seconds": _rate_limit_window_seconds(), |
| 3808 | "rate_limit_trust_proxy_headers": _env_enabled(RATE_LIMIT_TRUST_PROXY_HEADERS_ENV), |
| 3809 | "object_timeout_seconds": _object_timeout_seconds(), |
| 3810 | "trusted_in_process_objects": sorted(_trusted_in_process_object_ids()), |
| 3811 | "permission_enforcement_enabled": _permission_enforcement_enabled(), |
| 3812 | "permission_enforcement_requested": _permission_enforcement_requested(), |
| 3813 | "permission_enforcement_blocked": _permission_enforcement_blocked(), |
| 3814 | "permission_allow_unready_enforcement": _permission_unready_enforcement_allowed(), |
| 3815 | "permission_audit_enabled": _permission_audit_enabled(), |
| 3816 | "permission_mode": _permission_mode(), |
| 3817 | "permission_trust_headers": _env_enabled(PERMISSION_TRUST_HEADERS_ENV), |
| 3818 | "require_known_identity_users": _env_enabled(REQUIRE_KNOWN_IDENTITY_USERS_ENV), |
| 3819 | "event_keep_count": _event_keep_count(), |
| 3820 | "event_keep_seconds": _event_keep_seconds(), |
| 3821 | }, |
| 3822 | "checks": { |
| 3823 | "storage": storage_check, |
| 3824 | }, |
| 3825 | "system": _system_snapshot(), |
| 3826 | } |
| 3827 | |
| 3828 | if include_metrics: |
| 3829 | payload["metrics"] = metrics |
| 3830 | |
| 3831 | return payload |
| 3832 | |
| 3833 | |
| 3834 | async def _handle_admin_status( |
| 3835 | send, |
| 3836 | method: str, |
| 3837 | headers: dict[str, str], |
| 3838 | ) -> None: |
| 3839 | if method != "GET": |
| 3840 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3841 | return |
| 3842 | |
| 3843 | gate_error = _admin_token_gate_error( |
| 3844 | headers, |
| 3845 | f"Admin status requires {ADMIN_TOKEN_ENV}.", |
| 3846 | ) |
| 3847 | if gate_error is not None: |
| 3848 | status, message = gate_error |
| 3849 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 3850 | return |
| 3851 | |
| 3852 | try: |
| 3853 | payload = _admin_status_payload() |
| 3854 | except object_packages.InvalidPackageManifestError as exc: |
| 3855 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 3856 | return |
| 3857 | except OSError as exc: |
| 3858 | await _send_json( |
| 3859 | send, |
| 3860 | {"status": "error", "error": f"Could not build admin status: {exc}"}, |
| 3861 | status=500, |
| 3862 | ) |
| 3863 | return |
| 3864 | |
| 3865 | status_code = 503 if payload["status"] == "degraded" else 200 |
| 3866 | await _send_json(send, payload, status=status_code) |
| 3867 | |
| 3868 | |
| 3869 | async def _handle_admin_storage( |
| 3870 | send, |
| 3871 | method: str, |
| 3872 | headers: dict[str, str], |
| 3873 | ) -> None: |
| 3874 | """GET /admin/storage: compaction-observability stats for every |
| 3875 | append-mode collection (docs/storage-modes.md "Compaction"). |
| 3876 | |
| 3877 | Must stay fast regardless of collection size or cache/sidecar state -- |
| 3878 | passes allow_fold=False so no single collection's stats call can turn |
| 3879 | this into an O(file) scan; a collection whose cheap sources (warm |
| 3880 | _RECORDS_CACHE, coherent id->offset sidecar) can't answer comes back |
| 3881 | as an "estimated" entry (file_bytes only) instead of triggering a full |
| 3882 | fold. See object_records.append_collection_stats. |
| 3883 | """ |
| 3884 | if method != "GET": |
| 3885 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3886 | return |
| 3887 | |
| 3888 | gate_error = _admin_token_gate_error( |
| 3889 | headers, |
| 3890 | f"Admin storage requires {ADMIN_TOKEN_ENV}.", |
| 3891 | ) |
| 3892 | if gate_error is not None: |
| 3893 | status, message = gate_error |
| 3894 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 3895 | return |
| 3896 | |
| 3897 | append_collections = object_records.list_append_collection_stats( |
| 3898 | base_dir=_data_dir(), |
| 3899 | allow_fold=False, |
| 3900 | ) |
| 3901 | await _send_json( |
| 3902 | send, |
| 3903 | {"status": "ok", "append_collections": append_collections}, |
| 3904 | ) |
| 3905 | |
| 3906 | |
| 3907 | async def _handle_admin_collection_compact( |
| 3908 | send, |
| 3909 | collection: str, |
| 3910 | headers: dict[str, str], |
| 3911 | ) -> None: |
| 3912 | """POST /admin/collections/{collection}/compact: run |
| 3913 | object_records.compact_collection under the same gates that protect |
| 3914 | other mutating admin record routes (admin token, then the same |
| 3915 | collection-level write-permission check _record_write_denied_before_ |
| 3916 | lookup applies to record create/update/delete -- there is no single |
| 3917 | record here, so the collection-level check is the whole check, same |
| 3918 | as it is for those routes before their own per-record lookup runs). |
| 3919 | |
| 3920 | 404 for an unknown collection, 400 for a collection not currently in |
| 3921 | append storage mode (nothing to compact -- compact_collection itself |
| 3922 | tolerates being called on a classic collection as a no-op, but this |
| 3923 | endpoint reports that as a client error instead of a silent 200, so |
| 3924 | "I asked to compact X" never comes back "ok" for a collection that |
| 3925 | was never compactable to begin with). |
| 3926 | """ |
| 3927 | if await _record_write_denied_before_lookup( |
| 3928 | send, |
| 3929 | headers, |
| 3930 | object_permissions.UPDATE, |
| 3931 | collection=collection, |
| 3932 | ): |
| 3933 | return |
| 3934 | |
| 3935 | try: |
| 3936 | mode_stats = object_records.append_collection_stats(collection, base_dir=_data_dir()) |
| 3937 | except object_collections.InvalidCollectionNameError as exc: |
| 3938 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 3939 | return |
| 3940 | except object_collections.CollectionNotFoundError as exc: |
| 3941 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 3942 | return |
| 3943 | |
| 3944 | if mode_stats is None: |
| 3945 | await _send_json( |
| 3946 | send, |
| 3947 | { |
| 3948 | "status": "error", |
| 3949 | "error": f"Collection is not in append storage mode: {collection}", |
| 3950 | }, |
| 3951 | status=400, |
| 3952 | ) |
| 3953 | return |
| 3954 | |
| 3955 | started_at = time.perf_counter() |
| 3956 | try: |
| 3957 | summary = object_records.compact_collection(collection, base_dir=_data_dir()) |
| 3958 | except OSError as exc: |
| 3959 | await _send_json( |
| 3960 | send, |
| 3961 | {"status": "error", "error": f"Could not compact collection: {exc}"}, |
| 3962 | status=500, |
| 3963 | ) |
| 3964 | return |
| 3965 | duration_ms = (time.perf_counter() - started_at) * 1000 |
| 3966 | |
| 3967 | await _send_json( |
| 3968 | send, |
| 3969 | { |
| 3970 | "status": "ok", |
| 3971 | "collection": collection, |
| 3972 | **summary, |
| 3973 | "duration_ms": duration_ms, |
| 3974 | }, |
| 3975 | ) |
| 3976 | |
| 3977 | |
| 3978 | async def _handle_admin_changes( |
| 3979 | send, |
| 3980 | method: str, |
| 3981 | query: dict[str, str], |
| 3982 | headers: dict[str, str], |
| 3983 | ) -> None: |
| 3984 | if method != "GET": |
| 3985 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 3986 | return |
| 3987 | |
| 3988 | gate_error = _admin_token_gate_error( |
| 3989 | headers, |
| 3990 | f"Admin change history requires {ADMIN_TOKEN_ENV}.", |
| 3991 | ) |
| 3992 | if gate_error is not None: |
| 3993 | status, message = gate_error |
| 3994 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 3995 | return |
| 3996 | |
| 3997 | try: |
| 3998 | limit = _query_int( |
| 3999 | query, |
| 4000 | "limit", |
| 4001 | default=100, |
| 4002 | minimum=1, |
| 4003 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 4004 | ) |
| 4005 | offset = _query_int( |
| 4006 | query, |
| 4007 | "offset", |
| 4008 | default=0, |
| 4009 | minimum=0, |
| 4010 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 4011 | ) |
| 4012 | payload = _admin_changes_payload(query, limit=limit, offset=offset) |
| 4013 | except ValueError as exc: |
| 4014 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4015 | return |
| 4016 | except (InvalidObjectIdError, object_collections.InvalidCollectionNameError) as exc: |
| 4017 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4018 | return |
| 4019 | except (object_records.InvalidRecordIdError, object_packages.InvalidPackageIdError) as exc: |
| 4020 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4021 | return |
| 4022 | except object_file_changes.InvalidFileChangeError as exc: |
| 4023 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4024 | return |
| 4025 | except OSError as exc: |
| 4026 | await _send_json( |
| 4027 | send, |
| 4028 | {"status": "error", "error": f"Could not list admin changes: {exc}"}, |
| 4029 | status=500, |
| 4030 | ) |
| 4031 | return |
| 4032 | |
| 4033 | await _send_json(send, {"status": "ok", **payload}) |
| 4034 | |
| 4035 | |
| 4036 | async def _handle_admin_objects( |
| 4037 | send, |
| 4038 | method: str, |
| 4039 | body: bytes, |
| 4040 | headers: dict[str, str], |
| 4041 | ) -> None: |
| 4042 | if method == "POST": |
| 4043 | await _handle_objects_post(send, body, headers) |
| 4044 | return |
| 4045 | |
| 4046 | if method != "GET": |
| 4047 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4048 | return |
| 4049 | |
| 4050 | gate_error = _admin_token_gate_error( |
| 4051 | headers, |
| 4052 | f"Admin object listing requires {ADMIN_TOKEN_ENV}.", |
| 4053 | ) |
| 4054 | if gate_error is not None: |
| 4055 | status, message = gate_error |
| 4056 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4057 | return |
| 4058 | |
| 4059 | await _send_json(send, _list_objects_payload()) |
| 4060 | |
| 4061 | |
| 4062 | async def _handle_admin_object( |
| 4063 | send, |
| 4064 | method: str, |
| 4065 | object_id: str, |
| 4066 | query: dict[str, str], |
| 4067 | body: bytes, |
| 4068 | headers: dict[str, str], |
| 4069 | ) -> None: |
| 4070 | if method == "PUT" and query.get("source") == "true": |
| 4071 | await _handle_object_source_put(send, object_id, body, headers) |
| 4072 | return |
| 4073 | |
| 4074 | if method != "GET": |
| 4075 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4076 | return |
| 4077 | |
| 4078 | gate_error = _admin_token_gate_error( |
| 4079 | headers, |
| 4080 | f"Admin object inspection requires {ADMIN_TOKEN_ENV}.", |
| 4081 | ) |
| 4082 | if gate_error is not None: |
| 4083 | status, message = gate_error |
| 4084 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4085 | return |
| 4086 | |
| 4087 | if "@" in object_id: |
| 4088 | await _send_json( |
| 4089 | send, |
| 4090 | {"status": "error", "error": "Station routing is not available in admin inspection"}, |
| 4091 | status=400, |
| 4092 | ) |
| 4093 | return |
| 4094 | |
| 4095 | if query.get("source") == "true": |
| 4096 | await _handle_object_source_get(send, object_id) |
| 4097 | return |
| 4098 | |
| 4099 | if query.get("state") == "true": |
| 4100 | await _handle_object_state_get(send, object_id) |
| 4101 | return |
| 4102 | |
| 4103 | if query.get("logs") == "true": |
| 4104 | await _handle_object_logs_get(send, object_id, query) |
| 4105 | return |
| 4106 | |
| 4107 | if query.get("versions") == "true": |
| 4108 | await _handle_object_versions_get(send, object_id, query) |
| 4109 | return |
| 4110 | |
| 4111 | if "version" in query: |
| 4112 | await _handle_object_version_get(send, object_id, query) |
| 4113 | return |
| 4114 | |
| 4115 | if query.get("source_changes") == "true": |
| 4116 | await _handle_object_source_changes_get(send, object_id, query) |
| 4117 | return |
| 4118 | |
| 4119 | if query.get("changes") == "true": |
| 4120 | await _handle_object_changes_get(send, object_id, query) |
| 4121 | return |
| 4122 | |
| 4123 | if query.get("files") == "true": |
| 4124 | await _handle_object_files_get(send, object_id) |
| 4125 | return |
| 4126 | |
| 4127 | if "file" in query: |
| 4128 | await _handle_object_file_get(send, object_id, query) |
| 4129 | return |
| 4130 | |
| 4131 | if query.get("metadata") == "true" or query.get("format") == "json" or not query: |
| 4132 | await _handle_object_metadata_get(send, object_id) |
| 4133 | return |
| 4134 | |
| 4135 | await _send_json( |
| 4136 | send, |
| 4137 | { |
| 4138 | "status": "error", |
| 4139 | "error": "Unsupported admin object inspection query", |
| 4140 | "allowed_queries": [ |
| 4141 | "metadata=true", |
| 4142 | "source=true", |
| 4143 | "state=true", |
| 4144 | "logs=true", |
| 4145 | "versions=true", |
| 4146 | "version=<id>", |
| 4147 | "source_changes=true", |
| 4148 | "changes=true", |
| 4149 | "files=true", |
| 4150 | "file=<name>", |
| 4151 | ], |
| 4152 | }, |
| 4153 | status=400, |
| 4154 | ) |
| 4155 | |
| 4156 | |
| 4157 | async def _handle_admin_object_execute( |
| 4158 | send, |
| 4159 | method: str, |
| 4160 | object_id: str, |
| 4161 | body: bytes, |
| 4162 | headers: dict[str, str], |
| 4163 | ) -> None: |
| 4164 | if method != "POST": |
| 4165 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4166 | return |
| 4167 | |
| 4168 | gate_error = _admin_token_gate_error( |
| 4169 | headers, |
| 4170 | f"Admin object execution requires {ADMIN_TOKEN_ENV}.", |
| 4171 | ) |
| 4172 | if gate_error is not None: |
| 4173 | status, message = gate_error |
| 4174 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4175 | return |
| 4176 | |
| 4177 | if "@" in object_id: |
| 4178 | await _send_json( |
| 4179 | send, |
| 4180 | {"status": "error", "error": "Station routing is not available in admin execution"}, |
| 4181 | status=400, |
| 4182 | ) |
| 4183 | return |
| 4184 | |
| 4185 | try: |
| 4186 | payload = _parse_json_body(body) |
| 4187 | execute_method = _admin_execute_method(payload) |
| 4188 | execute_payload = _admin_execute_payload(payload) |
| 4189 | except ValueError as exc: |
| 4190 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4191 | return |
| 4192 | |
| 4193 | permission_action = object_permissions.EXECUTE |
| 4194 | if execute_method == "PUT": |
| 4195 | permission_action = object_permissions.UPDATE |
| 4196 | elif execute_method == "DELETE": |
| 4197 | permission_action = object_permissions.DELETE |
| 4198 | |
| 4199 | await _execute_object_method( |
| 4200 | send, |
| 4201 | object_id, |
| 4202 | execute_method, |
| 4203 | execute_payload, |
| 4204 | headers, |
| 4205 | permission_action=permission_action, |
| 4206 | ) |
| 4207 | |
| 4208 | |
| 4209 | async def _handle_admin_object_override( |
| 4210 | send, |
| 4211 | method: str, |
| 4212 | object_id: str, |
| 4213 | headers: dict[str, str], |
| 4214 | ) -> None: |
| 4215 | """Create or remove an override that shadows a package object by id. |
| 4216 | |
| 4217 | Overrides are the conflict-free customization path (Rule 2 in |
| 4218 | docs/upgrade-and-customization.md): creating an override here copies the |
| 4219 | *current package* source into the override root so execution and source |
| 4220 | reads/writes resolve to the override from now on, while install/upgrade |
| 4221 | logic keeps operating on the pristine package copy (see |
| 4222 | get_base_object_roots()). This endpoint requires DBBASIC_OVERRIDES_DIR to |
| 4223 | be configured; when it is unset the whole override subsystem is inert. |
| 4224 | """ |
| 4225 | if method not in ("POST", "DELETE"): |
| 4226 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4227 | return |
| 4228 | |
| 4229 | # Creating/removing an override mutates what a source read/write and |
| 4230 | # execution resolve to, so it is gated exactly like a direct source |
| 4231 | # write (admin token + DBBASIC_ENABLE_SOURCE_WRITES). |
| 4232 | gate_error = _source_write_gate_error(headers) |
| 4233 | if gate_error is not None: |
| 4234 | status, message = gate_error |
| 4235 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4236 | return |
| 4237 | |
| 4238 | if not validate_object_id(object_id): |
| 4239 | await _send_json(send, {"status": "error", "error": f"Invalid object id: {object_id}"}, status=400) |
| 4240 | return |
| 4241 | |
| 4242 | if get_override_root() is None: |
| 4243 | await _send_json( |
| 4244 | send, |
| 4245 | { |
| 4246 | "status": "error", |
| 4247 | "error": f"Overrides are not enabled; set {object_namespace.OVERRIDES_DIR_ENV}", |
| 4248 | }, |
| 4249 | status=400, |
| 4250 | ) |
| 4251 | return |
| 4252 | |
| 4253 | dest = object_namespace.override_path(object_id) |
| 4254 | if dest is None: |
| 4255 | await _send_json( |
| 4256 | send, |
| 4257 | {"status": "error", "error": f"Object id does not support overrides: {object_id}"}, |
| 4258 | status=400, |
| 4259 | ) |
| 4260 | return |
| 4261 | |
| 4262 | if method == "POST": |
| 4263 | try: |
| 4264 | source = object_source.get_object_source(object_id, get_base_object_roots()) |
| 4265 | except InvalidObjectIdError as exc: |
| 4266 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4267 | return |
| 4268 | except object_source.ObjectSourceNotFoundError as exc: |
| 4269 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 4270 | return |
| 4271 | |
| 4272 | if dest.exists(): |
| 4273 | await _send_json( |
| 4274 | send, |
| 4275 | {"status": "error", "error": f"Override already exists: {object_id}"}, |
| 4276 | status=409, |
| 4277 | ) |
| 4278 | return |
| 4279 | |
| 4280 | _write_bytes_atomic(dest, source.encode("utf-8")) |
| 4281 | await _send_json( |
| 4282 | send, |
| 4283 | { |
| 4284 | "status": "ok", |
| 4285 | "object_id": object_id, |
| 4286 | "override_path": str(dest), |
| 4287 | "created": True, |
| 4288 | }, |
| 4289 | ) |
| 4290 | return |
| 4291 | |
| 4292 | # DELETE: remove the override so resolution falls back to the package copy. |
| 4293 | if not dest.is_file(): |
| 4294 | await _send_json( |
| 4295 | send, |
| 4296 | {"status": "error", "error": f"No override exists: {object_id}"}, |
| 4297 | status=404, |
| 4298 | ) |
| 4299 | return |
| 4300 | |
| 4301 | dest.unlink() |
| 4302 | await _send_json( |
| 4303 | send, |
| 4304 | { |
| 4305 | "status": "ok", |
| 4306 | "object_id": object_id, |
| 4307 | "removed": True, |
| 4308 | }, |
| 4309 | ) |
| 4310 | |
| 4311 | |
| 4312 | def _write_bytes_atomic(path: Path, content: bytes) -> None: |
| 4313 | path.parent.mkdir(parents=True, exist_ok=True) |
| 4314 | tmp_name = "" |
| 4315 | try: |
| 4316 | with tempfile.NamedTemporaryFile( |
| 4317 | "wb", |
| 4318 | dir=path.parent, |
| 4319 | prefix=f".{path.name}.", |
| 4320 | suffix=".tmp", |
| 4321 | delete=False, |
| 4322 | ) as tmp: |
| 4323 | tmp_name = tmp.name |
| 4324 | tmp.write(content) |
| 4325 | tmp.flush() |
| 4326 | os.fsync(tmp.fileno()) |
| 4327 | os.replace(tmp_name, path) |
| 4328 | finally: |
| 4329 | if tmp_name: |
| 4330 | try: |
| 4331 | Path(tmp_name).unlink() |
| 4332 | except FileNotFoundError: |
| 4333 | pass |
| 4334 | |
| 4335 | |
| 4336 | async def _handle_admin_files( |
| 4337 | send, |
| 4338 | method: str, |
| 4339 | query: dict[str, str], |
| 4340 | headers: dict[str, str], |
| 4341 | ) -> None: |
| 4342 | if method != "GET": |
| 4343 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4344 | return |
| 4345 | |
| 4346 | gate_error = _admin_token_gate_error( |
| 4347 | headers, |
| 4348 | f"Admin file inspection requires {ADMIN_TOKEN_ENV}.", |
| 4349 | ) |
| 4350 | if gate_error is not None: |
| 4351 | status, message = gate_error |
| 4352 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4353 | return |
| 4354 | |
| 4355 | object_id = _optional_query_text(query, "object_id") |
| 4356 | if "file" in query: |
| 4357 | if object_id is None: |
| 4358 | await _send_json( |
| 4359 | send, |
| 4360 | {"status": "error", "error": "Query parameter 'object_id' is required"}, |
| 4361 | status=400, |
| 4362 | ) |
| 4363 | return |
| 4364 | await _handle_object_file_get(send, object_id, query) |
| 4365 | return |
| 4366 | |
| 4367 | try: |
| 4368 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 4369 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 4370 | if object_id is not None: |
| 4371 | _ensure_object_source_exists(object_id) |
| 4372 | files = object_files.list_all_object_files( |
| 4373 | base_dir=_data_dir(), |
| 4374 | object_id=object_id, |
| 4375 | ) |
| 4376 | except ValueError as exc: |
| 4377 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4378 | return |
| 4379 | except InvalidObjectIdError as exc: |
| 4380 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4381 | return |
| 4382 | except object_source.ObjectSourceNotFoundError as exc: |
| 4383 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 4384 | return |
| 4385 | except OSError as exc: |
| 4386 | await _send_json( |
| 4387 | send, |
| 4388 | {"status": "error", "error": f"Could not read object files: {exc}"}, |
| 4389 | status=500, |
| 4390 | ) |
| 4391 | return |
| 4392 | |
| 4393 | page = files[offset : offset + limit] |
| 4394 | await _send_json( |
| 4395 | send, |
| 4396 | { |
| 4397 | "status": "ok", |
| 4398 | "files": page, |
| 4399 | "count": len(page), |
| 4400 | "total": len(files), |
| 4401 | }, |
| 4402 | ) |
| 4403 | |
| 4404 | |
| 4405 | async def _handle_admin_object_files( |
| 4406 | send, |
| 4407 | method: str, |
| 4408 | object_id: str, |
| 4409 | query: dict[str, str], |
| 4410 | body: bytes, |
| 4411 | headers: dict[str, str], |
| 4412 | ) -> None: |
| 4413 | if method not in {"GET", "POST", "PUT", "DELETE"}: |
| 4414 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4415 | return |
| 4416 | |
| 4417 | if "@" in object_id: |
| 4418 | await _send_json( |
| 4419 | send, |
| 4420 | {"status": "error", "error": "Station routing is not available in admin inspection"}, |
| 4421 | status=400, |
| 4422 | ) |
| 4423 | return |
| 4424 | |
| 4425 | if method in {"POST", "PUT", "DELETE"}: |
| 4426 | await _handle_admin_object_file_write(send, method, object_id, query, body, headers) |
| 4427 | return |
| 4428 | |
| 4429 | gate_error = _admin_token_gate_error( |
| 4430 | headers, |
| 4431 | f"Admin file inspection requires {ADMIN_TOKEN_ENV}.", |
| 4432 | ) |
| 4433 | if gate_error is not None: |
| 4434 | status, message = gate_error |
| 4435 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4436 | return |
| 4437 | |
| 4438 | if "file" in query: |
| 4439 | await _handle_object_file_get(send, object_id, query) |
| 4440 | return |
| 4441 | |
| 4442 | await _handle_object_files_get(send, object_id) |
| 4443 | |
| 4444 | |
| 4445 | async def _handle_admin_object_file_write( |
| 4446 | send, |
| 4447 | method: str, |
| 4448 | object_id: str, |
| 4449 | query: dict[str, str], |
| 4450 | body: bytes, |
| 4451 | headers: dict[str, str], |
| 4452 | ) -> None: |
| 4453 | gate_error = _file_write_gate_error(headers) |
| 4454 | if gate_error is not None: |
| 4455 | status, message = gate_error |
| 4456 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4457 | return |
| 4458 | |
| 4459 | if await _send_permission_denied_if_needed( |
| 4460 | send, |
| 4461 | headers, |
| 4462 | object_permissions.FILES, |
| 4463 | object_id=object_id, |
| 4464 | method=method, |
| 4465 | ): |
| 4466 | return |
| 4467 | |
| 4468 | try: |
| 4469 | _ensure_object_source_exists(object_id) |
| 4470 | if method in {"POST", "PUT"}: |
| 4471 | filename, content = _file_write_payload(body) |
| 4472 | metadata = object_files.write_object_file( |
| 4473 | object_id, |
| 4474 | filename, |
| 4475 | content, |
| 4476 | base_dir=_data_dir(), |
| 4477 | overwrite=method == "PUT", |
| 4478 | max_bytes=_max_object_file_bytes(), |
| 4479 | ) |
| 4480 | operation = "created" if method == "POST" else "updated" |
| 4481 | status_code = 201 if method == "POST" else 200 |
| 4482 | else: |
| 4483 | filename = _file_delete_filename(query, body) |
| 4484 | metadata = object_files.delete_object_file( |
| 4485 | object_id, |
| 4486 | filename, |
| 4487 | base_dir=_data_dir(), |
| 4488 | ) |
| 4489 | operation = "deleted" |
| 4490 | status_code = 200 |
| 4491 | except object_files.ObjectFileTooLargeError as exc: |
| 4492 | await _send_json(send, {"status": "error", "error": str(exc)}, status=413) |
| 4493 | return |
| 4494 | except ValueError as exc: |
| 4495 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4496 | return |
| 4497 | except InvalidObjectIdError as exc: |
| 4498 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4499 | return |
| 4500 | except object_files.InvalidObjectFilenameError as exc: |
| 4501 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4502 | return |
| 4503 | except object_source.ObjectSourceNotFoundError as exc: |
| 4504 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 4505 | return |
| 4506 | except object_files.ObjectFileExistsError as exc: |
| 4507 | await _send_json(send, {"status": "error", "error": str(exc)}, status=409) |
| 4508 | return |
| 4509 | except object_files.ObjectFileNotFoundError as exc: |
| 4510 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 4511 | return |
| 4512 | except OSError as exc: |
| 4513 | await _send_json( |
| 4514 | send, |
| 4515 | {"status": "error", "error": f"Could not write object file: {exc}"}, |
| 4516 | status=500, |
| 4517 | ) |
| 4518 | return |
| 4519 | |
| 4520 | correlation_id = object_correlation.current_correlation_id() |
| 4521 | _append_file_log(object_id, operation=operation, metadata=metadata, method=method) |
| 4522 | change = _append_file_change_log( |
| 4523 | object_id, |
| 4524 | operation=operation, |
| 4525 | metadata=metadata, |
| 4526 | method=method, |
| 4527 | actor=_record_change_actor(headers), |
| 4528 | correlation_id=correlation_id, |
| 4529 | ) |
| 4530 | payload = { |
| 4531 | "status": "ok", |
| 4532 | "message": f"File {operation}: {metadata['name']}", |
| 4533 | "object_id": object_id, |
| 4534 | "operation": operation, |
| 4535 | "file": {"object_id": object_id, **metadata}, |
| 4536 | "correlation_id": correlation_id, |
| 4537 | } |
| 4538 | if change is not None: |
| 4539 | payload["change"] = change |
| 4540 | |
| 4541 | await _send_json(send, payload, status=status_code) |
| 4542 | |
| 4543 | |
| 4544 | async def _handle_admin_reconciles( |
| 4545 | send, |
| 4546 | method: str, |
| 4547 | query: dict[str, str], |
| 4548 | headers: dict[str, str], |
| 4549 | ) -> None: |
| 4550 | if method != "GET": |
| 4551 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4552 | return |
| 4553 | |
| 4554 | gate_error = _admin_token_gate_error( |
| 4555 | headers, |
| 4556 | f"Reconcile listing requires {ADMIN_TOKEN_ENV}.", |
| 4557 | ) |
| 4558 | if gate_error is not None: |
| 4559 | status, message = gate_error |
| 4560 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4561 | return |
| 4562 | |
| 4563 | reconciles = object_reconciles.list_reconciles( |
| 4564 | base_dir=_data_dir(), |
| 4565 | status=_optional_query_text(query, "status"), |
| 4566 | package=_optional_query_text(query, "package"), |
| 4567 | ) |
| 4568 | await _send_json( |
| 4569 | send, |
| 4570 | { |
| 4571 | "status": "ok", |
| 4572 | "reconciles": reconciles, |
| 4573 | "count": len(reconciles), |
| 4574 | }, |
| 4575 | ) |
| 4576 | |
| 4577 | |
| 4578 | async def _handle_admin_reconcile( |
| 4579 | send, |
| 4580 | method: str, |
| 4581 | reconcile_id: str, |
| 4582 | headers: dict[str, str], |
| 4583 | ) -> None: |
| 4584 | if method != "GET": |
| 4585 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4586 | return |
| 4587 | |
| 4588 | gate_error = _admin_token_gate_error( |
| 4589 | headers, |
| 4590 | f"Reconcile detail requires {ADMIN_TOKEN_ENV}.", |
| 4591 | ) |
| 4592 | if gate_error is not None: |
| 4593 | status, message = gate_error |
| 4594 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4595 | return |
| 4596 | |
| 4597 | if not object_reconciles.validate_reconcile_id(reconcile_id): |
| 4598 | await _send_json(send, {"status": "error", "error": f"Invalid reconcile id: {reconcile_id}"}, status=400) |
| 4599 | return |
| 4600 | |
| 4601 | reconcile = object_reconciles.get_reconcile(reconcile_id, base_dir=_data_dir()) |
| 4602 | if reconcile is None: |
| 4603 | await _send_json(send, {"status": "error", "error": f"Reconcile not found: {reconcile_id}"}, status=404) |
| 4604 | return |
| 4605 | |
| 4606 | await _send_json(send, {"status": "ok", "reconcile": reconcile}) |
| 4607 | |
| 4608 | |
| 4609 | async def _handle_admin_reconcile_resolve( |
| 4610 | send, |
| 4611 | method: str, |
| 4612 | reconcile_id: str, |
| 4613 | body: bytes, |
| 4614 | headers: dict[str, str], |
| 4615 | ) -> None: |
| 4616 | if method != "POST": |
| 4617 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4618 | return |
| 4619 | |
| 4620 | gate_error = _admin_token_gate_error( |
| 4621 | headers, |
| 4622 | f"Reconcile resolution requires {ADMIN_TOKEN_ENV}.", |
| 4623 | ) |
| 4624 | if gate_error is not None: |
| 4625 | status, message = gate_error |
| 4626 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4627 | return |
| 4628 | |
| 4629 | # Resolving "take theirs" can write to live object source, so it needs the |
| 4630 | # same gate as any other source write, in addition to the admin gate above. |
| 4631 | gate_error = _source_write_gate_error(headers) |
| 4632 | if gate_error is not None: |
| 4633 | status, message = gate_error |
| 4634 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4635 | return |
| 4636 | |
| 4637 | if not object_reconciles.validate_reconcile_id(reconcile_id): |
| 4638 | await _send_json(send, {"status": "error", "error": f"Invalid reconcile id: {reconcile_id}"}, status=400) |
| 4639 | return |
| 4640 | |
| 4641 | try: |
| 4642 | payload = _parse_json_body(body) |
| 4643 | except ValueError as exc: |
| 4644 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4645 | return |
| 4646 | |
| 4647 | choice = payload.get("choice") |
| 4648 | if not isinstance(choice, str) or choice not in object_reconciles.RECONCILE_CHOICES: |
| 4649 | await _send_json( |
| 4650 | send, |
| 4651 | { |
| 4652 | "status": "error", |
| 4653 | "error": "Request JSON field 'choice' must be one of: " |
| 4654 | + ", ".join(object_reconciles.RECONCILE_CHOICES), |
| 4655 | }, |
| 4656 | status=400, |
| 4657 | ) |
| 4658 | return |
| 4659 | |
| 4660 | try: |
| 4661 | reconcile = object_reconciles.resolve_reconcile( |
| 4662 | reconcile_id, |
| 4663 | choice, |
| 4664 | base_dir=_data_dir(), |
| 4665 | object_roots=get_base_object_roots(), |
| 4666 | resolved_at=_utc_timestamp(), |
| 4667 | ) |
| 4668 | except object_source.ObjectSourceNotFoundError as exc: |
| 4669 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 4670 | return |
| 4671 | except (InvalidObjectIdError, object_schemas.InvalidSchemaNameError, ValueError) as exc: |
| 4672 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4673 | return |
| 4674 | |
| 4675 | await _send_json(send, {"status": "ok", "reconcile": reconcile}) |
| 4676 | |
| 4677 | |
| 4678 | async def _handle_admin_collections( |
| 4679 | send, |
| 4680 | method: str, |
| 4681 | headers: dict[str, str], |
| 4682 | ) -> None: |
| 4683 | if method != "GET": |
| 4684 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4685 | return |
| 4686 | |
| 4687 | gate_error = _admin_token_gate_error( |
| 4688 | headers, |
| 4689 | f"Admin collection listing requires {ADMIN_TOKEN_ENV}.", |
| 4690 | ) |
| 4691 | if gate_error is not None: |
| 4692 | status, message = gate_error |
| 4693 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4694 | return |
| 4695 | |
| 4696 | await _handle_collections(send, method, headers) |
| 4697 | |
| 4698 | |
| 4699 | async def _handle_admin_collection( |
| 4700 | send, |
| 4701 | method: str, |
| 4702 | collection_tail: str, |
| 4703 | query: dict[str, str], |
| 4704 | body: bytes, |
| 4705 | headers: dict[str, str], |
| 4706 | ) -> None: |
| 4707 | parts = collection_tail.split("/") |
| 4708 | |
| 4709 | if method == "POST" and len(parts) == 2 and parts[1] == "records": |
| 4710 | await _handle_collection_record_create(send, parts[0], body, headers) |
| 4711 | return |
| 4712 | |
| 4713 | if method == "PUT" and len(parts) == 3 and parts[1] == "records": |
| 4714 | await _handle_collection_record_update(send, parts[0], parts[2], body, headers) |
| 4715 | return |
| 4716 | |
| 4717 | if method == "DELETE" and len(parts) == 3 and parts[1] == "records": |
| 4718 | await _handle_collection_record_delete(send, parts[0], parts[2], headers) |
| 4719 | return |
| 4720 | |
| 4721 | if method == "POST" and len(parts) == 2 and parts[1] == "compact": |
| 4722 | await _handle_admin_collection_compact(send, parts[0], headers) |
| 4723 | return |
| 4724 | |
| 4725 | if method != "GET": |
| 4726 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4727 | return |
| 4728 | |
| 4729 | gate_error = _admin_token_gate_error( |
| 4730 | headers, |
| 4731 | f"Admin collection inspection requires {ADMIN_TOKEN_ENV}.", |
| 4732 | ) |
| 4733 | if gate_error is not None: |
| 4734 | status, message = gate_error |
| 4735 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4736 | return |
| 4737 | |
| 4738 | if len(parts) == 2 and parts[1] == "changes": |
| 4739 | await _handle_collection_changes(send, method, parts[0], query, headers) |
| 4740 | return |
| 4741 | |
| 4742 | if len(parts) == 2 and parts[1] == "records": |
| 4743 | await _handle_collection_records_get(send, parts[0], query, headers) |
| 4744 | return |
| 4745 | |
| 4746 | if len(parts) == 4 and parts[1] == "records" and parts[3] == "changes": |
| 4747 | await _handle_collection_record_changes(send, method, parts[0], parts[2], query, headers) |
| 4748 | return |
| 4749 | |
| 4750 | if len(parts) == 3 and parts[1] == "records": |
| 4751 | await _handle_collection_record_get(send, parts[0], parts[2], headers) |
| 4752 | return |
| 4753 | |
| 4754 | if len(parts) == 1: |
| 4755 | await _handle_collection_get(send, method, collection_tail, headers) |
| 4756 | return |
| 4757 | |
| 4758 | await _send_json( |
| 4759 | send, |
| 4760 | { |
| 4761 | "status": "error", |
| 4762 | "error": "Unsupported admin collection inspection path", |
| 4763 | "allowed_paths": [ |
| 4764 | "/admin/collections/{collection}", |
| 4765 | "/admin/collections/{collection}/records", |
| 4766 | "/admin/collections/{collection}/records/{record_id}", |
| 4767 | "/admin/collections/{collection}/changes", |
| 4768 | "/admin/collections/{collection}/records/{record_id}/changes", |
| 4769 | "/admin/collections/{collection}/compact", |
| 4770 | ], |
| 4771 | }, |
| 4772 | status=400, |
| 4773 | ) |
| 4774 | |
| 4775 | |
| 4776 | async def _handle_admin_schemas( |
| 4777 | send, |
| 4778 | method: str, |
| 4779 | headers: dict[str, str], |
| 4780 | ) -> None: |
| 4781 | if method != "GET": |
| 4782 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4783 | return |
| 4784 | |
| 4785 | gate_error = _admin_token_gate_error( |
| 4786 | headers, |
| 4787 | f"Admin schema listing requires {ADMIN_TOKEN_ENV}.", |
| 4788 | ) |
| 4789 | if gate_error is not None: |
| 4790 | status, message = gate_error |
| 4791 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4792 | return |
| 4793 | |
| 4794 | await _handle_schemas(send, method, headers) |
| 4795 | |
| 4796 | |
| 4797 | async def _handle_admin_schema( |
| 4798 | send, |
| 4799 | method: str, |
| 4800 | schema: str, |
| 4801 | query: dict[str, str], |
| 4802 | body: bytes, |
| 4803 | headers: dict[str, str], |
| 4804 | ) -> None: |
| 4805 | if method == "PUT": |
| 4806 | await _handle_schema_put(send, schema, body, headers) |
| 4807 | return |
| 4808 | |
| 4809 | if method == "POST": |
| 4810 | await _handle_schema_post(send, schema, body, headers) |
| 4811 | return |
| 4812 | |
| 4813 | if method != "GET": |
| 4814 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4815 | return |
| 4816 | |
| 4817 | gate_error = _admin_token_gate_error( |
| 4818 | headers, |
| 4819 | f"Admin schema inspection requires {ADMIN_TOKEN_ENV}.", |
| 4820 | ) |
| 4821 | if gate_error is not None: |
| 4822 | status, message = gate_error |
| 4823 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4824 | return |
| 4825 | |
| 4826 | supported_schema_keys = {"format", "limit", "version", "versions"} |
| 4827 | only_format = set(query).issubset({"format"}) |
| 4828 | supported = set(query).issubset(supported_schema_keys) and ( |
| 4829 | not query or only_format or query.get("versions") == "true" or "version" in query |
| 4830 | ) |
| 4831 | if not supported: |
| 4832 | await _send_json( |
| 4833 | send, |
| 4834 | { |
| 4835 | "status": "error", |
| 4836 | "error": "Unsupported admin schema inspection query", |
| 4837 | "allowed_queries": ["versions=true", "version=<id>"], |
| 4838 | }, |
| 4839 | status=400, |
| 4840 | ) |
| 4841 | return |
| 4842 | |
| 4843 | await _handle_schema(send, method, schema, query, b"", headers) |
| 4844 | |
| 4845 | |
| 4846 | async def _handle_admin_identity_accounts( |
| 4847 | send, |
| 4848 | method: str, |
| 4849 | headers: dict[str, str], |
| 4850 | ) -> None: |
| 4851 | if method != "GET": |
| 4852 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4853 | return |
| 4854 | |
| 4855 | await _handle_identity_accounts(send, method, b"", headers) |
| 4856 | |
| 4857 | |
| 4858 | async def _handle_admin_identity_account( |
| 4859 | send, |
| 4860 | method: str, |
| 4861 | account_id: str, |
| 4862 | headers: dict[str, str], |
| 4863 | ) -> None: |
| 4864 | if method != "GET": |
| 4865 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4866 | return |
| 4867 | |
| 4868 | await _handle_identity_account(send, method, account_id, headers) |
| 4869 | |
| 4870 | |
| 4871 | async def _handle_admin_identity_users( |
| 4872 | send, |
| 4873 | method: str, |
| 4874 | query: dict[str, str], |
| 4875 | headers: dict[str, str], |
| 4876 | ) -> None: |
| 4877 | if method != "GET": |
| 4878 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4879 | return |
| 4880 | |
| 4881 | await _handle_identity_users(send, method, query, b"", headers) |
| 4882 | |
| 4883 | |
| 4884 | async def _handle_admin_identity_user( |
| 4885 | send, |
| 4886 | method: str, |
| 4887 | user_id: str, |
| 4888 | body: bytes, |
| 4889 | headers: dict[str, str], |
| 4890 | ) -> None: |
| 4891 | if user_id.endswith("/password") and method in {"POST", "DELETE"}: |
| 4892 | await _handle_identity_user(send, method, user_id, body, headers) |
| 4893 | return |
| 4894 | |
| 4895 | if method != "GET": |
| 4896 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4897 | return |
| 4898 | |
| 4899 | await _handle_identity_user(send, method, user_id, b"", headers) |
| 4900 | |
| 4901 | |
| 4902 | async def _handle_admin_identity_sessions( |
| 4903 | send, |
| 4904 | method: str, |
| 4905 | headers: dict[str, str], |
| 4906 | ) -> None: |
| 4907 | if method != "GET": |
| 4908 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4909 | return |
| 4910 | |
| 4911 | await _handle_identity_sessions(send, method, b"", headers) |
| 4912 | |
| 4913 | |
| 4914 | async def _handle_admin_identity_session( |
| 4915 | send, |
| 4916 | method: str, |
| 4917 | session_id: str, |
| 4918 | headers: dict[str, str], |
| 4919 | ) -> None: |
| 4920 | if method != "GET": |
| 4921 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4922 | return |
| 4923 | |
| 4924 | await _handle_identity_session(send, method, session_id, headers) |
| 4925 | |
| 4926 | |
| 4927 | async def _handle_admin_identity_sources_forget( |
| 4928 | send, |
| 4929 | method: str, |
| 4930 | body: bytes, |
| 4931 | headers: dict[str, str], |
| 4932 | ) -> None: |
| 4933 | """Drop cached identity-source answers so a revocation takes effect now. |
| 4934 | |
| 4935 | Body: {"token_hash": "<sha256 hex of the Authorization header value>"} |
| 4936 | or {"all": true}. Raw tokens are never accepted, logged or echoed. |
| 4937 | """ |
| 4938 | if method != "POST": |
| 4939 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4940 | return |
| 4941 | gate_error = _admin_token_gate_error( |
| 4942 | headers, f"Forgetting identity cache entries requires {ADMIN_TOKEN_ENV}." |
| 4943 | ) |
| 4944 | if gate_error is not None: |
| 4945 | status, message = gate_error |
| 4946 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4947 | return |
| 4948 | try: |
| 4949 | payload = _parse_json_body(body) |
| 4950 | except ValueError as exc: |
| 4951 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 4952 | return |
| 4953 | token_hash = payload.get("token_hash") |
| 4954 | forget_all = payload.get("all") is True |
| 4955 | valid_hash = isinstance(token_hash, str) and re.fullmatch(r"[0-9a-f]{64}", token_hash) |
| 4956 | if forget_all == bool(valid_hash) or set(payload) - {"token_hash", "all"}: |
| 4957 | await _send_json( |
| 4958 | send, |
| 4959 | { |
| 4960 | "status": "error", |
| 4961 | "error": 'Send exactly one of {"token_hash": "<64 hex chars>"} or {"all": true}', |
| 4962 | }, |
| 4963 | status=400, |
| 4964 | ) |
| 4965 | return |
| 4966 | forgotten = await asyncio.to_thread( |
| 4967 | object_identity_sources.forget, None if forget_all else token_hash |
| 4968 | ) |
| 4969 | await _send_json(send, {"status": "ok", "forgotten": forgotten}) |
| 4970 | |
| 4971 | |
| 4972 | async def _handle_daemon_status( |
| 4973 | send, |
| 4974 | method: str, |
| 4975 | headers: dict[str, str], |
| 4976 | ) -> None: |
| 4977 | if method != "GET": |
| 4978 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 4979 | return |
| 4980 | |
| 4981 | gate_error = _admin_token_gate_error( |
| 4982 | headers, |
| 4983 | f"Daemon status requires {ADMIN_TOKEN_ENV}.", |
| 4984 | ) |
| 4985 | if gate_error is not None: |
| 4986 | status, message = gate_error |
| 4987 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 4988 | return |
| 4989 | |
| 4990 | try: |
| 4991 | payload = object_daemon_status.daemon_status( |
| 4992 | base_dir=_data_dir(), |
| 4993 | rate_limit_dir=_rate_limit_dir(), |
| 4994 | event_keep_count=_event_keep_count(), |
| 4995 | event_keep_seconds=_event_keep_seconds(), |
| 4996 | ) |
| 4997 | except OSError as exc: |
| 4998 | await _send_json( |
| 4999 | send, |
| 5000 | {"status": "error", "error": f"Could not build daemon status: {exc}"}, |
| 5001 | status=500, |
| 5002 | ) |
| 5003 | return |
| 5004 | |
| 5005 | await _send_json(send, payload) |
| 5006 | |
| 5007 | |
| 5008 | async def _handle_daemon_scheduler_tasks( |
| 5009 | send, |
| 5010 | method: str, |
| 5011 | query: dict[str, str], |
| 5012 | body: bytes, |
| 5013 | headers: dict[str, str], |
| 5014 | ) -> None: |
| 5015 | gate_error = _admin_token_gate_error(headers, f"Daemon scheduler controls require {ADMIN_TOKEN_ENV}.") |
| 5016 | if gate_error is not None: |
| 5017 | status, message = gate_error |
| 5018 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5019 | return |
| 5020 | |
| 5021 | if method == "GET": |
| 5022 | try: |
| 5023 | tasks = object_daemon_control.list_scheduler_tasks( |
| 5024 | base_dir=_data_dir(), |
| 5025 | status=_optional_query_text(query, "status"), |
| 5026 | limit=_query_int(query, "limit", default=100, minimum=1, maximum=1000), |
| 5027 | offset=_query_int(query, "offset", default=0, minimum=0), |
| 5028 | include_payload=_optional_query_bool(query, "include_payload") is True, |
| 5029 | ) |
| 5030 | except (object_daemon_control.DaemonControlError, ValueError) as exc: |
| 5031 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5032 | return |
| 5033 | except OSError as exc: |
| 5034 | await _send_json( |
| 5035 | send, |
| 5036 | {"status": "error", "error": f"Could not read scheduler tasks: {exc}"}, |
| 5037 | status=500, |
| 5038 | ) |
| 5039 | return |
| 5040 | |
| 5041 | await _send_json(send, {"status": "ok", **tasks}) |
| 5042 | return |
| 5043 | |
| 5044 | if method == "POST": |
| 5045 | try: |
| 5046 | task = object_daemon_control.create_scheduler_task( |
| 5047 | _parse_json_body(body), |
| 5048 | actor=_record_change_actor(headers), |
| 5049 | base_dir=_data_dir(), |
| 5050 | include_payload=_optional_query_bool(query, "include_payload") is True, |
| 5051 | ) |
| 5052 | except ( |
| 5053 | object_daemon_control.DaemonControlError, |
| 5054 | InvalidObjectIdError, |
| 5055 | ValueError, |
| 5056 | ) as exc: |
| 5057 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5058 | return |
| 5059 | except OSError as exc: |
| 5060 | await _send_json( |
| 5061 | send, |
| 5062 | {"status": "error", "error": f"Could not create scheduler task: {exc}"}, |
| 5063 | status=500, |
| 5064 | ) |
| 5065 | return |
| 5066 | |
| 5067 | await _send_json(send, {"status": "ok", "task": task}, status=201) |
| 5068 | return |
| 5069 | |
| 5070 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5071 | |
| 5072 | |
| 5073 | async def _handle_daemon_scheduler_task( |
| 5074 | send, |
| 5075 | method: str, |
| 5076 | task_id: str, |
| 5077 | body: bytes, |
| 5078 | headers: dict[str, str], |
| 5079 | ) -> None: |
| 5080 | gate_error = _admin_token_gate_error(headers, f"Daemon scheduler controls require {ADMIN_TOKEN_ENV}.") |
| 5081 | if gate_error is not None: |
| 5082 | status, message = gate_error |
| 5083 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5084 | return |
| 5085 | |
| 5086 | clean_task_id = urllib.parse.unquote(task_id) |
| 5087 | if method in {"PATCH", "PUT"}: |
| 5088 | try: |
| 5089 | task = object_daemon_control.update_scheduler_task( |
| 5090 | clean_task_id, |
| 5091 | _parse_json_body(body), |
| 5092 | actor=_record_change_actor(headers), |
| 5093 | base_dir=_data_dir(), |
| 5094 | ) |
| 5095 | except ( |
| 5096 | object_daemon_control.DaemonControlError, |
| 5097 | InvalidObjectIdError, |
| 5098 | ValueError, |
| 5099 | ) as exc: |
| 5100 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5101 | return |
| 5102 | except object_daemon_control.DaemonItemNotFoundError as exc: |
| 5103 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 5104 | return |
| 5105 | except OSError as exc: |
| 5106 | await _send_json( |
| 5107 | send, |
| 5108 | {"status": "error", "error": f"Could not update scheduler task: {exc}"}, |
| 5109 | status=500, |
| 5110 | ) |
| 5111 | return |
| 5112 | |
| 5113 | await _send_json(send, {"status": "ok", "task": task}) |
| 5114 | return |
| 5115 | |
| 5116 | if method == "DELETE": |
| 5117 | try: |
| 5118 | task = object_daemon_control.delete_scheduler_task(clean_task_id, base_dir=_data_dir()) |
| 5119 | except object_daemon_control.DaemonControlError as exc: |
| 5120 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5121 | return |
| 5122 | except object_daemon_control.DaemonItemNotFoundError as exc: |
| 5123 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 5124 | return |
| 5125 | except OSError as exc: |
| 5126 | await _send_json( |
| 5127 | send, |
| 5128 | {"status": "error", "error": f"Could not delete scheduler task: {exc}"}, |
| 5129 | status=500, |
| 5130 | ) |
| 5131 | return |
| 5132 | |
| 5133 | await _send_json(send, {"status": "ok", "deleted": True, "task": task}) |
| 5134 | return |
| 5135 | |
| 5136 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5137 | |
| 5138 | |
| 5139 | async def _handle_daemon_queue_messages( |
| 5140 | send, |
| 5141 | method: str, |
| 5142 | query: dict[str, str], |
| 5143 | body: bytes, |
| 5144 | headers: dict[str, str], |
| 5145 | ) -> None: |
| 5146 | gate_error = _admin_token_gate_error(headers, f"Daemon queue controls require {ADMIN_TOKEN_ENV}.") |
| 5147 | if gate_error is not None: |
| 5148 | status, message = gate_error |
| 5149 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5150 | return |
| 5151 | |
| 5152 | if method == "GET": |
| 5153 | try: |
| 5154 | messages = object_daemon_control.list_queue_messages( |
| 5155 | base_dir=_data_dir(), |
| 5156 | status=_optional_query_text(query, "status"), |
| 5157 | queue_name=_optional_query_text(query, "queue_name"), |
| 5158 | limit=_query_int(query, "limit", default=100, minimum=1, maximum=1000), |
| 5159 | offset=_query_int(query, "offset", default=0, minimum=0), |
| 5160 | include_payload=_optional_query_bool(query, "include_payload") is True, |
| 5161 | ) |
| 5162 | except (object_daemon_control.DaemonControlError, ValueError) as exc: |
| 5163 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5164 | return |
| 5165 | except OSError as exc: |
| 5166 | await _send_json( |
| 5167 | send, |
| 5168 | {"status": "error", "error": f"Could not read queue messages: {exc}"}, |
| 5169 | status=500, |
| 5170 | ) |
| 5171 | return |
| 5172 | |
| 5173 | await _send_json(send, {"status": "ok", **messages}) |
| 5174 | return |
| 5175 | |
| 5176 | if method == "POST": |
| 5177 | try: |
| 5178 | message = object_daemon_control.enqueue_message( |
| 5179 | _parse_json_body(body), |
| 5180 | actor=_record_change_actor(headers), |
| 5181 | base_dir=_data_dir(), |
| 5182 | include_payload=_optional_query_bool(query, "include_payload") is True, |
| 5183 | ) |
| 5184 | except ( |
| 5185 | object_daemon_control.DaemonControlError, |
| 5186 | InvalidObjectIdError, |
| 5187 | ValueError, |
| 5188 | ) as exc: |
| 5189 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5190 | return |
| 5191 | except OSError as exc: |
| 5192 | await _send_json( |
| 5193 | send, |
| 5194 | {"status": "error", "error": f"Could not enqueue message: {exc}"}, |
| 5195 | status=500, |
| 5196 | ) |
| 5197 | return |
| 5198 | |
| 5199 | await _send_json(send, {"status": "ok", "message": message}, status=201) |
| 5200 | return |
| 5201 | |
| 5202 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5203 | |
| 5204 | |
| 5205 | async def _handle_daemon_queue_message( |
| 5206 | send, |
| 5207 | method: str, |
| 5208 | message_id: str, |
| 5209 | body: bytes, |
| 5210 | headers: dict[str, str], |
| 5211 | ) -> None: |
| 5212 | gate_error = _admin_token_gate_error(headers, f"Daemon queue controls require {ADMIN_TOKEN_ENV}.") |
| 5213 | if gate_error is not None: |
| 5214 | status, message = gate_error |
| 5215 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5216 | return |
| 5217 | |
| 5218 | clean_message_id = urllib.parse.unquote(message_id) |
| 5219 | if method in {"PATCH", "PUT"}: |
| 5220 | try: |
| 5221 | message = object_daemon_control.update_queue_message( |
| 5222 | clean_message_id, |
| 5223 | _parse_json_body(body), |
| 5224 | actor=_record_change_actor(headers), |
| 5225 | base_dir=_data_dir(), |
| 5226 | ) |
| 5227 | except (object_daemon_control.DaemonControlError, ValueError) as exc: |
| 5228 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5229 | return |
| 5230 | except object_daemon_control.DaemonItemNotFoundError as exc: |
| 5231 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 5232 | return |
| 5233 | except OSError as exc: |
| 5234 | await _send_json( |
| 5235 | send, |
| 5236 | {"status": "error", "error": f"Could not update queue message: {exc}"}, |
| 5237 | status=500, |
| 5238 | ) |
| 5239 | return |
| 5240 | |
| 5241 | await _send_json(send, {"status": "ok", "message": message}) |
| 5242 | return |
| 5243 | |
| 5244 | if method == "DELETE": |
| 5245 | try: |
| 5246 | message = object_daemon_control.delete_queue_message(clean_message_id, base_dir=_data_dir()) |
| 5247 | except object_daemon_control.DaemonControlError as exc: |
| 5248 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5249 | return |
| 5250 | except object_daemon_control.DaemonItemNotFoundError as exc: |
| 5251 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 5252 | return |
| 5253 | except OSError as exc: |
| 5254 | await _send_json( |
| 5255 | send, |
| 5256 | {"status": "error", "error": f"Could not delete queue message: {exc}"}, |
| 5257 | status=500, |
| 5258 | ) |
| 5259 | return |
| 5260 | |
| 5261 | await _send_json(send, {"status": "ok", "deleted": True, "message": message}) |
| 5262 | return |
| 5263 | |
| 5264 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5265 | |
| 5266 | |
| 5267 | def _admin_status_payload() -> dict[str, Any]: |
| 5268 | health = _health_payload(include_metrics=True) |
| 5269 | # A broken permission policy must not take the console's status page down: |
| 5270 | # the parts that need the policy (collection and schema names, package |
| 5271 | # plans) are marked unavailable instead of guessed, and the alert says why. |
| 5272 | policy_error = _policy_read_error() |
| 5273 | unavailable: list[str] = [] |
| 5274 | collections: list[Any] | None |
| 5275 | schemas: list[Any] | None |
| 5276 | try: |
| 5277 | collections = object_collections.list_collections(base_dir=_data_dir()) |
| 5278 | schemas = object_schemas.list_schemas(base_dir=_data_dir()) |
| 5279 | except (OSError, ValueError): |
| 5280 | if policy_error is None: |
| 5281 | raise |
| 5282 | collections = schemas = None |
| 5283 | unavailable += ["collections", "schemas"] |
| 5284 | try: |
| 5285 | packages = _admin_package_summaries() |
| 5286 | except (OSError, ValueError): |
| 5287 | if policy_error is None: |
| 5288 | raise |
| 5289 | packages = [] |
| 5290 | unavailable.append("packages") |
| 5291 | permissions = _permissions_status_payload() |
| 5292 | |
| 5293 | enforcement_problem = _permission_enforcement_problem() |
| 5294 | scheduled_backups = _scheduled_backups_payload() |
| 5295 | backup_alert = _scheduled_backup_alert(scheduled_backups) |
| 5296 | return { |
| 5297 | "status": health["status"], |
| 5298 | "timestamp": health["timestamp"], |
| 5299 | "version": health["version"], |
| 5300 | "build_commit": _build_commit(), |
| 5301 | "station_id": health["station_id"], |
| 5302 | # Things an operator must read first. Empty when all is well. |
| 5303 | "alerts": [ |
| 5304 | alert |
| 5305 | for alert in ( |
| 5306 | _policy_file_alert(policy_error), |
| 5307 | enforcement_problem, |
| 5308 | backup_alert, |
| 5309 | _login_lockout_alert(), |
| 5310 | _identity_source_alert(), |
| 5311 | _identity_audience_alert(), |
| 5312 | _policy_findings_alert(policy_error), |
| 5313 | ) |
| 5314 | if alert |
| 5315 | ], |
| 5316 | # Last backup and restore test, their ages, and what is wrong. |
| 5317 | "scheduled_backups": scheduled_backups, |
| 5318 | "health": health, |
| 5319 | "inventory": { |
| 5320 | "objects": health["objects"]["count"], |
| 5321 | "collections": None if collections is None else len(collections), |
| 5322 | "schemas": None if schemas is None else len(schemas), |
| 5323 | "packages": None if "packages" in unavailable else len(packages), |
| 5324 | # Counts that need the permission policy are null while it cannot |
| 5325 | # be read, and named here (the key is absent on a healthy box). |
| 5326 | **({"unavailable": unavailable} if unavailable else {}), |
| 5327 | }, |
| 5328 | "capabilities": _admin_capabilities_payload(), |
| 5329 | "packages": packages, |
| 5330 | "permissions": { |
| 5331 | "enforcement_enabled": permissions["permissions"]["enforcement_enabled"], |
| 5332 | "audit_enabled": permissions["permissions"]["audit_enabled"], |
| 5333 | "mode": permissions["permissions"]["mode"], |
| 5334 | "policy": permissions["policy"], |
| 5335 | "readiness": permissions["readiness"], |
| 5336 | "warnings": permissions["warnings"], |
| 5337 | }, |
| 5338 | } |
| 5339 | |
| 5340 | |
| 5341 | def _policy_read_error() -> str | None: |
| 5342 | """Why the permission policy cannot be read right now, or None when it can.""" |
| 5343 | try: |
| 5344 | object_permission_store.load_policy(_data_dir()) |
| 5345 | except (OSError, ValueError) as exc: |
| 5346 | return _policy_unavailable_error(exc) |
| 5347 | return None |
| 5348 | |
| 5349 | |
| 5350 | def _policy_file_alert(policy_error: str | None) -> str | None: |
| 5351 | """The alert for a policy file that cannot be used, in any permission mode.""" |
| 5352 | if policy_error is None: |
| 5353 | return None |
| 5354 | detail = policy_error.split(": ", 1)[1] if ": " in policy_error else policy_error |
| 5355 | what = "could not be read" if policy_error.startswith("Permission policy could not") else "is invalid" |
| 5356 | return ( |
| 5357 | f"Permission policy file {what}: {detail}. Non-admin requests get 503 " |
| 5358 | "permission_policy_unavailable while enforcement is on; repair it with " |
| 5359 | "PUT /permissions/policy (admin token); GET /permissions/policy returns the " |
| 5360 | "file's text." |
| 5361 | ) |
| 5362 | |
| 5363 | |
| 5364 | def _policy_findings_alert(policy_error: str | None) -> str | None: |
| 5365 | """The /admin/status alert while the stored policy holds a DRON mistake |
| 5366 | the engine reads loosely (object_permissions.stored_policy_findings). |
| 5367 | The box goes on deciding exactly as before; this says what that means. |
| 5368 | Names rules by index and package tag and keys, never a rule's reason.""" |
| 5369 | if policy_error is not None: |
| 5370 | return None # the invalid-policy alert says more |
| 5371 | findings = object_permission_store.stored_policy_findings(_data_dir()) |
| 5372 | if not findings: |
| 5373 | return None |
| 5374 | serious = [finding for finding in findings if finding["serious"]] |
| 5375 | if serious: |
| 5376 | shown = "; ".join(object_permissions.finding_text(finding) for finding in serious[:3]) |
| 5377 | more = f" (and {len(serious) - 3} more)" if len(serious) > 3 else "" |
| 5378 | rest = len(findings) - len(serious) |
| 5379 | others = f" {rest} smaller mistake(s) too." if rest else "" |
| 5380 | # A finding with applied False is a widened allow the fail-closed |
| 5381 | # setting has stopped applying (object_permissions.apply_fail_closed). |
| 5382 | stopped = sum(1 for finding in serious if finding.get("applied") is False) |
| 5383 | state = ( |
| 5384 | f"{stopped} allow rule(s) named here are not applied " |
| 5385 | f"({object_permissions.FAIL_CLOSED_WIDENED_ALLOWS_ENV} is on); nothing else was changed." |
| 5386 | if stopped else "Nothing was changed; the box decides as it did." |
| 5387 | ) |
| 5388 | return ( |
| 5389 | f"Permission policy file has {len(serious)} mistake(s) that let it allow MORE than " |
| 5390 | f"written: {shown}{more}.{others} {state} " |
| 5391 | "GET /permissions/status lists each; fix them and PUT /permissions/policy (admin token)." |
| 5392 | ) |
| 5393 | return ( |
| 5394 | f"Permission policy file has {len(findings)} mistake(s) DRON refuses that the engine reads " |
| 5395 | "loosely (none widens access): GET /permissions/status lists each; fix them and " |
| 5396 | "PUT /permissions/policy (admin token)." |
| 5397 | ) |
| 5398 | |
| 5399 | |
| 5400 | def _admin_capabilities_payload() -> dict[str, Any]: |
| 5401 | enforcement_problems = _permission_enforcement_problems() |
| 5402 | return { |
| 5403 | "source_writes": { |
| 5404 | "enabled": _env_enabled(SOURCE_WRITES_ENV), |
| 5405 | "env": SOURCE_WRITES_ENV, |
| 5406 | }, |
| 5407 | "file_writes": { |
| 5408 | "enabled": _env_enabled(FILE_WRITES_ENV), |
| 5409 | "env": FILE_WRITES_ENV, |
| 5410 | "max_bytes": _max_object_file_bytes(), |
| 5411 | "max_bytes_env": MAX_OBJECT_FILE_BYTES_ENV, |
| 5412 | }, |
| 5413 | "package_installs": { |
| 5414 | "enabled": _env_enabled(PACKAGE_INSTALLS_ENABLED_ENV), |
| 5415 | "env": PACKAGE_INSTALLS_ENABLED_ENV, |
| 5416 | }, |
| 5417 | "package_restore": { |
| 5418 | "enabled": _env_enabled(PACKAGE_RESTORE_ENABLED_ENV), |
| 5419 | "env": PACKAGE_RESTORE_ENABLED_ENV, |
| 5420 | }, |
| 5421 | "overrides": { |
| 5422 | "enabled": get_override_root() is not None, |
| 5423 | "env": object_namespace.OVERRIDES_DIR_ENV, |
| 5424 | }, |
| 5425 | "packages": { |
| 5426 | "available": True, |
| 5427 | "can_install": _env_enabled(PACKAGE_INSTALLS_ENABLED_ENV), |
| 5428 | "can_restore": _env_enabled(PACKAGE_RESTORE_ENABLED_ENV), |
| 5429 | "install_env": PACKAGE_INSTALLS_ENABLED_ENV, |
| 5430 | }, |
| 5431 | "backups": { |
| 5432 | "available": True, |
| 5433 | "can_create": True, |
| 5434 | "can_download": True, |
| 5435 | "can_preview": True, |
| 5436 | "can_restore": False, |
| 5437 | **_backup_schedule_payload(), |
| 5438 | }, |
| 5439 | "storage": { |
| 5440 | "append_collections": len( |
| 5441 | object_schemas.list_append_storage_collections(base_dir=_data_dir()) |
| 5442 | ), |
| 5443 | }, |
| 5444 | "permission_enforcement": { |
| 5445 | "enabled": _permission_enforcement_enabled(), |
| 5446 | "requested": _permission_enforcement_requested(), |
| 5447 | # Deprecated, always False: requested enforcement is always effective. |
| 5448 | "blocked": _permission_enforcement_blocked(), |
| 5449 | "mode": _permission_mode(), |
| 5450 | "env": PERMISSION_ENFORCEMENT_ENV, |
| 5451 | "problems": enforcement_problems, |
| 5452 | # Deprecated alias of `problems`, kept one release. |
| 5453 | "blockers": enforcement_problems, |
| 5454 | "fix": _permission_enforcement_fix() if enforcement_problems else None, |
| 5455 | }, |
| 5456 | "permission_audit": { |
| 5457 | "enabled": _permission_audit_enabled(), |
| 5458 | "env": PERMISSION_AUDIT_ENV, |
| 5459 | }, |
| 5460 | "record_events": { |
| 5461 | "enabled": _record_events_enabled(), |
| 5462 | "env": RECORD_EVENTS_ENV, |
| 5463 | "keep_count": _event_keep_count(), |
| 5464 | "keep_seconds": _event_keep_seconds(), |
| 5465 | }, |
| 5466 | "filtering": { |
| 5467 | "enabled": _filtering_enabled(), |
| 5468 | "env": FILTERING_ENABLED_ENV, |
| 5469 | }, |
| 5470 | "event_handlers": { |
| 5471 | "enabled": object_handlers.handlers_enabled(), |
| 5472 | "env": object_handlers.HANDLERS_ENABLED_ENV, |
| 5473 | }, |
| 5474 | "worker_pool": { |
| 5475 | "enabled": _worker_pool_size() > 0, |
| 5476 | "size": _worker_pool_size(), |
| 5477 | "env": object_worker_pool.WORKER_POOL_SIZE_ENV, |
| 5478 | }, |
| 5479 | # Whether u_<uid>_* objects can run here (launcher, Landlock ABI >= 4, not |
| 5480 | # root) and, if not, why: docs/runtime-contract.md "User Object Isolation". |
| 5481 | "user_code_isolation": { |
| 5482 | **object_sandbox.isolation_status(), |
| 5483 | "env": object_sandbox.ISOLATION_ENV, |
| 5484 | "spares": int(object_sandbox._env_number(object_sandbox.POOL_SIZE_ENV, object_sandbox.DEFAULT_POOL_SIZE)), |
| 5485 | "spares_env": object_sandbox.POOL_SIZE_ENV, |
| 5486 | }, |
| 5487 | "identity": { |
| 5488 | "trusted_headers_enabled": _env_enabled(PERMISSION_TRUST_HEADERS_ENV), |
| 5489 | "require_known_identity_users": _env_enabled(REQUIRE_KNOWN_IDENTITY_USERS_ENV), |
| 5490 | "session_login_enabled": _env_enabled(SESSION_LOGIN_ENV), |
| 5491 | "session_login_token_configured": bool(os.environ.get(SESSION_LOGIN_TOKEN_ENV, "")), |
| 5492 | "session_admin_gates_enabled": _env_enabled(SESSION_ADMIN_GATES_ENV), |
| 5493 | "session_admin_gates_env": SESSION_ADMIN_GATES_ENV, |
| 5494 | "password_login_enabled": _env_enabled(PASSWORD_LOGIN_ENV), |
| 5495 | "identity_source_configured": bool(object_identity_sources.configured_sources()), |
| 5496 | "identity_source_refused": _identity_source_refusal(), |
| 5497 | "password_login_env": PASSWORD_LOGIN_ENV, |
| 5498 | "signup_enabled": _signup_available(), |
| 5499 | "signup_env": object_signup.SIGNUP_ENV, |
| 5500 | "signup_blockers": _signup_blockers(), |
| 5501 | "password_reset_enabled": _password_reset_available(), |
| 5502 | "password_reset_env": object_signup.PASSWORD_RESET_ENV, |
| 5503 | "password_reset_blockers": _password_reset_blockers(), |
| 5504 | "public_url": object_signup.public_url(), |
| 5505 | "public_url_env": object_signup.PUBLIC_URL_ENV, |
| 5506 | }, |
| 5507 | "limits": { |
| 5508 | "max_request_bytes": _max_request_bytes(), |
| 5509 | "max_object_file_bytes": _max_object_file_bytes(), |
| 5510 | "max_concurrent_requests": _max_concurrent_requests(), |
| 5511 | "max_concurrent_executions": _max_concurrent_executions(), |
| 5512 | "rate_limit_requests": _rate_limit_requests(), |
| 5513 | "rate_limit_window_seconds": _rate_limit_window_seconds(), |
| 5514 | "object_timeout_seconds": _object_timeout_seconds(), |
| 5515 | }, |
| 5516 | } |
| 5517 | |
| 5518 | |
| 5519 | def _admin_package_summaries() -> list[dict[str, Any]]: |
| 5520 | packages = _list_all_packages() |
| 5521 | return [_admin_package_summary(package) for package in packages] |
| 5522 | |
| 5523 | |
| 5524 | def _admin_package_summary(package: Mapping[str, Any]) -> dict[str, Any]: |
| 5525 | package_id = str(package["id"]) |
| 5526 | plan = object_packages.dry_run_package( |
| 5527 | package_id, |
| 5528 | root=_root_for_package(package_id), |
| 5529 | base_dir=_data_dir(), |
| 5530 | ) |
| 5531 | changes = object_package_changes.list_package_changes( |
| 5532 | package_id, |
| 5533 | base_dir=_data_dir(), |
| 5534 | limit=1, |
| 5535 | ) |
| 5536 | installed = _package_plan_installed_count(plan) |
| 5537 | total = _package_plan_installable_count(plan) |
| 5538 | summary = dict(package) |
| 5539 | summary["status"] = _package_install_status(installed=installed, total=total) |
| 5540 | summary["install"] = { |
| 5541 | "installed_count": installed, |
| 5542 | "installable_count": total, |
| 5543 | "safe_to_install": bool(plan.get("safe_to_install")), |
| 5544 | "install_enabled": _env_enabled(PACKAGE_INSTALLS_ENABLED_ENV), |
| 5545 | "warnings": list(plan.get("warnings", [])), |
| 5546 | } |
| 5547 | summary["changes"] = { |
| 5548 | "total": changes["total"], |
| 5549 | "latest": changes["changes"][0] if changes["changes"] else None, |
| 5550 | } |
| 5551 | return summary |
| 5552 | |
| 5553 | |
| 5554 | def _package_plan_installed_count(plan: Mapping[str, Any]) -> int: |
| 5555 | count = 0 |
| 5556 | for section in ("objects", "schemas", "seed"): |
| 5557 | count += sum(1 for entry in plan.get(section, []) if entry.get("installed")) |
| 5558 | count += sum(1 for entry in plan.get("migrations", []) if entry.get("applied")) |
| 5559 | return count |
| 5560 | |
| 5561 | |
| 5562 | def _package_plan_installable_count(plan: Mapping[str, Any]) -> int: |
| 5563 | return sum( |
| 5564 | len(plan.get(section, [])) |
| 5565 | for section in ("objects", "schemas", "seed", "migrations") |
| 5566 | ) |
| 5567 | |
| 5568 | |
| 5569 | def _package_install_status(*, installed: int, total: int) -> str: |
| 5570 | if total == 0: |
| 5571 | return "available" |
| 5572 | if installed == total: |
| 5573 | return "installed" |
| 5574 | if installed > 0: |
| 5575 | return "partial" |
| 5576 | return "available" |
| 5577 | |
| 5578 | |
| 5579 | async def _handle_permissions_status( |
| 5580 | send, |
| 5581 | method: str, |
| 5582 | headers: dict[str, str], |
| 5583 | ) -> None: |
| 5584 | gate_error = _permissions_gate_error(headers) |
| 5585 | if gate_error is not None: |
| 5586 | status, message = gate_error |
| 5587 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5588 | return |
| 5589 | |
| 5590 | if method != "GET": |
| 5591 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5592 | return |
| 5593 | |
| 5594 | await _send_json(send, _permissions_status_payload()) |
| 5595 | |
| 5596 | |
| 5597 | def _permissions_status_payload() -> dict[str, Any]: |
| 5598 | permissions = { |
| 5599 | **_permission_readiness_inputs(), |
| 5600 | "enforcement_enabled": _permission_enforcement_enabled(), |
| 5601 | "enforcement_requested": _permission_enforcement_requested(), |
| 5602 | "enforcement_blocked": _permission_enforcement_blocked(), |
| 5603 | "allow_unready_enforcement": _permission_unready_enforcement_allowed(), |
| 5604 | "audit_enabled": _permission_audit_enabled(), |
| 5605 | "mode": _permission_mode(), |
| 5606 | } |
| 5607 | return object_permission_status.build_permissions_status( |
| 5608 | base_dir=_data_dir(), |
| 5609 | permissions=permissions, |
| 5610 | require_known_identity_users_env=REQUIRE_KNOWN_IDENTITY_USERS_ENV, |
| 5611 | ) |
| 5612 | |
| 5613 | |
| 5614 | def _permission_readiness_inputs() -> dict[str, Any]: |
| 5615 | return { |
| 5616 | "admin_token_configured": bool(os.environ.get(ADMIN_TOKEN_ENV, "")), |
| 5617 | "trusted_headers_enabled": _env_enabled(PERMISSION_TRUST_HEADERS_ENV), |
| 5618 | "require_known_identity_users": _env_enabled(REQUIRE_KNOWN_IDENTITY_USERS_ENV), |
| 5619 | "session_login_enabled": _env_enabled(SESSION_LOGIN_ENV), |
| 5620 | "session_login_token_configured": bool(os.environ.get(SESSION_LOGIN_TOKEN_ENV, "")), |
| 5621 | "password_login_enabled": _env_enabled(PASSWORD_LOGIN_ENV), |
| 5622 | # A valid DBBASIC_IDENTITY_VERIFY_URL (no network call: it only parses). |
| 5623 | "identity_source_configured": bool(object_identity_sources.configured_sources()), |
| 5624 | # Why a DBBASIC_IDENTITY_VERIFY_URL that is set was refused, or None. |
| 5625 | "identity_source_refused": _identity_source_refusal(), |
| 5626 | } |
| 5627 | |
| 5628 | |
| 5629 | def _identity_source_refusal() -> str | None: |
| 5630 | """Why the identity source the environment names was refused, or None |
| 5631 | (none named, or it was accepted). The reason names settings, never the |
| 5632 | secret or the URL. Never raises.""" |
| 5633 | try: |
| 5634 | return object_identity_sources.configuration_error() |
| 5635 | except Exception as exc: # noqa: BLE001 |
| 5636 | return f"identity source configuration could not be checked ({type(exc).__name__})" |
| 5637 | |
| 5638 | |
| 5639 | def _identity_source_alert() -> str | None: |
| 5640 | """The /admin/status alert while a configured identity source is refused: |
| 5641 | the startup log line is otherwise the only sign, and its users arrive as |
| 5642 | anonymous.""" |
| 5643 | reason = _identity_source_refusal() |
| 5644 | if not reason: |
| 5645 | return None |
| 5646 | return ( |
| 5647 | f"Identity source refused, none is in use: {reason}. Sign-ins from it are treated as anonymous. " |
| 5648 | f"Fix {object_identity_sources.IDENTITY_VERIFY_URL_ENV}, {object_identity_sources.IDENTITY_AUDIENCE_ENV} " |
| 5649 | f"and, for a host that is not loopback, {object_identity_sources.IDENTITY_VERIFY_SECRET_ENV} " |
| 5650 | f"(or unset {object_identity_sources.IDENTITY_VERIFY_URL_ENV}), then restart." |
| 5651 | ) |
| 5652 | |
| 5653 | |
| 5654 | async def _handle_permissions_policy( |
| 5655 | send, |
| 5656 | method: str, |
| 5657 | body: bytes, |
| 5658 | headers: dict[str, str], |
| 5659 | ) -> None: |
| 5660 | gate_error = _permissions_gate_error(headers) |
| 5661 | if gate_error is not None: |
| 5662 | status, message = gate_error |
| 5663 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5664 | return |
| 5665 | |
| 5666 | if method == "GET": |
| 5667 | try: |
| 5668 | policy = object_permission_store.load_policy(_data_dir()) |
| 5669 | except (OSError, ValueError) as exc: |
| 5670 | # The console opens this to repair the file: answer with what is |
| 5671 | # wrong and (when the file can be read) its text, never a 500. |
| 5672 | await _send_json(send, _broken_policy_payload(exc)) |
| 5673 | return |
| 5674 | |
| 5675 | await _send_json( |
| 5676 | send, |
| 5677 | { |
| 5678 | "status": "ok", |
| 5679 | "policy": object_permissions.policy_to_dict(policy), |
| 5680 | }, |
| 5681 | ) |
| 5682 | return |
| 5683 | |
| 5684 | if method == "PUT": |
| 5685 | try: |
| 5686 | payload = _parse_json_body(body) |
| 5687 | policy_payload = _policy_payload_from_request(payload) |
| 5688 | policy = object_permission_store.replace_policy(policy_payload, _data_dir()) |
| 5689 | except object_permissions.PolicyDeclarationError as exc: |
| 5690 | # Held to DRON at save: each mistake by rule index, package tag |
| 5691 | # and key, so a console can point at it. Nothing was written. |
| 5692 | await _send_json( |
| 5693 | send, |
| 5694 | {"status": "error", "error": str(exc), "problems": exc.problems}, |
| 5695 | status=400, |
| 5696 | ) |
| 5697 | return |
| 5698 | except ValueError as exc: |
| 5699 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5700 | return |
| 5701 | except OSError as exc: |
| 5702 | await _send_json( |
| 5703 | send, |
| 5704 | {"status": "error", "error": f"Could not save permission policy: {exc}"}, |
| 5705 | status=500, |
| 5706 | ) |
| 5707 | return |
| 5708 | |
| 5709 | await _send_json( |
| 5710 | send, |
| 5711 | { |
| 5712 | "status": "ok", |
| 5713 | "policy": object_permissions.policy_to_dict(policy), |
| 5714 | }, |
| 5715 | ) |
| 5716 | return |
| 5717 | |
| 5718 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5719 | |
| 5720 | |
| 5721 | POLICY_RAW_MAX_BYTES = 64 * 1024 |
| 5722 | |
| 5723 | |
| 5724 | def _broken_policy_payload(exc: BaseException) -> dict[str, Any]: |
| 5725 | """GET /permissions/policy for a policy that cannot be loaded (admin token only). |
| 5726 | |
| 5727 | policy is null, error says why, raw is the file's first 64 KB as text |
| 5728 | (raw_truncated says whether more follows); raw is left out when the file |
| 5729 | cannot be read at all. |
| 5730 | """ |
| 5731 | payload: dict[str, Any] = { |
| 5732 | "status": "ok", |
| 5733 | "policy": None, |
| 5734 | "error": _policy_unavailable_error(exc), |
| 5735 | } |
| 5736 | try: |
| 5737 | with open(object_permission_store.policy_path(_data_dir()), "rb") as handle: |
| 5738 | data = handle.read(POLICY_RAW_MAX_BYTES + 1) |
| 5739 | except (OSError, ValueError): |
| 5740 | return payload |
| 5741 | payload["raw"] = data[:POLICY_RAW_MAX_BYTES].decode("utf-8", errors="replace") |
| 5742 | payload["raw_truncated"] = len(data) > POLICY_RAW_MAX_BYTES |
| 5743 | return payload |
| 5744 | |
| 5745 | |
| 5746 | async def _handle_permissions_check( |
| 5747 | send, |
| 5748 | method: str, |
| 5749 | body: bytes, |
| 5750 | headers: dict[str, str], |
| 5751 | ) -> None: |
| 5752 | gate_error = _permissions_gate_error(headers) |
| 5753 | if gate_error is not None: |
| 5754 | status, message = gate_error |
| 5755 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5756 | return |
| 5757 | |
| 5758 | if method != "POST": |
| 5759 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5760 | return |
| 5761 | |
| 5762 | try: |
| 5763 | payload = _parse_json_body(body) |
| 5764 | policy = _policy_for_check_request(payload) |
| 5765 | subject = object_permissions.subject_from_dict(payload.get("subject", payload.get("user"))) |
| 5766 | action = _required_payload_text(payload, "action") |
| 5767 | collection = _optional_payload_text(payload, "collection") |
| 5768 | object_id = _optional_payload_text(payload, "object_id") |
| 5769 | record = _optional_record_payload(payload) |
| 5770 | checked_at = _optional_datetime_payload(payload, "now") |
| 5771 | except ValueError as exc: |
| 5772 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5773 | return |
| 5774 | |
| 5775 | if object_id is not None: |
| 5776 | # A question about an object is the route gate's question, so it |
| 5777 | # gets the route gate's answer: same function, and the collection |
| 5778 | # the gate would read out of the id, not one the caller names. |
| 5779 | decision = _object_permission_decision( |
| 5780 | subject, action, policy, object_id, record=record, now=checked_at) |
| 5781 | else: |
| 5782 | decision = object_permissions.check_permission( |
| 5783 | subject, |
| 5784 | action, |
| 5785 | policy=policy, |
| 5786 | collection=collection, |
| 5787 | record=record, |
| 5788 | now=checked_at, |
| 5789 | ) |
| 5790 | await _send_json( |
| 5791 | send, |
| 5792 | { |
| 5793 | "status": "ok", |
| 5794 | "decision": object_permissions.decision_to_dict(decision), |
| 5795 | }, |
| 5796 | ) |
| 5797 | |
| 5798 | |
| 5799 | async def _handle_permissions_unshipped( |
| 5800 | send, |
| 5801 | method: str, |
| 5802 | headers: dict[str, str], |
| 5803 | ) -> None: |
| 5804 | """GET /permissions/unshipped: the rules in the active policy that no |
| 5805 | installed package ships (object_packages.unshipped_permission_rules). |
| 5806 | |
| 5807 | Read-only and admin-gated like the policy it describes. It exists |
| 5808 | because an upgrade removes only what it can prove a package shipped; |
| 5809 | everything else it leaves and reports once, in an install response |
| 5810 | that scrolls away. This is the same list, on demand, for the whole box. |
| 5811 | """ |
| 5812 | gate_error = _permissions_gate_error(headers) |
| 5813 | if gate_error is not None: |
| 5814 | status, message = gate_error |
| 5815 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5816 | return |
| 5817 | |
| 5818 | if method != "GET": |
| 5819 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5820 | return |
| 5821 | |
| 5822 | try: |
| 5823 | report = object_packages.unshipped_permission_rules( |
| 5824 | roots=_package_roots(), |
| 5825 | base_dir=_data_dir(), |
| 5826 | ) |
| 5827 | except (OSError, ValueError) as exc: |
| 5828 | await _send_policy_unavailable(send, headers, _policy_unavailable_error(exc)) |
| 5829 | return |
| 5830 | |
| 5831 | await _send_json(send, {"status": "ok", **report}) |
| 5832 | |
| 5833 | |
| 5834 | async def _handle_permissions_audit( |
| 5835 | send, |
| 5836 | method: str, |
| 5837 | query: dict[str, str], |
| 5838 | headers: dict[str, str], |
| 5839 | ) -> None: |
| 5840 | gate_error = _permissions_gate_error(headers) |
| 5841 | if gate_error is not None: |
| 5842 | status, message = gate_error |
| 5843 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5844 | return |
| 5845 | |
| 5846 | if method != "GET": |
| 5847 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5848 | return |
| 5849 | |
| 5850 | try: |
| 5851 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 5852 | entries = object_permission_audit.get_permission_audit( |
| 5853 | _data_dir(), |
| 5854 | limit=limit, |
| 5855 | action=_optional_query_text(query, "action"), |
| 5856 | object_id=_optional_query_text(query, "object_id"), |
| 5857 | collection=_optional_query_text(query, "collection"), |
| 5858 | allowed=_optional_query_bool(query, "allowed"), |
| 5859 | enforced=_optional_query_bool(query, "enforced"), |
| 5860 | ) |
| 5861 | except ValueError as exc: |
| 5862 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5863 | return |
| 5864 | except OSError as exc: |
| 5865 | await _send_json( |
| 5866 | send, |
| 5867 | {"status": "error", "error": f"Could not read permission audit: {exc}"}, |
| 5868 | status=500, |
| 5869 | ) |
| 5870 | return |
| 5871 | |
| 5872 | await _send_json( |
| 5873 | send, |
| 5874 | { |
| 5875 | "status": "ok", |
| 5876 | "entries": entries, |
| 5877 | "count": len(entries), |
| 5878 | }, |
| 5879 | ) |
| 5880 | |
| 5881 | |
| 5882 | async def _handle_events( |
| 5883 | send, |
| 5884 | method: str, |
| 5885 | query: dict[str, str], |
| 5886 | body: bytes, |
| 5887 | headers: dict[str, str], |
| 5888 | ) -> None: |
| 5889 | gate_error = _admin_token_gate_error(headers, f"Events API requires {ADMIN_TOKEN_ENV}.") |
| 5890 | if gate_error is not None: |
| 5891 | status, message = gate_error |
| 5892 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5893 | return |
| 5894 | |
| 5895 | if method == "GET": |
| 5896 | try: |
| 5897 | since = None |
| 5898 | if "since" in query: |
| 5899 | since = _query_int(query, "since", minimum=0) |
| 5900 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 5901 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 5902 | events = object_events.list_events( |
| 5903 | event_type=_optional_query_text(query, "event_type"), |
| 5904 | since=since, |
| 5905 | base_dir=_data_dir(), |
| 5906 | limit=limit, |
| 5907 | offset=offset, |
| 5908 | ) |
| 5909 | except (object_events.InvalidEventTypeError, ValueError) as exc: |
| 5910 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5911 | return |
| 5912 | except OSError as exc: |
| 5913 | await _send_json( |
| 5914 | send, |
| 5915 | {"status": "error", "error": f"Could not read events: {exc}"}, |
| 5916 | status=500, |
| 5917 | ) |
| 5918 | return |
| 5919 | |
| 5920 | await _send_json(send, {"status": "ok", **events}) |
| 5921 | return |
| 5922 | |
| 5923 | if method == "POST": |
| 5924 | try: |
| 5925 | payload = _parse_json_body(body) |
| 5926 | event = object_events.publish_event( |
| 5927 | _required_payload_text(payload, "event_type"), |
| 5928 | payload=payload.get("payload", {}), |
| 5929 | source=_payload_text(payload, "source", "api"), |
| 5930 | actor=_record_change_actor(headers), |
| 5931 | base_dir=_data_dir(), |
| 5932 | keep_count=_event_keep_count(), |
| 5933 | keep_seconds=_event_keep_seconds(), |
| 5934 | ) |
| 5935 | except (object_events.InvalidEventTypeError, ValueError) as exc: |
| 5936 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5937 | return |
| 5938 | except OSError as exc: |
| 5939 | await _send_json( |
| 5940 | send, |
| 5941 | {"status": "error", "error": f"Could not publish event: {exc}"}, |
| 5942 | status=500, |
| 5943 | ) |
| 5944 | return |
| 5945 | |
| 5946 | await _send_json(send, {"status": "ok", "event": event}, status=201) |
| 5947 | return |
| 5948 | |
| 5949 | if method == "DELETE": |
| 5950 | try: |
| 5951 | keep_count = _event_retention_query_int( |
| 5952 | query, |
| 5953 | "keep_count", |
| 5954 | default=_event_keep_count(), |
| 5955 | maximum=object_events.MAX_EVENT_KEEP_COUNT, |
| 5956 | ) |
| 5957 | keep_seconds = _event_retention_query_int( |
| 5958 | query, |
| 5959 | "keep_seconds", |
| 5960 | default=_event_keep_seconds(), |
| 5961 | ) |
| 5962 | result = object_events.prune_events( |
| 5963 | base_dir=_data_dir(), |
| 5964 | keep_count=keep_count, |
| 5965 | keep_seconds=keep_seconds, |
| 5966 | ) |
| 5967 | except ValueError as exc: |
| 5968 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 5969 | return |
| 5970 | except OSError as exc: |
| 5971 | await _send_json( |
| 5972 | send, |
| 5973 | {"status": "error", "error": f"Could not prune events: {exc}"}, |
| 5974 | status=500, |
| 5975 | ) |
| 5976 | return |
| 5977 | |
| 5978 | await _send_json(send, {"status": "ok", "retention": result}) |
| 5979 | return |
| 5980 | |
| 5981 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 5982 | |
| 5983 | |
| 5984 | async def _handle_event_subscriptions( |
| 5985 | send, |
| 5986 | method: str, |
| 5987 | query: dict[str, str], |
| 5988 | body: bytes, |
| 5989 | headers: dict[str, str], |
| 5990 | ) -> None: |
| 5991 | gate_error = _admin_token_gate_error(headers, f"Events API requires {ADMIN_TOKEN_ENV}.") |
| 5992 | if gate_error is not None: |
| 5993 | status, message = gate_error |
| 5994 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 5995 | return |
| 5996 | |
| 5997 | if method == "GET": |
| 5998 | try: |
| 5999 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 6000 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 6001 | subscriptions = object_events.list_subscriptions( |
| 6002 | event_type=_optional_query_text(query, "event_type"), |
| 6003 | base_dir=_data_dir(), |
| 6004 | limit=limit, |
| 6005 | offset=offset, |
| 6006 | ) |
| 6007 | except (object_events.InvalidEventTypeError, ValueError) as exc: |
| 6008 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6009 | return |
| 6010 | except OSError as exc: |
| 6011 | await _send_json( |
| 6012 | send, |
| 6013 | {"status": "error", "error": f"Could not read event subscriptions: {exc}"}, |
| 6014 | status=500, |
| 6015 | ) |
| 6016 | return |
| 6017 | |
| 6018 | await _send_json(send, {"status": "ok", **subscriptions}) |
| 6019 | return |
| 6020 | |
| 6021 | if method == "POST": |
| 6022 | try: |
| 6023 | payload = _parse_json_body(body) |
| 6024 | subscription = object_events.subscribe_event( |
| 6025 | _required_payload_text(payload, "event_type"), |
| 6026 | subscriber_id=_optional_payload_text(payload, "subscriber_id"), |
| 6027 | callback_url=_payload_text(payload, "callback_url", ""), |
| 6028 | actor=_record_change_actor(headers), |
| 6029 | base_dir=_data_dir(), |
| 6030 | ) |
| 6031 | except ( |
| 6032 | object_events.InvalidEventTypeError, |
| 6033 | object_events.InvalidSubscriberIdError, |
| 6034 | ValueError, |
| 6035 | ) as exc: |
| 6036 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6037 | return |
| 6038 | except OSError as exc: |
| 6039 | await _send_json( |
| 6040 | send, |
| 6041 | {"status": "error", "error": f"Could not save event subscription: {exc}"}, |
| 6042 | status=500, |
| 6043 | ) |
| 6044 | return |
| 6045 | |
| 6046 | await _send_json(send, {"status": "ok", "subscription": subscription}, status=201) |
| 6047 | return |
| 6048 | |
| 6049 | if method == "DELETE": |
| 6050 | try: |
| 6051 | subscription = object_events.delete_subscription( |
| 6052 | _required_query_text(query, "event_type"), |
| 6053 | _required_query_text(query, "subscriber_id"), |
| 6054 | base_dir=_data_dir(), |
| 6055 | ) |
| 6056 | except ( |
| 6057 | object_events.InvalidEventTypeError, |
| 6058 | object_events.InvalidSubscriberIdError, |
| 6059 | ValueError, |
| 6060 | ) as exc: |
| 6061 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6062 | return |
| 6063 | except object_events.SubscriptionNotFoundError as exc: |
| 6064 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 6065 | return |
| 6066 | except OSError as exc: |
| 6067 | await _send_json( |
| 6068 | send, |
| 6069 | {"status": "error", "error": f"Could not delete event subscription: {exc}"}, |
| 6070 | status=500, |
| 6071 | ) |
| 6072 | return |
| 6073 | |
| 6074 | await _send_json( |
| 6075 | send, |
| 6076 | { |
| 6077 | "status": "ok", |
| 6078 | "deleted": True, |
| 6079 | "subscription": subscription, |
| 6080 | }, |
| 6081 | ) |
| 6082 | return |
| 6083 | |
| 6084 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6085 | |
| 6086 | |
| 6087 | async def _handle_event_deliveries( |
| 6088 | send, |
| 6089 | method: str, |
| 6090 | query: dict[str, str], |
| 6091 | headers: dict[str, str], |
| 6092 | ) -> None: |
| 6093 | gate_error = _admin_token_gate_error(headers, f"Events API requires {ADMIN_TOKEN_ENV}.") |
| 6094 | if gate_error is not None: |
| 6095 | status, message = gate_error |
| 6096 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6097 | return |
| 6098 | |
| 6099 | if method != "GET": |
| 6100 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6101 | return |
| 6102 | |
| 6103 | try: |
| 6104 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 6105 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 6106 | event_limit = _query_int(query, "event_limit", default=10, minimum=0, maximum=1000) |
| 6107 | deliveries = object_events.list_event_deliveries( |
| 6108 | event_type=_optional_query_text(query, "event_type"), |
| 6109 | delivery_status=_optional_query_text(query, "delivery_status"), |
| 6110 | pending=_optional_query_bool(query, "pending"), |
| 6111 | include_callback_url=_optional_query_bool(query, "include_callback_url") is True, |
| 6112 | include_events=_optional_query_bool(query, "include_events") is True, |
| 6113 | event_limit=event_limit, |
| 6114 | base_dir=_data_dir(), |
| 6115 | limit=limit, |
| 6116 | offset=offset, |
| 6117 | ) |
| 6118 | except (object_events.InvalidEventTypeError, ValueError) as exc: |
| 6119 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6120 | return |
| 6121 | except OSError as exc: |
| 6122 | await _send_json( |
| 6123 | send, |
| 6124 | {"status": "error", "error": f"Could not read event deliveries: {exc}"}, |
| 6125 | status=500, |
| 6126 | ) |
| 6127 | return |
| 6128 | |
| 6129 | await _send_json(send, {"status": "ok", **deliveries}) |
| 6130 | |
| 6131 | |
| 6132 | async def _handle_packages( |
| 6133 | send, |
| 6134 | method: str, |
| 6135 | headers: dict[str, str], |
| 6136 | ) -> None: |
| 6137 | if method != "GET": |
| 6138 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6139 | return |
| 6140 | |
| 6141 | gate_error = _admin_token_gate_error( |
| 6142 | headers, |
| 6143 | f"Package listing requires {ADMIN_TOKEN_ENV}.", |
| 6144 | ) |
| 6145 | if gate_error is not None: |
| 6146 | status, message = gate_error |
| 6147 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6148 | return |
| 6149 | |
| 6150 | try: |
| 6151 | packages = _list_all_packages() |
| 6152 | except object_packages.InvalidPackageManifestError as exc: |
| 6153 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 6154 | return |
| 6155 | |
| 6156 | await _send_json( |
| 6157 | send, |
| 6158 | { |
| 6159 | "status": "ok", |
| 6160 | "packages": packages, |
| 6161 | "count": len(packages), |
| 6162 | }, |
| 6163 | ) |
| 6164 | |
| 6165 | |
| 6166 | async def _handle_package( |
| 6167 | send, |
| 6168 | method: str, |
| 6169 | package_id: str, |
| 6170 | query: dict[str, str], |
| 6171 | headers: dict[str, str], |
| 6172 | ) -> None: |
| 6173 | if method != "GET": |
| 6174 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6175 | return |
| 6176 | |
| 6177 | gate_error = _admin_token_gate_error( |
| 6178 | headers, |
| 6179 | f"Package detail requires {ADMIN_TOKEN_ENV}.", |
| 6180 | ) |
| 6181 | if gate_error is not None: |
| 6182 | status, message = gate_error |
| 6183 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6184 | return |
| 6185 | |
| 6186 | try: |
| 6187 | dry_run = _optional_query_bool(query, "dry_run") is True |
| 6188 | if dry_run: |
| 6189 | plan = object_packages.dry_run_package( |
| 6190 | package_id, |
| 6191 | root=_root_for_package(package_id), |
| 6192 | base_dir=_data_dir(), |
| 6193 | ) |
| 6194 | change = object_package_changes.append_package_change( |
| 6195 | package_id=package_id, |
| 6196 | action="dry_run", |
| 6197 | package_version=plan["package"].get("version"), |
| 6198 | actor=_record_change_actor(headers), |
| 6199 | details=object_package_changes.dry_run_change_details(plan), |
| 6200 | base_dir=_data_dir(), |
| 6201 | ) |
| 6202 | payload = { |
| 6203 | "status": "ok", |
| 6204 | "dry_run": plan, |
| 6205 | "change": change, |
| 6206 | } |
| 6207 | else: |
| 6208 | payload = { |
| 6209 | "status": "ok", |
| 6210 | "package": object_packages.get_package( |
| 6211 | package_id, |
| 6212 | root=_root_for_package(package_id), |
| 6213 | ), |
| 6214 | "provenance": object_packages.package_status( |
| 6215 | package_id, |
| 6216 | root=_root_for_package(package_id), |
| 6217 | base_dir=_data_dir(), |
| 6218 | object_roots=get_base_object_roots(), |
| 6219 | ), |
| 6220 | } |
| 6221 | except object_packages.InvalidPackageIdError as exc: |
| 6222 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6223 | return |
| 6224 | except object_packages.PackageNotFoundError as exc: |
| 6225 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 6226 | return |
| 6227 | except object_packages.InvalidPackageManifestError as exc: |
| 6228 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 6229 | return |
| 6230 | except object_package_changes.InvalidPackageChangeError as exc: |
| 6231 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 6232 | return |
| 6233 | except ValueError as exc: |
| 6234 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6235 | return |
| 6236 | except OSError as exc: |
| 6237 | await _send_json(send, {"status": "error", "error": f"Could not record package change: {exc}"}, status=500) |
| 6238 | return |
| 6239 | |
| 6240 | await _send_json(send, payload) |
| 6241 | |
| 6242 | |
| 6243 | async def _handle_package_install( |
| 6244 | send, |
| 6245 | method: str, |
| 6246 | package_id: str, |
| 6247 | body: bytes, |
| 6248 | headers: dict[str, str], |
| 6249 | ) -> None: |
| 6250 | if method != "POST": |
| 6251 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6252 | return |
| 6253 | |
| 6254 | gate_error = _admin_token_gate_error( |
| 6255 | headers, |
| 6256 | f"Package installs require {ADMIN_TOKEN_ENV}.", |
| 6257 | ) |
| 6258 | if gate_error is not None: |
| 6259 | status, message = gate_error |
| 6260 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6261 | return |
| 6262 | |
| 6263 | if not _env_enabled(PACKAGE_INSTALLS_ENABLED_ENV): |
| 6264 | await _send_json( |
| 6265 | send, |
| 6266 | { |
| 6267 | "status": "error", |
| 6268 | "error": f"Package installs are disabled. Set {PACKAGE_INSTALLS_ENABLED_ENV}=true.", |
| 6269 | }, |
| 6270 | status=403, |
| 6271 | ) |
| 6272 | return |
| 6273 | |
| 6274 | plan = None |
| 6275 | requested_change = None |
| 6276 | |
| 6277 | try: |
| 6278 | payload = _parse_json_body(body) |
| 6279 | allow_replace = _optional_payload_bool(payload, "allow_replace") is True |
| 6280 | reused_restore_point = _reused_restore_point(payload) |
| 6281 | plan = object_packages.dry_run_package( |
| 6282 | package_id, |
| 6283 | root=_root_for_package(package_id), |
| 6284 | base_dir=_data_dir(), |
| 6285 | ) |
| 6286 | requested_change = object_package_changes.append_package_change( |
| 6287 | package_id=package_id, |
| 6288 | action="install_requested", |
| 6289 | package_version=plan["package"].get("version"), |
| 6290 | actor=_record_change_actor(headers), |
| 6291 | details=object_package_changes.dry_run_change_details(plan), |
| 6292 | base_dir=_data_dir(), |
| 6293 | ) |
| 6294 | |
| 6295 | restore_point: dict[str, Any] | None = None |
| 6296 | |
| 6297 | def create_restore_point(_: Mapping[str, Any]) -> dict[str, Any]: |
| 6298 | nonlocal restore_point |
| 6299 | if reused_restore_point is not None: |
| 6300 | restore_point = dict(reused_restore_point) |
| 6301 | return restore_point |
| 6302 | summary = object_backup.create_runtime_restore_point( |
| 6303 | f"package-{package_id}", |
| 6304 | data_dir=_data_dir(), |
| 6305 | ) |
| 6306 | restore_point = _backup_summary_payload(summary) |
| 6307 | return restore_point |
| 6308 | |
| 6309 | install_result = object_packages.install_package( |
| 6310 | package_id, |
| 6311 | root=_root_for_package(package_id), |
| 6312 | base_dir=_data_dir(), |
| 6313 | object_roots=get_base_object_roots(), |
| 6314 | allow_replace=allow_replace, |
| 6315 | before_write=create_restore_point, |
| 6316 | ) |
| 6317 | restore_point = install_result.get("restore_point", restore_point) |
| 6318 | installed_change = object_package_changes.append_package_change( |
| 6319 | package_id=package_id, |
| 6320 | action="installed", |
| 6321 | package_version=install_result["package"].get("version"), |
| 6322 | actor=_record_change_actor(headers), |
| 6323 | details=_package_change_details(install_result, restore_point=restore_point), |
| 6324 | base_dir=_data_dir(), |
| 6325 | ) |
| 6326 | except _RestorePointUnavailableError as exc: |
| 6327 | await _send_json(send, {"status": "error", "error": str(exc)}, status=409) |
| 6328 | return |
| 6329 | except object_packages.InvalidPackageIdError as exc: |
| 6330 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6331 | return |
| 6332 | except object_packages.PackageNotFoundError as exc: |
| 6333 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 6334 | return |
| 6335 | except object_packages.PackageInstallError as exc: |
| 6336 | failed_change = _try_append_package_install_failure( |
| 6337 | package_id=package_id, |
| 6338 | plan=plan, |
| 6339 | headers=headers, |
| 6340 | error=str(exc), |
| 6341 | ) |
| 6342 | changes = _package_install_changes(requested_change, failed=failed_change) |
| 6343 | await _send_json( |
| 6344 | send, |
| 6345 | { |
| 6346 | "status": "error", |
| 6347 | "error": str(exc), |
| 6348 | "changes": changes, |
| 6349 | }, |
| 6350 | status=409, |
| 6351 | ) |
| 6352 | return |
| 6353 | except object_packages.InvalidPackageManifestError as exc: |
| 6354 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 6355 | return |
| 6356 | except object_package_changes.InvalidPackageChangeError as exc: |
| 6357 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 6358 | return |
| 6359 | except ValueError as exc: |
| 6360 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6361 | return |
| 6362 | except OSError as exc: |
| 6363 | failed_change = _try_append_package_install_failure( |
| 6364 | package_id=package_id, |
| 6365 | plan=plan, |
| 6366 | headers=headers, |
| 6367 | error=str(exc), |
| 6368 | ) |
| 6369 | await _send_json( |
| 6370 | send, |
| 6371 | { |
| 6372 | "status": "error", |
| 6373 | "error": f"Package install failed: {exc}", |
| 6374 | "changes": _package_install_changes(requested_change, failed=failed_change), |
| 6375 | }, |
| 6376 | status=500, |
| 6377 | ) |
| 6378 | return |
| 6379 | |
| 6380 | await _send_json( |
| 6381 | send, |
| 6382 | { |
| 6383 | "status": "ok", |
| 6384 | "install": install_result, |
| 6385 | "changes": { |
| 6386 | "requested": requested_change, |
| 6387 | "installed": installed_change, |
| 6388 | }, |
| 6389 | "restore_point": restore_point, |
| 6390 | }, |
| 6391 | status=201, |
| 6392 | ) |
| 6393 | |
| 6394 | |
| 6395 | async def _handle_package_restore( |
| 6396 | send, |
| 6397 | method: str, |
| 6398 | package_id: str, |
| 6399 | body: bytes, |
| 6400 | headers: dict[str, str], |
| 6401 | ) -> None: |
| 6402 | if method != "POST": |
| 6403 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6404 | return |
| 6405 | |
| 6406 | gate_error = _admin_token_gate_error( |
| 6407 | headers, |
| 6408 | f"Package restore requires {ADMIN_TOKEN_ENV}.", |
| 6409 | ) |
| 6410 | if gate_error is not None: |
| 6411 | status, message = gate_error |
| 6412 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6413 | return |
| 6414 | |
| 6415 | if not _env_enabled(PACKAGE_RESTORE_ENABLED_ENV): |
| 6416 | await _send_json( |
| 6417 | send, |
| 6418 | { |
| 6419 | "status": "error", |
| 6420 | "error": f"Package restore is disabled. Set {PACKAGE_RESTORE_ENABLED_ENV}=true.", |
| 6421 | }, |
| 6422 | status=403, |
| 6423 | ) |
| 6424 | return |
| 6425 | |
| 6426 | from_change: dict[str, Any] | None = None |
| 6427 | restore_point: dict[str, Any] | None = None |
| 6428 | preview = False |
| 6429 | |
| 6430 | try: |
| 6431 | payload = _parse_json_body(body) |
| 6432 | preview = isinstance(payload, dict) and payload.get("preview") is True |
| 6433 | if not preview and _required_payload_text(payload, "confirm") != "restore-runtime": |
| 6434 | raise ValueError("Request JSON field 'confirm' must be 'restore-runtime'") |
| 6435 | change_id = _required_payload_text(payload, "change_id") |
| 6436 | from_change = object_package_changes.get_package_change( |
| 6437 | package_id, |
| 6438 | change_id, |
| 6439 | base_dir=_data_dir(), |
| 6440 | ) |
| 6441 | if from_change is None: |
| 6442 | await _send_json( |
| 6443 | send, |
| 6444 | {"status": "error", "error": f"Package change not found: {change_id}"}, |
| 6445 | status=404, |
| 6446 | ) |
| 6447 | return |
| 6448 | |
| 6449 | restore_point = _restore_point_from_package_change(from_change) |
| 6450 | |
| 6451 | # The policy difference comes first, and the apply must present the |
| 6452 | # digest of the one the operator saw (step one is preview: true). |
| 6453 | # Fail closed: if it cannot be computed, nothing is restored. |
| 6454 | try: |
| 6455 | policy_diff = object_policy_diff.restore_policy_diff( |
| 6456 | restore_point["path"], _data_dir(), prune=True, |
| 6457 | ) |
| 6458 | except object_policy_diff.PolicyDiffError as exc: |
| 6459 | raise _PackageRestoreRefused( |
| 6460 | f"Package restore refused: the policy difference cannot be computed ({exc})", |
| 6461 | {}, |
| 6462 | ) from exc |
| 6463 | policy_diff_hash = object_policy_diff.policy_diff_hash( |
| 6464 | policy_diff, package_id=package_id, change_id=change_id, |
| 6465 | ) |
| 6466 | policy_fields = { |
| 6467 | "policy_diff": policy_diff, |
| 6468 | "policy_diff_hash": policy_diff_hash, |
| 6469 | "policy_diff_text": object_policy_diff.format_policy_diff(policy_diff), |
| 6470 | } |
| 6471 | if preview: |
| 6472 | await _send_json( |
| 6473 | send, |
| 6474 | { |
| 6475 | "status": "ok", |
| 6476 | "preview": True, |
| 6477 | "package_id": package_id, |
| 6478 | "restore_point": restore_point, |
| 6479 | "from_change": from_change, |
| 6480 | **policy_fields, |
| 6481 | }, |
| 6482 | ) |
| 6483 | return |
| 6484 | presented_hash = payload.get("policy_diff_hash") |
| 6485 | if presented_hash is None and policy_diff["changed"]: |
| 6486 | raise _PackageRestoreRefused( |
| 6487 | "Package restore changes the permission policy" |
| 6488 | + (" and LOOSENS it" if policy_diff["loosens"] else "") |
| 6489 | + ": preview it ({\"preview\": true}) and send back its policy_diff_hash", |
| 6490 | policy_fields, |
| 6491 | ) |
| 6492 | if presented_hash is not None and presented_hash != policy_diff_hash: |
| 6493 | raise _PackageRestoreRefused( |
| 6494 | "Package restore refused: the policy difference is not the one previewed " |
| 6495 | "(the policy or the snapshot changed since); preview it again", |
| 6496 | policy_fields, |
| 6497 | ) |
| 6498 | |
| 6499 | restored_files: list[tuple[str, bytes | None, bytes | None]] = [] |
| 6500 | restore_summary = object_backup.restore_runtime_backup( |
| 6501 | restore_point["path"], |
| 6502 | objects_dir=_primary_objects_dir(), |
| 6503 | data_dir=_data_dir(), |
| 6504 | overwrite=True, |
| 6505 | prune_extra=True, |
| 6506 | # A rollback of the runtime, not of the record of who did what, |
| 6507 | # of who may sign in, nor of the histories: the restore is added |
| 6508 | # to them below instead. |
| 6509 | preserve=object_backup.is_package_restore_preserved, |
| 6510 | on_change=lambda name, before, after: restored_files.append((name, before, after)), |
| 6511 | ) |
| 6512 | history = _record_package_restore_history( |
| 6513 | restored_files, |
| 6514 | package_id=package_id, |
| 6515 | from_change=from_change, |
| 6516 | restore_point=restore_point, |
| 6517 | actor=_record_change_actor(headers), |
| 6518 | ) |
| 6519 | requested_change = object_package_changes.append_package_change( |
| 6520 | package_id=package_id, |
| 6521 | action="restore_requested", |
| 6522 | package_version=from_change.get("package_version"), |
| 6523 | actor=_record_change_actor(headers), |
| 6524 | details=_package_restore_change_details( |
| 6525 | from_change, |
| 6526 | restore_point, |
| 6527 | restore=restore_summary.to_dict(), |
| 6528 | history=history, |
| 6529 | policy_diff=policy_diff, |
| 6530 | policy_diff_hash=policy_diff_hash, |
| 6531 | ), |
| 6532 | base_dir=_data_dir(), |
| 6533 | ) |
| 6534 | rolled_back_change = object_package_changes.append_package_change( |
| 6535 | package_id=package_id, |
| 6536 | action="rolled_back", |
| 6537 | package_version=from_change.get("package_version"), |
| 6538 | actor=_record_change_actor(headers), |
| 6539 | details=_package_restore_change_details( |
| 6540 | from_change, |
| 6541 | restore_point, |
| 6542 | restore=restore_summary.to_dict(), |
| 6543 | history=history, |
| 6544 | policy_diff=policy_diff, |
| 6545 | policy_diff_hash=policy_diff_hash, |
| 6546 | ), |
| 6547 | base_dir=_data_dir(), |
| 6548 | ) |
| 6549 | except (object_packages.InvalidPackageIdError, object_package_changes.InvalidPackageChangeError) as exc: |
| 6550 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6551 | return |
| 6552 | except _PackageRestoreRefused as exc: |
| 6553 | # A preview writes nothing, its refusals included. |
| 6554 | failed_change = None if preview else _try_append_package_restore_failure( |
| 6555 | package_id=package_id, |
| 6556 | from_change=from_change, |
| 6557 | restore_point=restore_point, |
| 6558 | headers=headers, |
| 6559 | error=str(exc), |
| 6560 | ) |
| 6561 | await _send_json( |
| 6562 | send, |
| 6563 | { |
| 6564 | "status": "error", |
| 6565 | "error": str(exc), |
| 6566 | **exc.fields, |
| 6567 | "changes": _package_restore_changes(failed=failed_change), |
| 6568 | }, |
| 6569 | status=409, |
| 6570 | ) |
| 6571 | return |
| 6572 | except (ValueError, object_backup.BackupRestoreError) as exc: |
| 6573 | if preview: |
| 6574 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6575 | return |
| 6576 | failed_change = _try_append_package_restore_failure( |
| 6577 | package_id=package_id, |
| 6578 | from_change=from_change, |
| 6579 | restore_point=restore_point, |
| 6580 | headers=headers, |
| 6581 | error=str(exc), |
| 6582 | ) |
| 6583 | await _send_json( |
| 6584 | send, |
| 6585 | { |
| 6586 | "status": "error", |
| 6587 | "error": str(exc), |
| 6588 | "changes": _package_restore_changes(failed=failed_change), |
| 6589 | }, |
| 6590 | status=400, |
| 6591 | ) |
| 6592 | return |
| 6593 | except OSError as exc: |
| 6594 | if preview: |
| 6595 | await _send_json( |
| 6596 | send, {"status": "error", "error": f"Package restore preview failed: {exc}"}, status=500, |
| 6597 | ) |
| 6598 | return |
| 6599 | failed_change = _try_append_package_restore_failure( |
| 6600 | package_id=package_id, |
| 6601 | from_change=from_change, |
| 6602 | restore_point=restore_point, |
| 6603 | headers=headers, |
| 6604 | error=str(exc), |
| 6605 | ) |
| 6606 | await _send_json( |
| 6607 | send, |
| 6608 | { |
| 6609 | "status": "error", |
| 6610 | "error": f"Package restore failed: {exc}", |
| 6611 | "changes": _package_restore_changes(failed=failed_change), |
| 6612 | }, |
| 6613 | status=500, |
| 6614 | ) |
| 6615 | return |
| 6616 | |
| 6617 | await _send_json( |
| 6618 | send, |
| 6619 | { |
| 6620 | "status": "ok", |
| 6621 | "restore": restore_summary.to_dict(), |
| 6622 | "restore_point": restore_point, |
| 6623 | "from_change": from_change, |
| 6624 | "history": history, |
| 6625 | "policy_diff": policy_diff, |
| 6626 | "policy_diff_hash": policy_diff_hash, |
| 6627 | "changes": { |
| 6628 | "requested": requested_change, |
| 6629 | "rolled_back": rolled_back_change, |
| 6630 | }, |
| 6631 | }, |
| 6632 | ) |
| 6633 | |
| 6634 | |
| 6635 | async def _handle_package_changes( |
| 6636 | send, |
| 6637 | method: str, |
| 6638 | package_id: str, |
| 6639 | query: dict[str, str], |
| 6640 | headers: dict[str, str], |
| 6641 | ) -> None: |
| 6642 | if method != "GET": |
| 6643 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 6644 | return |
| 6645 | |
| 6646 | gate_error = _admin_token_gate_error( |
| 6647 | headers, |
| 6648 | f"Package change history requires {ADMIN_TOKEN_ENV}.", |
| 6649 | ) |
| 6650 | if gate_error is not None: |
| 6651 | status, message = gate_error |
| 6652 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 6653 | return |
| 6654 | |
| 6655 | try: |
| 6656 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 6657 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 6658 | changes = object_package_changes.list_package_changes( |
| 6659 | package_id, |
| 6660 | base_dir=_data_dir(), |
| 6661 | limit=limit, |
| 6662 | offset=offset, |
| 6663 | ) |
| 6664 | except object_packages.InvalidPackageIdError as exc: |
| 6665 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6666 | return |
| 6667 | except ValueError as exc: |
| 6668 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 6669 | return |
| 6670 | |
| 6671 | await _send_json(send, {"status": "ok", **changes}) |
| 6672 | |
| 6673 | |
| 6674 | class _RestorePointUnavailableError(Exception): |
| 6675 | """A named restore point does not exist or is not a readable backup.""" |
| 6676 | |
| 6677 | |
| 6678 | def _reused_restore_point(payload: Mapping[str, Any]) -> dict[str, Any] | None: |
| 6679 | """Resolve the optional install ``restore_point`` (an existing backup id). |
| 6680 | |
| 6681 | Returns the restore-point record in the same shape a fresh archive |
| 6682 | produces, or None when the field is absent. Malformed ids raise |
| 6683 | ValueError (400); a missing or unreadable archive raises |
| 6684 | _RestorePointUnavailableError (409). Nothing is written either way. |
| 6685 | """ |
| 6686 | if "restore_point" not in payload: |
| 6687 | return None |
| 6688 | backup_id = payload["restore_point"] |
| 6689 | if not isinstance(backup_id, str) or not object_backup_index.validate_backup_id(backup_id): |
| 6690 | raise ValueError( |
| 6691 | "Request JSON field 'restore_point' must be a backup id from GET /admin/backups" |
| 6692 | ) |
| 6693 | path = object_backup_index.backup_path(backup_id, data_dir=_data_dir()) |
| 6694 | if not path.is_file(): |
| 6695 | raise _RestorePointUnavailableError(f"Backup not found: {backup_id}") |
| 6696 | manifest: Any = None |
| 6697 | try: |
| 6698 | # The manifest is the first archive member, so this reads only its head. |
| 6699 | with tarfile.open(path, "r:*") as archive: |
| 6700 | first = archive.next() |
| 6701 | if first is not None and first.name == object_backup.MANIFEST_NAME: |
| 6702 | handle = archive.extractfile(first) |
| 6703 | if handle is not None: |
| 6704 | manifest = json.loads(handle.read().decode("utf-8")) |
| 6705 | except (tarfile.TarError, OSError, ValueError): |
| 6706 | manifest = None |
| 6707 | if not isinstance(manifest, dict): |
| 6708 | raise _RestorePointUnavailableError(f"Backup is not a readable runtime backup: {backup_id}") |
| 6709 | warnings = manifest.get("warnings") |
| 6710 | return { |
| 6711 | "path": str(path), |
| 6712 | "format_version": manifest.get("format_version"), |
| 6713 | "created_at": manifest.get("created_at"), |
| 6714 | "files": manifest.get("files"), |
| 6715 | "bytes": manifest.get("bytes"), |
| 6716 | "warnings": list(warnings) if isinstance(warnings, list) else [], |
| 6717 | } |
| 6718 | |
| 6719 | |
| 6720 | def _backup_summary_payload(summary: object_backup.BackupSummary) -> dict[str, Any]: |
| 6721 | return { |
| 6722 | "path": summary.path, |
| 6723 | "format_version": summary.format_version, |
| 6724 | "created_at": summary.created_at, |
| 6725 | "files": summary.files, |
| 6726 | "bytes": summary.bytes, |
| 6727 | "warnings": summary.warnings, |
| 6728 | } |
| 6729 | |
| 6730 | |
| 6731 | def _package_change_details( |
| 6732 | plan: Mapping[str, Any], |
| 6733 | *, |
| 6734 | restore_point: Mapping[str, Any] | None = None, |
| 6735 | error: str | None = None, |
| 6736 | ) -> dict[str, Any]: |
| 6737 | details = object_package_changes.dry_run_change_details(plan) |
| 6738 | if restore_point is not None: |
| 6739 | details["restore_point"] = dict(restore_point) |
| 6740 | if error: |
| 6741 | details["error"] = error |
| 6742 | return details |
| 6743 | |
| 6744 | |
| 6745 | def _try_append_package_install_failure( |
| 6746 | *, |
| 6747 | package_id: str, |
| 6748 | plan: Mapping[str, Any] | None, |
| 6749 | headers: dict[str, str], |
| 6750 | error: str, |
| 6751 | ) -> dict[str, Any] | None: |
| 6752 | failed_details: dict[str, Any] = {"error": error} |
| 6753 | failed_version = None |
| 6754 | if plan is not None: |
| 6755 | failed_details = _package_change_details(plan, error=error) |
| 6756 | failed_version = plan["package"].get("version") |
| 6757 | |
| 6758 | try: |
| 6759 | return object_package_changes.append_package_change( |
| 6760 | package_id=package_id, |
| 6761 | action="failed", |
| 6762 | package_version=failed_version, |
| 6763 | actor=_record_change_actor(headers), |
| 6764 | message=error, |
| 6765 | details=failed_details, |
| 6766 | base_dir=_data_dir(), |
| 6767 | ) |
| 6768 | except Exception: |
| 6769 | return None |
| 6770 | |
| 6771 | |
| 6772 | def _package_install_changes( |
| 6773 | requested_change: Mapping[str, Any] | None, |
| 6774 | *, |
| 6775 | failed: Mapping[str, Any] | None = None, |
| 6776 | ) -> dict[str, Any | None]: |
| 6777 | changes: dict[str, Any | None] = {} |
| 6778 | if requested_change is not None: |
| 6779 | changes["requested"] = dict(requested_change) |
| 6780 | changes["failed"] = dict(failed) if failed is not None else None |
| 6781 | return changes |
| 6782 | |
| 6783 | |
| 6784 | def _restore_point_from_package_change(change: Mapping[str, Any]) -> dict[str, Any]: |
| 6785 | details = change.get("details") |
| 6786 | if not isinstance(details, Mapping): |
| 6787 | raise object_backup.BackupRestoreError("Package change has no restore point details") |
| 6788 | |
| 6789 | restore_point = details.get("restore_point") |
| 6790 | if not isinstance(restore_point, Mapping): |
| 6791 | raise object_backup.BackupRestoreError("Package change has no restore point") |
| 6792 | |
| 6793 | restore_path = restore_point.get("path") |
| 6794 | if not isinstance(restore_path, str) or not restore_path.strip() or "\x00" in restore_path: |
| 6795 | raise object_backup.BackupRestoreError("Package restore point path is not safe") |
| 6796 | |
| 6797 | candidate = Path(restore_path) |
| 6798 | allowed_root = Path( |
| 6799 | os.environ.get(object_backup.BACKUPS_DIR_ENV) |
| 6800 | or (Path(_data_dir()) / object_backup.BACKUPS_DIR) |
| 6801 | ) |
| 6802 | resolved_candidate = candidate.resolve(strict=False) |
| 6803 | resolved_allowed = allowed_root.resolve(strict=False) |
| 6804 | try: |
| 6805 | resolved_candidate.relative_to(resolved_allowed) |
| 6806 | except ValueError as exc: |
| 6807 | raise object_backup.BackupRestoreError( |
| 6808 | "Package restore point is outside the configured backup directory" |
| 6809 | ) from exc |
| 6810 | |
| 6811 | payload = dict(restore_point) |
| 6812 | payload["path"] = str(candidate) |
| 6813 | return payload |
| 6814 | |
| 6815 | |
| 6816 | def _package_restore_change_details( |
| 6817 | from_change: Mapping[str, Any], |
| 6818 | restore_point: Mapping[str, Any], |
| 6819 | *, |
| 6820 | restore: Mapping[str, Any] | None = None, |
| 6821 | history: Mapping[str, Any] | None = None, |
| 6822 | policy_diff: Mapping[str, Any] | None = None, |
| 6823 | policy_diff_hash: str | None = None, |
| 6824 | error: str | None = None, |
| 6825 | ) -> dict[str, Any]: |
| 6826 | details: dict[str, Any] = { |
| 6827 | "from_change": { |
| 6828 | "change_id": from_change.get("change_id"), |
| 6829 | "timestamp": from_change.get("timestamp"), |
| 6830 | "action": from_change.get("action"), |
| 6831 | "package_version": from_change.get("package_version"), |
| 6832 | }, |
| 6833 | "restore_mode": "runtime_snapshot", |
| 6834 | "restore_point": dict(restore_point), |
| 6835 | } |
| 6836 | if restore is not None: |
| 6837 | details["restore"] = dict(restore) |
| 6838 | if history is not None: |
| 6839 | details["history"] = dict(history) |
| 6840 | if policy_diff is not None: |
| 6841 | details["policy_diff"] = dict(policy_diff) |
| 6842 | details["policy_diff_hash"] = policy_diff_hash |
| 6843 | if error: |
| 6844 | details["error"] = error |
| 6845 | return details |
| 6846 | |
| 6847 | |
| 6848 | class _PackageRestoreRefused(ValueError): |
| 6849 | """A package restore refused over its policy difference (409).""" |
| 6850 | |
| 6851 | def __init__(self, message: str, fields: Mapping[str, Any]): |
| 6852 | super().__init__(message) |
| 6853 | self.fields = dict(fields) |
| 6854 | |
| 6855 | |
| 6856 | _RESTORE_HISTORY_MAX_ERRORS = 20 |
| 6857 | |
| 6858 | |
| 6859 | def _record_package_restore_history( |
| 6860 | restored_files: list[tuple[str, bytes | None, bytes | None]], |
| 6861 | *, |
| 6862 | package_id: str, |
| 6863 | from_change: Mapping[str, Any], |
| 6864 | restore_point: Mapping[str, Any], |
| 6865 | actor: str, |
| 6866 | ) -> dict[str, Any]: |
| 6867 | """Add a package restore to the per-object histories it changed. |
| 6868 | |
| 6869 | The restore keeps every history as it is on disk |
| 6870 | (object_backup.HISTORY_DATA_DIRS); this appends what the restore itself |
| 6871 | did, as the edit, rollback and destroy routes would have: who, when and |
| 6872 | from which snapshot. An object source it replaced or removed is saved |
| 6873 | as a version first when no version holds it, so nothing the rollback |
| 6874 | overwrote is lost. Entries are additive and best effort, like the |
| 6875 | routes' own change logs (the runtime is already restored); each one |
| 6876 | that cannot be written is counted and named in ``errors``. |
| 6877 | """ |
| 6878 | data_dir = Path(_data_dir()) |
| 6879 | objects_dir = Path(_primary_objects_dir()) |
| 6880 | correlation_id = object_correlation.current_correlation_id() |
| 6881 | change_id = str(from_change.get("change_id") or "") |
| 6882 | message = f"Package restore: {package_id} rolled back to before change {change_id}" |
| 6883 | before_message = f"Before package restore: {package_id} (change {change_id})" |
| 6884 | restore_ref = { |
| 6885 | "package_id": package_id, |
| 6886 | "from_change_id": change_id, |
| 6887 | "restore_point": Path(str(restore_point.get("path") or "")).name, |
| 6888 | } |
| 6889 | counts = { |
| 6890 | "source_versions": 0, |
| 6891 | "source_changes": 0, |
| 6892 | "schema_versions": 0, |
| 6893 | "record_changes": 0, |
| 6894 | "file_changes": 0, |
| 6895 | } |
| 6896 | errors: list[str] = [] |
| 6897 | failed = 0 |
| 6898 | versions: object_versions.VersionManager | None = None |
| 6899 | schema_versions: object_schema_versions.SchemaVersionManager | None = None |
| 6900 | |
| 6901 | for name, before, after in restored_files: |
| 6902 | parts = PurePosixPath(name).parts |
| 6903 | try: |
| 6904 | if parts[0] == "objects": |
| 6905 | try: |
| 6906 | object_id = object_namespace.object_id_from_path( |
| 6907 | objects_dir.joinpath(*parts[1:]), objects_dir, |
| 6908 | ) |
| 6909 | except ValueError: |
| 6910 | continue # not an object source (a helper or data file) |
| 6911 | versions = versions or object_versions.VersionManager(data_dir) |
| 6912 | before_text = before.decode("utf-8") if before is not None else None |
| 6913 | after_text = after.decode("utf-8") if after is not None else None |
| 6914 | from_version: int | None = None |
| 6915 | if before_text is not None: |
| 6916 | latest = versions.get_version(object_id) |
| 6917 | if latest is None or latest["content"] != before_text: |
| 6918 | from_version = versions.save_version( |
| 6919 | object_id, before_text, actor, before_message, correlation_id, |
| 6920 | ) |
| 6921 | counts["source_versions"] += 1 |
| 6922 | else: |
| 6923 | from_version = int(latest["version_id"]) |
| 6924 | if after_text is not None: |
| 6925 | version_id = versions.save_version( |
| 6926 | object_id, after_text, actor, message, correlation_id, |
| 6927 | ) |
| 6928 | counts["source_versions"] += 1 |
| 6929 | action = "source_rollback" if before_text is not None else "source_create" |
| 6930 | else: |
| 6931 | assert from_version is not None |
| 6932 | version_id, action, from_version = from_version, "source_destroy", None |
| 6933 | object_source_changes.append_source_change( |
| 6934 | object_id=object_id, |
| 6935 | action=action, |
| 6936 | version_id=version_id, |
| 6937 | from_version_id=from_version, |
| 6938 | actor=actor, |
| 6939 | message=message, |
| 6940 | correlation_id=correlation_id, |
| 6941 | details={"package_restore": restore_ref}, |
| 6942 | base_dir=data_dir, |
| 6943 | ) |
| 6944 | counts["source_changes"] += 1 |
| 6945 | elif parts[:2] == ("data", "schemas") and len(parts) == 3 and parts[2].endswith(".json"): |
| 6946 | schema = parts[2][: -len(".json")] |
| 6947 | schema_versions = schema_versions or object_schema_versions.SchemaVersionManager(data_dir) |
| 6948 | latest = schema_versions.get_version(schema) |
| 6949 | if before is not None and (latest is None or latest["content"] != before.decode("utf-8")): |
| 6950 | schema_versions.save_version(schema, before.decode("utf-8"), actor, before_message) |
| 6951 | counts["schema_versions"] += 1 |
| 6952 | if after is not None: |
| 6953 | schema_versions.save_version(schema, after.decode("utf-8"), actor, message) |
| 6954 | counts["schema_versions"] += 1 |
| 6955 | elif ( |
| 6956 | parts[:2] == ("data", "collections") |
| 6957 | and len(parts) == 4 |
| 6958 | and parts[3] == "records.tsv" |
| 6959 | ): |
| 6960 | collection = parts[2] |
| 6961 | before_rows = object_backup_index._parse_tsv_by_id(before) |
| 6962 | after_rows = object_backup_index._parse_tsv_by_id(after) |
| 6963 | for record_id in sorted(set(before_rows) | set(after_rows)): |
| 6964 | old_row = before_rows.get(record_id) |
| 6965 | new_row = after_rows.get(record_id) |
| 6966 | if old_row == new_row: |
| 6967 | continue |
| 6968 | action = "create" if old_row is None else "delete" if new_row is None else "update" |
| 6969 | try: |
| 6970 | object_record_changes.append_record_change( |
| 6971 | collection=collection, |
| 6972 | record_id=record_id, |
| 6973 | action=action, |
| 6974 | before=old_row, |
| 6975 | after=new_row, |
| 6976 | actor=actor, |
| 6977 | message=message, |
| 6978 | correlation_id=correlation_id, |
| 6979 | base_dir=data_dir, |
| 6980 | ) |
| 6981 | counts["record_changes"] += 1 |
| 6982 | except Exception as exc: # one bad row must not hide the rest |
| 6983 | failed += 1 |
| 6984 | if len(errors) < _RESTORE_HISTORY_MAX_ERRORS: |
| 6985 | errors.append(f"{name} {record_id}: {exc}") |
| 6986 | elif parts[:2] == ("data", "files") and len(parts) >= 4: |
| 6987 | object_file_changes.append_file_change( |
| 6988 | object_id=parts[2], |
| 6989 | action=( |
| 6990 | "file_delete" if after is None |
| 6991 | else "file_create" if before is None |
| 6992 | else "file_update" |
| 6993 | ), |
| 6994 | file_name="/".join(parts[3:]), |
| 6995 | file_size=len(after) if after is not None else None, |
| 6996 | actor=actor, |
| 6997 | message=message, |
| 6998 | correlation_id=correlation_id, |
| 6999 | details={"package_restore": restore_ref}, |
| 7000 | base_dir=data_dir, |
| 7001 | ) |
| 7002 | counts["file_changes"] += 1 |
| 7003 | except Exception as exc: # additive and best effort: see docstring |
| 7004 | failed += 1 |
| 7005 | if len(errors) < _RESTORE_HISTORY_MAX_ERRORS: |
| 7006 | errors.append(f"{name}: {exc}") |
| 7007 | |
| 7008 | return {**counts, "failed": failed, "errors": errors} |
| 7009 | |
| 7010 | |
| 7011 | def _try_append_package_restore_failure( |
| 7012 | *, |
| 7013 | package_id: str, |
| 7014 | from_change: Mapping[str, Any] | None, |
| 7015 | restore_point: Mapping[str, Any] | None, |
| 7016 | headers: dict[str, str], |
| 7017 | error: str, |
| 7018 | ) -> dict[str, Any] | None: |
| 7019 | details: dict[str, Any] = {"error": error} |
| 7020 | package_version = None |
| 7021 | if from_change is not None: |
| 7022 | package_version = from_change.get("package_version") |
| 7023 | details = _package_restore_change_details( |
| 7024 | from_change, |
| 7025 | restore_point or {}, |
| 7026 | error=error, |
| 7027 | ) |
| 7028 | |
| 7029 | try: |
| 7030 | return object_package_changes.append_package_change( |
| 7031 | package_id=package_id, |
| 7032 | action="failed", |
| 7033 | package_version=package_version, |
| 7034 | actor=_record_change_actor(headers), |
| 7035 | message=error, |
| 7036 | details=details, |
| 7037 | base_dir=_data_dir(), |
| 7038 | ) |
| 7039 | except Exception: |
| 7040 | return None |
| 7041 | |
| 7042 | |
| 7043 | def _package_restore_changes( |
| 7044 | *, |
| 7045 | failed: Mapping[str, Any] | None = None, |
| 7046 | ) -> dict[str, Any | None]: |
| 7047 | return {"failed": dict(failed) if failed is not None else None} |
| 7048 | |
| 7049 | |
| 7050 | async def _handle_object_get( |
| 7051 | send, |
| 7052 | object_id: str, |
| 7053 | query: dict[str, str], |
| 7054 | headers: dict[str, str], |
| 7055 | ) -> None: |
| 7056 | if "@" in object_id: |
| 7057 | await _send_json( |
| 7058 | send, |
| 7059 | {"status": "error", "error": "Station routing is not available in this server"}, |
| 7060 | status=400, |
| 7061 | ) |
| 7062 | return |
| 7063 | |
| 7064 | if _is_sensitive_get(query) and not _caller_owns_user_object(object_id, headers): |
| 7065 | gate_error = _admin_token_gate_error( |
| 7066 | headers, |
| 7067 | f"Object introspection requires {ADMIN_TOKEN_ENV}.", |
| 7068 | ) |
| 7069 | if gate_error is not None: |
| 7070 | status, message = gate_error |
| 7071 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 7072 | return |
| 7073 | |
| 7074 | if query.get("versions") == "true": |
| 7075 | if await _send_permission_denied_if_needed( |
| 7076 | send, |
| 7077 | headers, |
| 7078 | object_permissions.VERSIONS, |
| 7079 | object_id=object_id, |
| 7080 | method="GET", |
| 7081 | ): |
| 7082 | return |
| 7083 | await _handle_object_versions_get(send, object_id, query) |
| 7084 | return |
| 7085 | |
| 7086 | if "version" in query: |
| 7087 | if await _send_permission_denied_if_needed( |
| 7088 | send, |
| 7089 | headers, |
| 7090 | object_permissions.VERSIONS, |
| 7091 | object_id=object_id, |
| 7092 | method="GET", |
| 7093 | ): |
| 7094 | return |
| 7095 | await _handle_object_version_get(send, object_id, query) |
| 7096 | return |
| 7097 | |
| 7098 | if query.get("state") == "true": |
| 7099 | if await _send_permission_denied_if_needed( |
| 7100 | send, |
| 7101 | headers, |
| 7102 | object_permissions.STATE, |
| 7103 | object_id=object_id, |
| 7104 | method="GET", |
| 7105 | ): |
| 7106 | return |
| 7107 | await _handle_object_state_get(send, object_id) |
| 7108 | return |
| 7109 | |
| 7110 | if query.get("logs") == "true": |
| 7111 | if await _send_permission_denied_if_needed( |
| 7112 | send, |
| 7113 | headers, |
| 7114 | object_permissions.LOGS, |
| 7115 | object_id=object_id, |
| 7116 | method="GET", |
| 7117 | ): |
| 7118 | return |
| 7119 | await _handle_object_logs_get(send, object_id, query) |
| 7120 | return |
| 7121 | |
| 7122 | if query.get("source_changes") == "true": |
| 7123 | if await _send_permission_denied_if_needed( |
| 7124 | send, |
| 7125 | headers, |
| 7126 | object_permissions.SOURCE, |
| 7127 | object_id=object_id, |
| 7128 | method="GET", |
| 7129 | ): |
| 7130 | return |
| 7131 | await _handle_object_source_changes_get(send, object_id, query) |
| 7132 | return |
| 7133 | |
| 7134 | if query.get("changes") == "true": |
| 7135 | if await _send_permission_denied_if_needed( |
| 7136 | send, |
| 7137 | headers, |
| 7138 | object_permissions.SOURCE, |
| 7139 | object_id=object_id, |
| 7140 | method="GET", |
| 7141 | ): |
| 7142 | return |
| 7143 | await _handle_object_changes_get(send, object_id, query) |
| 7144 | return |
| 7145 | |
| 7146 | if query.get("files") == "true": |
| 7147 | if await _send_permission_denied_if_needed( |
| 7148 | send, |
| 7149 | headers, |
| 7150 | object_permissions.FILES, |
| 7151 | object_id=object_id, |
| 7152 | method="GET", |
| 7153 | ): |
| 7154 | return |
| 7155 | await _handle_object_files_get(send, object_id) |
| 7156 | return |
| 7157 | |
| 7158 | if "file" in query: |
| 7159 | if await _send_permission_denied_if_needed( |
| 7160 | send, |
| 7161 | headers, |
| 7162 | object_permissions.FILES, |
| 7163 | object_id=object_id, |
| 7164 | method="GET", |
| 7165 | ): |
| 7166 | return |
| 7167 | await _handle_object_file_get(send, object_id, query) |
| 7168 | return |
| 7169 | |
| 7170 | if query.get("schedules") == "true": |
| 7171 | if await _send_permission_denied_if_needed( |
| 7172 | send, |
| 7173 | headers, |
| 7174 | object_permissions.STATE, |
| 7175 | object_id=object_id, |
| 7176 | method="GET", |
| 7177 | ): |
| 7178 | return |
| 7179 | await _handle_object_schedules_get(send, object_id) |
| 7180 | return |
| 7181 | |
| 7182 | if query.get("metadata") == "true": |
| 7183 | if await _send_permission_denied_if_needed( |
| 7184 | send, |
| 7185 | headers, |
| 7186 | object_permissions.READ, |
| 7187 | object_id=object_id, |
| 7188 | method="GET", |
| 7189 | ): |
| 7190 | return |
| 7191 | await _handle_object_metadata_get(send, object_id) |
| 7192 | return |
| 7193 | |
| 7194 | if query.get("source") == "true": |
| 7195 | if await _send_permission_denied_if_needed( |
| 7196 | send, |
| 7197 | headers, |
| 7198 | object_permissions.SOURCE, |
| 7199 | object_id=object_id, |
| 7200 | method="GET", |
| 7201 | ): |
| 7202 | return |
| 7203 | await _handle_object_source_get(send, object_id) |
| 7204 | return |
| 7205 | |
| 7206 | await _execute_object_method( |
| 7207 | send, |
| 7208 | object_id, |
| 7209 | "GET", |
| 7210 | query, |
| 7211 | headers, |
| 7212 | permission_action=object_permissions.EXECUTE, |
| 7213 | ) |
| 7214 | |
| 7215 | |
| 7216 | async def _handle_object_source_get(send, object_id: str) -> None: |
| 7217 | try: |
| 7218 | source = object_source.get_object_source(object_id) |
| 7219 | except InvalidObjectIdError as exc: |
| 7220 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7221 | return |
| 7222 | except object_source.ObjectSourceNotFoundError as exc: |
| 7223 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7224 | return |
| 7225 | |
| 7226 | await _send_json( |
| 7227 | send, |
| 7228 | { |
| 7229 | "status": "ok", |
| 7230 | "object_id": object_id, |
| 7231 | "source": source, |
| 7232 | }, |
| 7233 | ) |
| 7234 | |
| 7235 | |
| 7236 | async def _handle_object_state_get(send, object_id: str) -> None: |
| 7237 | try: |
| 7238 | _ensure_object_source_exists(object_id) |
| 7239 | state = object_state.get_object_state(object_id, base_dir=_data_dir()) |
| 7240 | except InvalidObjectIdError as exc: |
| 7241 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7242 | return |
| 7243 | except object_source.ObjectSourceNotFoundError as exc: |
| 7244 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7245 | return |
| 7246 | |
| 7247 | await _send_json( |
| 7248 | send, |
| 7249 | { |
| 7250 | "status": "ok", |
| 7251 | "object_id": object_id, |
| 7252 | "state": state, |
| 7253 | }, |
| 7254 | ) |
| 7255 | |
| 7256 | |
| 7257 | async def _handle_object_schedules_get(send, object_id: str) -> None: |
| 7258 | """The owner's view of their object's self-scheduled methods.""" |
| 7259 | tasks = await asyncio.to_thread( |
| 7260 | object_schedule.list_object_tasks, object_id, base_dir=_data_dir() |
| 7261 | ) |
| 7262 | await _send_json( |
| 7263 | send, {"status": "ok", "object_id": object_id, "schedules": tasks} |
| 7264 | ) |
| 7265 | |
| 7266 | |
| 7267 | async def _handle_object_metadata_get(send, object_id: str) -> None: |
| 7268 | try: |
| 7269 | metadata = object_metadata.get_object_metadata(object_id, base_dir=_data_dir()) |
| 7270 | except InvalidObjectIdError as exc: |
| 7271 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7272 | return |
| 7273 | except object_source.ObjectSourceNotFoundError as exc: |
| 7274 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7275 | return |
| 7276 | |
| 7277 | await _send_json( |
| 7278 | send, |
| 7279 | { |
| 7280 | "status": "ok", |
| 7281 | "object_id": object_id, |
| 7282 | "metadata": metadata, |
| 7283 | }, |
| 7284 | ) |
| 7285 | |
| 7286 | |
| 7287 | async def _handle_object_logs_get( |
| 7288 | send, |
| 7289 | object_id: str, |
| 7290 | query: dict[str, str], |
| 7291 | ) -> None: |
| 7292 | try: |
| 7293 | _ensure_object_source_exists(object_id) |
| 7294 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 7295 | logs = object_logs.get_object_logs( |
| 7296 | object_id, |
| 7297 | base_dir=_data_dir(), |
| 7298 | level=query.get("level"), |
| 7299 | limit=limit, |
| 7300 | ) |
| 7301 | except ValueError as exc: |
| 7302 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7303 | return |
| 7304 | except InvalidObjectIdError as exc: |
| 7305 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7306 | return |
| 7307 | except object_source.ObjectSourceNotFoundError as exc: |
| 7308 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7309 | return |
| 7310 | |
| 7311 | await _send_json( |
| 7312 | send, |
| 7313 | { |
| 7314 | "status": "ok", |
| 7315 | "object_id": object_id, |
| 7316 | "logs": logs, |
| 7317 | "count": len(logs), |
| 7318 | }, |
| 7319 | ) |
| 7320 | |
| 7321 | |
| 7322 | async def _handle_object_source_changes_get( |
| 7323 | send, |
| 7324 | object_id: str, |
| 7325 | query: dict[str, str], |
| 7326 | ) -> None: |
| 7327 | try: |
| 7328 | _ensure_object_source_exists(object_id) |
| 7329 | limit = _query_int( |
| 7330 | query, |
| 7331 | "limit", |
| 7332 | default=100, |
| 7333 | minimum=1, |
| 7334 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 7335 | ) |
| 7336 | offset = _query_int( |
| 7337 | query, |
| 7338 | "offset", |
| 7339 | default=0, |
| 7340 | minimum=0, |
| 7341 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 7342 | ) |
| 7343 | payload = object_source_changes.list_source_changes( |
| 7344 | object_id, |
| 7345 | base_dir=_data_dir(), |
| 7346 | limit=limit, |
| 7347 | offset=offset, |
| 7348 | ) |
| 7349 | except ValueError as exc: |
| 7350 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7351 | return |
| 7352 | except InvalidObjectIdError as exc: |
| 7353 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7354 | return |
| 7355 | except object_source.ObjectSourceNotFoundError as exc: |
| 7356 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7357 | return |
| 7358 | |
| 7359 | await _send_json(send, {"status": "ok", **payload}) |
| 7360 | |
| 7361 | |
| 7362 | async def _handle_object_changes_get( |
| 7363 | send, |
| 7364 | object_id: str, |
| 7365 | query: dict[str, str], |
| 7366 | ) -> None: |
| 7367 | try: |
| 7368 | _ensure_object_source_exists(object_id) |
| 7369 | limit = _query_int( |
| 7370 | query, |
| 7371 | "limit", |
| 7372 | default=100, |
| 7373 | minimum=1, |
| 7374 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 7375 | ) |
| 7376 | offset = _query_int( |
| 7377 | query, |
| 7378 | "offset", |
| 7379 | default=0, |
| 7380 | minimum=0, |
| 7381 | maximum=object_source_changes.MAX_CHANGE_LIMIT, |
| 7382 | ) |
| 7383 | payload = _object_changes_payload(object_id, query, limit=limit, offset=offset) |
| 7384 | except ValueError as exc: |
| 7385 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7386 | return |
| 7387 | except InvalidObjectIdError as exc: |
| 7388 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7389 | return |
| 7390 | except object_file_changes.InvalidFileChangeError as exc: |
| 7391 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7392 | return |
| 7393 | except object_source.ObjectSourceNotFoundError as exc: |
| 7394 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7395 | return |
| 7396 | except OSError as exc: |
| 7397 | await _send_json( |
| 7398 | send, |
| 7399 | {"status": "error", "error": f"Could not list object changes: {exc}"}, |
| 7400 | status=500, |
| 7401 | ) |
| 7402 | return |
| 7403 | |
| 7404 | await _send_json(send, {"status": "ok", **payload}) |
| 7405 | |
| 7406 | |
| 7407 | def _object_changes_payload( |
| 7408 | object_id: str, |
| 7409 | query: dict[str, str], |
| 7410 | *, |
| 7411 | limit: int, |
| 7412 | offset: int, |
| 7413 | ) -> dict[str, Any]: |
| 7414 | kind = _admin_change_kind_filter(query) |
| 7415 | if kind not in {None, "source", "file"}: |
| 7416 | raise ValueError("Object changes only support kind=source or kind=file") |
| 7417 | |
| 7418 | entries: list[dict[str, Any]] = [] |
| 7419 | if kind in {None, "source"}: |
| 7420 | entries.extend(_source_admin_changes(object_id=object_id)) |
| 7421 | if kind in {None, "file"}: |
| 7422 | entries.extend( |
| 7423 | _file_admin_changes( |
| 7424 | object_id=object_id, |
| 7425 | file_name=_admin_change_file_filter(query), |
| 7426 | ) |
| 7427 | ) |
| 7428 | |
| 7429 | entries = _sort_admin_changes(entries) |
| 7430 | total = len(entries) |
| 7431 | window = entries[offset:offset + limit] |
| 7432 | return { |
| 7433 | "object_id": object_id, |
| 7434 | "changes": window, |
| 7435 | "count": len(window), |
| 7436 | "total": total, |
| 7437 | "limit": limit, |
| 7438 | "offset": offset, |
| 7439 | "has_more": offset + len(window) < total, |
| 7440 | } |
| 7441 | |
| 7442 | |
| 7443 | def _admin_changes_payload( |
| 7444 | query: dict[str, str], |
| 7445 | *, |
| 7446 | limit: int, |
| 7447 | offset: int, |
| 7448 | ) -> dict[str, Any]: |
| 7449 | kind = _admin_change_kind_filter(query) |
| 7450 | object_id = _admin_change_object_filter(query) |
| 7451 | collection = _admin_change_collection_filter(query) |
| 7452 | record_id = _admin_change_record_filter(query) |
| 7453 | package_id = _admin_change_package_filter(query) |
| 7454 | file_name = _admin_change_file_filter(query) |
| 7455 | |
| 7456 | entries: list[dict[str, Any]] = [] |
| 7457 | if kind in {None, "source"}: |
| 7458 | entries.extend(_source_admin_changes(object_id=object_id)) |
| 7459 | if kind in {None, "file"}: |
| 7460 | entries.extend(_file_admin_changes(object_id=object_id, file_name=file_name)) |
| 7461 | if kind in {None, "record"}: |
| 7462 | entries.extend(_record_admin_changes(collection=collection, record_id=record_id)) |
| 7463 | if kind in {None, "package"}: |
| 7464 | entries.extend(_package_admin_changes(package_id=package_id)) |
| 7465 | |
| 7466 | entries = [ |
| 7467 | entry |
| 7468 | for entry in entries |
| 7469 | if _admin_change_matches( |
| 7470 | entry, |
| 7471 | object_id=object_id, |
| 7472 | collection=collection, |
| 7473 | record_id=record_id, |
| 7474 | package_id=package_id, |
| 7475 | file_name=file_name, |
| 7476 | ) |
| 7477 | ] |
| 7478 | entries = _sort_admin_changes(entries) |
| 7479 | total = len(entries) |
| 7480 | window = entries[offset:offset + limit] |
| 7481 | return { |
| 7482 | "changes": window, |
| 7483 | "count": len(window), |
| 7484 | "total": total, |
| 7485 | "limit": limit, |
| 7486 | "offset": offset, |
| 7487 | "has_more": offset + len(window) < total, |
| 7488 | "filters": { |
| 7489 | "kind": kind, |
| 7490 | "object_id": object_id, |
| 7491 | "collection": collection, |
| 7492 | "record_id": record_id, |
| 7493 | "package_id": package_id, |
| 7494 | "file": file_name, |
| 7495 | }, |
| 7496 | } |
| 7497 | |
| 7498 | |
| 7499 | def _source_admin_changes(object_id: str | None = None) -> list[dict[str, Any]]: |
| 7500 | changes: list[dict[str, Any]] = [] |
| 7501 | for candidate in _admin_change_object_ids( |
| 7502 | object_source_changes.SOURCE_CHANGES_DIR, |
| 7503 | object_id=object_id, |
| 7504 | ): |
| 7505 | payload = object_source_changes.list_source_changes( |
| 7506 | candidate, |
| 7507 | base_dir=_data_dir(), |
| 7508 | limit=object_source_changes.MAX_CHANGE_LIMIT, |
| 7509 | ) |
| 7510 | changes.extend(_normalize_source_admin_change(change) for change in payload["changes"]) |
| 7511 | return changes |
| 7512 | |
| 7513 | |
| 7514 | def _file_admin_changes( |
| 7515 | object_id: str | None = None, |
| 7516 | file_name: str | None = None, |
| 7517 | ) -> list[dict[str, Any]]: |
| 7518 | changes: list[dict[str, Any]] = [] |
| 7519 | for candidate in _admin_change_object_ids( |
| 7520 | object_file_changes.FILE_CHANGES_DIR, |
| 7521 | object_id=object_id, |
| 7522 | ): |
| 7523 | payload = object_file_changes.list_file_changes( |
| 7524 | candidate, |
| 7525 | file_name=file_name, |
| 7526 | base_dir=_data_dir(), |
| 7527 | limit=object_file_changes.MAX_CHANGE_LIMIT, |
| 7528 | ) |
| 7529 | changes.extend(_normalize_file_admin_change(change) for change in payload["changes"]) |
| 7530 | return changes |
| 7531 | |
| 7532 | |
| 7533 | def _record_admin_changes( |
| 7534 | collection: str | None = None, |
| 7535 | record_id: str | None = None, |
| 7536 | ) -> list[dict[str, Any]]: |
| 7537 | changes: list[dict[str, Any]] = [] |
| 7538 | for candidate in _admin_change_collections(collection=collection): |
| 7539 | payload = object_record_changes.list_record_changes( |
| 7540 | candidate, |
| 7541 | record_id=record_id, |
| 7542 | base_dir=_data_dir(), |
| 7543 | limit=object_record_changes.MAX_CHANGE_LIMIT, |
| 7544 | ) |
| 7545 | changes.extend(_normalize_record_admin_change(change) for change in payload["changes"]) |
| 7546 | return changes |
| 7547 | |
| 7548 | |
| 7549 | def _package_admin_changes(package_id: str | None = None) -> list[dict[str, Any]]: |
| 7550 | changes: list[dict[str, Any]] = [] |
| 7551 | for candidate in _admin_change_package_ids(package_id=package_id): |
| 7552 | payload = object_package_changes.list_package_changes( |
| 7553 | candidate, |
| 7554 | base_dir=_data_dir(), |
| 7555 | limit=object_package_changes.MAX_CHANGE_LIMIT, |
| 7556 | ) |
| 7557 | changes.extend(_normalize_package_admin_change(change) for change in payload["changes"]) |
| 7558 | return changes |
| 7559 | |
| 7560 | |
| 7561 | def _admin_change_object_ids( |
| 7562 | change_dir: str, |
| 7563 | *, |
| 7564 | object_id: str | None, |
| 7565 | ) -> list[str]: |
| 7566 | if object_id is not None: |
| 7567 | if not validate_object_id(object_id): |
| 7568 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 7569 | return [object_id] |
| 7570 | |
| 7571 | root = Path(_data_dir()) / change_dir |
| 7572 | if not root.exists(): |
| 7573 | return [] |
| 7574 | if not root.is_dir(): |
| 7575 | raise OSError(f"Change root is not a directory: {root}") |
| 7576 | return sorted( |
| 7577 | path.name |
| 7578 | for path in root.iterdir() |
| 7579 | if path.is_dir() and validate_object_id(path.name) |
| 7580 | ) |
| 7581 | |
| 7582 | |
| 7583 | def _admin_change_collections(*, collection: str | None) -> list[str]: |
| 7584 | if collection is not None: |
| 7585 | if not object_collections.validate_collection_name(collection): |
| 7586 | raise object_collections.InvalidCollectionNameError( |
| 7587 | f"Invalid collection name: {collection}" |
| 7588 | ) |
| 7589 | return [collection] |
| 7590 | |
| 7591 | root = Path(_data_dir()) / object_record_changes.RECORD_CHANGES_DIR |
| 7592 | if not root.exists(): |
| 7593 | return [] |
| 7594 | if not root.is_dir(): |
| 7595 | raise OSError(f"Change root is not a directory: {root}") |
| 7596 | return sorted( |
| 7597 | path.name |
| 7598 | for path in root.iterdir() |
| 7599 | if path.is_dir() and object_collections.validate_collection_name(path.name) |
| 7600 | ) |
| 7601 | |
| 7602 | |
| 7603 | def _admin_change_package_ids(*, package_id: str | None) -> list[str]: |
| 7604 | if package_id is not None: |
| 7605 | if not object_packages.validate_package_id(package_id): |
| 7606 | raise object_packages.InvalidPackageIdError(f"Invalid package id: {package_id}") |
| 7607 | return [package_id] |
| 7608 | |
| 7609 | root = Path(_data_dir()) / object_package_changes.PACKAGE_CHANGES_DIR |
| 7610 | if not root.exists(): |
| 7611 | return [] |
| 7612 | if not root.is_dir(): |
| 7613 | raise OSError(f"Change root is not a directory: {root}") |
| 7614 | return sorted( |
| 7615 | path.name |
| 7616 | for path in root.iterdir() |
| 7617 | if path.is_dir() and object_packages.validate_package_id(path.name) |
| 7618 | ) |
| 7619 | |
| 7620 | |
| 7621 | def _admin_change_kind_filter(query: dict[str, str]) -> str | None: |
| 7622 | kind = _optional_query_text(query, "kind") |
| 7623 | if kind is None: |
| 7624 | return None |
| 7625 | if kind not in ADMIN_CHANGE_KINDS: |
| 7626 | allowed = ", ".join(sorted(ADMIN_CHANGE_KINDS)) |
| 7627 | raise ValueError(f"Query parameter 'kind' must be one of: {allowed}") |
| 7628 | return kind |
| 7629 | |
| 7630 | |
| 7631 | def _admin_change_object_filter(query: dict[str, str]) -> str | None: |
| 7632 | object_id = _optional_query_text(query, "object_id") |
| 7633 | if object_id is not None and not validate_object_id(object_id): |
| 7634 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 7635 | return object_id |
| 7636 | |
| 7637 | |
| 7638 | def _admin_change_collection_filter(query: dict[str, str]) -> str | None: |
| 7639 | collection = _optional_query_text(query, "collection") |
| 7640 | if collection is not None and not object_collections.validate_collection_name(collection): |
| 7641 | raise object_collections.InvalidCollectionNameError( |
| 7642 | f"Invalid collection name: {collection}" |
| 7643 | ) |
| 7644 | return collection |
| 7645 | |
| 7646 | |
| 7647 | def _admin_change_record_filter(query: dict[str, str]) -> str | None: |
| 7648 | record_id = _optional_query_text(query, "record_id") |
| 7649 | if record_id is not None and not object_records.validate_record_id(record_id): |
| 7650 | raise object_records.InvalidRecordIdError(f"Invalid record id: {record_id}") |
| 7651 | return record_id |
| 7652 | |
| 7653 | |
| 7654 | def _admin_change_package_filter(query: dict[str, str]) -> str | None: |
| 7655 | package_id = _optional_query_text(query, "package_id") |
| 7656 | if package_id is not None and not object_packages.validate_package_id(package_id): |
| 7657 | raise object_packages.InvalidPackageIdError(f"Invalid package id: {package_id}") |
| 7658 | return package_id |
| 7659 | |
| 7660 | |
| 7661 | def _admin_change_file_filter(query: dict[str, str]) -> str | None: |
| 7662 | file_name = _optional_query_text(query, "file") |
| 7663 | if file_name is None: |
| 7664 | return None |
| 7665 | if "\x00" in file_name or file_name.startswith("/") or ".." in file_name: |
| 7666 | raise object_file_changes.InvalidFileChangeError(f"Invalid file name: {file_name!r}") |
| 7667 | path = Path(file_name) |
| 7668 | if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts): |
| 7669 | raise object_file_changes.InvalidFileChangeError(f"Invalid file name: {file_name!r}") |
| 7670 | return path.as_posix() |
| 7671 | |
| 7672 | |
| 7673 | def _admin_change_matches( |
| 7674 | entry: dict[str, Any], |
| 7675 | *, |
| 7676 | object_id: str | None, |
| 7677 | collection: str | None, |
| 7678 | record_id: str | None, |
| 7679 | package_id: str | None, |
| 7680 | file_name: str | None, |
| 7681 | ) -> bool: |
| 7682 | target = entry.get("target", {}) |
| 7683 | if not isinstance(target, dict): |
| 7684 | return False |
| 7685 | if object_id is not None and target.get("object_id") != object_id: |
| 7686 | return False |
| 7687 | if collection is not None and target.get("collection") != collection: |
| 7688 | return False |
| 7689 | if record_id is not None and target.get("record_id") != record_id: |
| 7690 | return False |
| 7691 | if package_id is not None and target.get("package_id") != package_id: |
| 7692 | return False |
| 7693 | if file_name is not None and target.get("file_name") != file_name: |
| 7694 | return False |
| 7695 | return True |
| 7696 | |
| 7697 | |
| 7698 | def _sort_admin_changes(entries: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| 7699 | return sorted( |
| 7700 | entries, |
| 7701 | key=lambda entry: ( |
| 7702 | str(entry.get("timestamp") or ""), |
| 7703 | str(entry.get("change_id") or ""), |
| 7704 | ), |
| 7705 | reverse=True, |
| 7706 | ) |
| 7707 | |
| 7708 | |
| 7709 | def _normalize_source_admin_change(change: Mapping[str, Any]) -> dict[str, Any]: |
| 7710 | return { |
| 7711 | "kind": "source", |
| 7712 | "change_id": change.get("change_id"), |
| 7713 | "timestamp": change.get("timestamp"), |
| 7714 | "action": change.get("action"), |
| 7715 | "actor": change.get("actor"), |
| 7716 | "summary": change.get("message") or _source_change_summary(change), |
| 7717 | "correlation_id": change.get("correlation_id"), |
| 7718 | "target": { |
| 7719 | "object_id": change.get("object_id"), |
| 7720 | "version_id": change.get("version_id"), |
| 7721 | "from_version_id": change.get("from_version_id"), |
| 7722 | }, |
| 7723 | "change": dict(change), |
| 7724 | } |
| 7725 | |
| 7726 | |
| 7727 | def _normalize_file_admin_change(change: Mapping[str, Any]) -> dict[str, Any]: |
| 7728 | return { |
| 7729 | "kind": "file", |
| 7730 | "change_id": change.get("change_id"), |
| 7731 | "timestamp": change.get("timestamp"), |
| 7732 | "action": change.get("action"), |
| 7733 | "actor": change.get("actor"), |
| 7734 | "summary": change.get("message") or _file_change_summary(change), |
| 7735 | "correlation_id": change.get("correlation_id"), |
| 7736 | "target": { |
| 7737 | "object_id": change.get("object_id"), |
| 7738 | "file_name": change.get("file_name"), |
| 7739 | "file_size": change.get("file_size"), |
| 7740 | }, |
| 7741 | "change": dict(change), |
| 7742 | } |
| 7743 | |
| 7744 | |
| 7745 | def _normalize_record_admin_change(change: Mapping[str, Any]) -> dict[str, Any]: |
| 7746 | return { |
| 7747 | "kind": "record", |
| 7748 | "change_id": change.get("change_id"), |
| 7749 | "timestamp": change.get("timestamp"), |
| 7750 | "action": change.get("action"), |
| 7751 | "actor": change.get("actor"), |
| 7752 | "summary": change.get("message") or _record_change_summary(change), |
| 7753 | "correlation_id": change.get("correlation_id"), |
| 7754 | "target": { |
| 7755 | "collection": change.get("collection"), |
| 7756 | "record_id": change.get("record_id"), |
| 7757 | "changed_fields": change.get("changed_fields", []), |
| 7758 | }, |
| 7759 | "change": dict(change), |
| 7760 | } |
| 7761 | |
| 7762 | |
| 7763 | def _normalize_package_admin_change(change: Mapping[str, Any]) -> dict[str, Any]: |
| 7764 | return { |
| 7765 | "kind": "package", |
| 7766 | "change_id": change.get("change_id"), |
| 7767 | "timestamp": change.get("timestamp"), |
| 7768 | "action": change.get("action"), |
| 7769 | "actor": change.get("actor"), |
| 7770 | "summary": change.get("message") or _package_change_summary(change), |
| 7771 | "correlation_id": change.get("correlation_id"), |
| 7772 | "target": { |
| 7773 | "package_id": change.get("package_id"), |
| 7774 | "package_version": change.get("package_version"), |
| 7775 | }, |
| 7776 | "change": dict(change), |
| 7777 | } |
| 7778 | |
| 7779 | |
| 7780 | def _source_change_summary(change: Mapping[str, Any]) -> str: |
| 7781 | return f"{change.get('action', 'source_change')} {change.get('object_id', '')}".strip() |
| 7782 | |
| 7783 | |
| 7784 | def _file_change_summary(change: Mapping[str, Any]) -> str: |
| 7785 | return f"{change.get('action', 'file_change')} {change.get('file_name', '')}".strip() |
| 7786 | |
| 7787 | |
| 7788 | def _record_change_summary(change: Mapping[str, Any]) -> str: |
| 7789 | return ( |
| 7790 | f"{change.get('action', 'record_change')} " |
| 7791 | f"{change.get('collection', '')}/{change.get('record_id', '')}" |
| 7792 | ).strip() |
| 7793 | |
| 7794 | |
| 7795 | def _package_change_summary(change: Mapping[str, Any]) -> str: |
| 7796 | return f"{change.get('action', 'package_change')} {change.get('package_id', '')}".strip() |
| 7797 | |
| 7798 | |
| 7799 | async def _handle_object_files_get(send, object_id: str) -> None: |
| 7800 | try: |
| 7801 | _ensure_object_source_exists(object_id) |
| 7802 | files = object_files.list_object_files(object_id, base_dir=_data_dir()) |
| 7803 | except InvalidObjectIdError as exc: |
| 7804 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7805 | return |
| 7806 | except object_source.ObjectSourceNotFoundError as exc: |
| 7807 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7808 | return |
| 7809 | except OSError as exc: |
| 7810 | await _send_json( |
| 7811 | send, |
| 7812 | {"status": "error", "error": f"Could not read object files: {exc}"}, |
| 7813 | status=500, |
| 7814 | ) |
| 7815 | return |
| 7816 | |
| 7817 | await _send_json( |
| 7818 | send, |
| 7819 | { |
| 7820 | "status": "ok", |
| 7821 | "object_id": object_id, |
| 7822 | "files": files, |
| 7823 | "count": len(files), |
| 7824 | }, |
| 7825 | ) |
| 7826 | |
| 7827 | |
| 7828 | async def _handle_object_file_get( |
| 7829 | send, |
| 7830 | object_id: str, |
| 7831 | query: dict[str, str], |
| 7832 | ) -> None: |
| 7833 | filename = query.get("file", "") |
| 7834 | try: |
| 7835 | _ensure_object_source_exists(object_id) |
| 7836 | content, metadata = object_files.read_object_file( |
| 7837 | object_id, |
| 7838 | filename, |
| 7839 | base_dir=_data_dir(), |
| 7840 | ) |
| 7841 | except object_files.InvalidObjectFilenameError as exc: |
| 7842 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7843 | return |
| 7844 | except InvalidObjectIdError as exc: |
| 7845 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7846 | return |
| 7847 | except object_source.ObjectSourceNotFoundError as exc: |
| 7848 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7849 | return |
| 7850 | except object_files.ObjectFileNotFoundError as exc: |
| 7851 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7852 | return |
| 7853 | except OSError as exc: |
| 7854 | await _send_json( |
| 7855 | send, |
| 7856 | {"status": "error", "error": f"Could not read object file: {exc}"}, |
| 7857 | status=500, |
| 7858 | ) |
| 7859 | return |
| 7860 | |
| 7861 | content_type, _ = mimetypes.guess_type(metadata["name"]) |
| 7862 | if content_type is None: |
| 7863 | content_type = "application/octet-stream" |
| 7864 | |
| 7865 | disposition = "inline" if content_type.startswith("image/") else "attachment" |
| 7866 | download_name = _download_filename(metadata["name"]) |
| 7867 | await _send_response( |
| 7868 | send, |
| 7869 | status=200, |
| 7870 | headers=[ |
| 7871 | ("content-type", content_type), |
| 7872 | ("content-length", str(len(content))), |
| 7873 | ("content-disposition", f'{disposition}; filename="{download_name}"'), |
| 7874 | ], |
| 7875 | body=content, |
| 7876 | ) |
| 7877 | |
| 7878 | |
| 7879 | async def _handle_object_versions_get( |
| 7880 | send, |
| 7881 | object_id: str, |
| 7882 | query: dict[str, str], |
| 7883 | ) -> None: |
| 7884 | try: |
| 7885 | _ensure_object_source_exists(object_id) |
| 7886 | limit = _query_int(query, "limit", default=10, minimum=1, maximum=100) |
| 7887 | versions = _version_manager().get_history(object_id, limit=limit) |
| 7888 | except ValueError as exc: |
| 7889 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7890 | return |
| 7891 | except InvalidObjectIdError as exc: |
| 7892 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7893 | return |
| 7894 | except object_source.ObjectSourceNotFoundError as exc: |
| 7895 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7896 | return |
| 7897 | |
| 7898 | await _send_json( |
| 7899 | send, |
| 7900 | { |
| 7901 | "status": "ok", |
| 7902 | "object_id": object_id, |
| 7903 | "versions": versions, |
| 7904 | "count": len(versions), |
| 7905 | }, |
| 7906 | ) |
| 7907 | |
| 7908 | |
| 7909 | async def _handle_object_version_get( |
| 7910 | send, |
| 7911 | object_id: str, |
| 7912 | query: dict[str, str], |
| 7913 | ) -> None: |
| 7914 | try: |
| 7915 | _ensure_object_source_exists(object_id) |
| 7916 | version_id = _query_int(query, "version", minimum=1) |
| 7917 | version = _version_manager().get_version(object_id, version_id) |
| 7918 | except ValueError as exc: |
| 7919 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7920 | return |
| 7921 | except InvalidObjectIdError as exc: |
| 7922 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7923 | return |
| 7924 | except object_source.ObjectSourceNotFoundError as exc: |
| 7925 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 7926 | return |
| 7927 | |
| 7928 | if version is None: |
| 7929 | await _send_json( |
| 7930 | send, |
| 7931 | {"status": "error", "error": f"Version {version_id} not found for object {object_id}"}, |
| 7932 | status=404, |
| 7933 | ) |
| 7934 | return |
| 7935 | |
| 7936 | await _send_json( |
| 7937 | send, |
| 7938 | { |
| 7939 | "status": "ok", |
| 7940 | "object_id": object_id, |
| 7941 | "version": version, |
| 7942 | }, |
| 7943 | ) |
| 7944 | |
| 7945 | |
| 7946 | async def _handle_object_post( |
| 7947 | send, |
| 7948 | object_id: str, |
| 7949 | body: bytes, |
| 7950 | query: dict[str, str], |
| 7951 | headers: dict[str, str], |
| 7952 | ) -> None: |
| 7953 | if "@" in object_id: |
| 7954 | await _send_json( |
| 7955 | send, |
| 7956 | {"status": "error", "error": "Station routing is not available in this server"}, |
| 7957 | status=400, |
| 7958 | ) |
| 7959 | return |
| 7960 | |
| 7961 | try: |
| 7962 | payload = _parse_post_payload(body, query, headers) |
| 7963 | except ValueError as exc: |
| 7964 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 7965 | return |
| 7966 | |
| 7967 | if payload.get("action") == "rollback": |
| 7968 | await _handle_object_rollback_post(send, object_id, payload, headers) |
| 7969 | return |
| 7970 | |
| 7971 | await _execute_object_method( |
| 7972 | send, |
| 7973 | object_id, |
| 7974 | "POST", |
| 7975 | payload, |
| 7976 | headers, |
| 7977 | permission_action=object_permissions.EXECUTE, |
| 7978 | ) |
| 7979 | |
| 7980 | |
| 7981 | async def _handle_object_body_method( |
| 7982 | send, |
| 7983 | object_id: str, |
| 7984 | method: str, |
| 7985 | body: bytes, |
| 7986 | query: dict[str, str], |
| 7987 | headers: dict[str, str], |
| 7988 | ) -> None: |
| 7989 | if "@" in object_id: |
| 7990 | await _send_json( |
| 7991 | send, |
| 7992 | {"status": "error", "error": "Station routing is not available in this server"}, |
| 7993 | status=400, |
| 7994 | ) |
| 7995 | return |
| 7996 | |
| 7997 | try: |
| 7998 | if body.strip() and _is_form_content_type(headers): |
| 7999 | payload: dict[str, Any] = _form_fields_payload(body) |
| 8000 | elif body.strip() and _is_multipart_content_type(headers): |
| 8001 | payload = object_multipart.parse_multipart(body, headers.get("content-type", "")) |
| 8002 | elif body.strip(): |
| 8003 | payload = _parse_json_body(body) |
| 8004 | else: |
| 8005 | payload = dict(query) |
| 8006 | except ValueError as exc: |
| 8007 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8008 | return |
| 8009 | |
| 8010 | permission_action = object_permissions.EXECUTE |
| 8011 | if method == "PUT": |
| 8012 | permission_action = object_permissions.UPDATE |
| 8013 | elif method == "DELETE": |
| 8014 | permission_action = object_permissions.DELETE |
| 8015 | |
| 8016 | await _execute_object_method( |
| 8017 | send, |
| 8018 | object_id, |
| 8019 | method, |
| 8020 | payload, |
| 8021 | headers, |
| 8022 | permission_action=permission_action, |
| 8023 | ) |
| 8024 | |
| 8025 | |
| 8026 | async def _handle_object_rollback_post( |
| 8027 | send, |
| 8028 | object_id: str, |
| 8029 | payload: dict[str, Any], |
| 8030 | headers: dict[str, str], |
| 8031 | ) -> None: |
| 8032 | gate_error = _object_source_write_gate_error(headers, object_id) |
| 8033 | if gate_error is not None: |
| 8034 | status, message = gate_error |
| 8035 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 8036 | return |
| 8037 | |
| 8038 | if await _send_permission_denied_if_needed( |
| 8039 | send, |
| 8040 | headers, |
| 8041 | object_permissions.SOURCE, |
| 8042 | object_id=object_id, |
| 8043 | method="POST", |
| 8044 | ): |
| 8045 | return |
| 8046 | |
| 8047 | try: |
| 8048 | version_id = _payload_int(payload, "version_id", minimum=1) |
| 8049 | author = _source_author(payload, headers) |
| 8050 | message = _payload_text(payload, "message", f"Rollback to version {version_id}") |
| 8051 | correlation_id = object_correlation.current_correlation_id() |
| 8052 | new_version_id = object_source.rollback_object_source( |
| 8053 | object_id=object_id, |
| 8054 | to_version=version_id, |
| 8055 | author=author, |
| 8056 | message=message, |
| 8057 | version_manager=_version_manager(), |
| 8058 | correlation_id=correlation_id, |
| 8059 | ) |
| 8060 | except ValueError as exc: |
| 8061 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8062 | return |
| 8063 | except InvalidObjectIdError as exc: |
| 8064 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8065 | return |
| 8066 | except object_source.ObjectSourceNotFoundError as exc: |
| 8067 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 8068 | return |
| 8069 | except object_versions.VersionNotFoundError as exc: |
| 8070 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 8071 | return |
| 8072 | |
| 8073 | object_handlers.invalidate() |
| 8074 | |
| 8075 | await _send_json( |
| 8076 | send, |
| 8077 | { |
| 8078 | "status": "ok", |
| 8079 | "message": f"Rolled back to version {version_id}", |
| 8080 | "version_id": version_id, |
| 8081 | "new_version_id": new_version_id, |
| 8082 | "object_id": object_id, |
| 8083 | "correlation_id": object_correlation.current_correlation_id(), |
| 8084 | }, |
| 8085 | ) |
| 8086 | _append_source_change_log( |
| 8087 | object_id, |
| 8088 | action="source_rollback", |
| 8089 | version_id=new_version_id, |
| 8090 | from_version_id=version_id, |
| 8091 | actor=author, |
| 8092 | message=message, |
| 8093 | correlation_id=correlation_id, |
| 8094 | ) |
| 8095 | |
| 8096 | |
| 8097 | async def _handle_object_source_put( |
| 8098 | send, |
| 8099 | object_id: str, |
| 8100 | body: bytes, |
| 8101 | headers: dict[str, str], |
| 8102 | ) -> None: |
| 8103 | if "@" in object_id: |
| 8104 | await _send_json( |
| 8105 | send, |
| 8106 | {"status": "error", "error": "Station routing is not available in this server"}, |
| 8107 | status=400, |
| 8108 | ) |
| 8109 | return |
| 8110 | |
| 8111 | gate_error = _object_source_write_gate_error(headers, object_id) |
| 8112 | if gate_error is not None: |
| 8113 | status, message = gate_error |
| 8114 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 8115 | return |
| 8116 | |
| 8117 | if await _send_permission_denied_if_needed( |
| 8118 | send, |
| 8119 | headers, |
| 8120 | object_permissions.SOURCE, |
| 8121 | object_id=object_id, |
| 8122 | method="PUT", |
| 8123 | ): |
| 8124 | return |
| 8125 | |
| 8126 | try: |
| 8127 | payload = _parse_json_body(body) |
| 8128 | except ValueError as exc: |
| 8129 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8130 | return |
| 8131 | |
| 8132 | code = payload.get("code") |
| 8133 | if not isinstance(code, str): |
| 8134 | await _send_json( |
| 8135 | send, |
| 8136 | {"status": "error", "error": "Request JSON field 'code' must be a string"}, |
| 8137 | status=400, |
| 8138 | ) |
| 8139 | return |
| 8140 | |
| 8141 | author = _source_author(payload, headers) |
| 8142 | message = _payload_text(payload, "message", "Updated via API") |
| 8143 | correlation_id = object_correlation.current_correlation_id() |
| 8144 | |
| 8145 | try: |
| 8146 | version_id = object_source.update_object_source( |
| 8147 | object_id=object_id, |
| 8148 | new_code=code, |
| 8149 | author=author, |
| 8150 | message=message, |
| 8151 | version_manager=_version_manager(), |
| 8152 | correlation_id=correlation_id, |
| 8153 | ) |
| 8154 | except InvalidObjectIdError as exc: |
| 8155 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8156 | return |
| 8157 | except object_source.ObjectSourceNotFoundError as exc: |
| 8158 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 8159 | return |
| 8160 | |
| 8161 | object_handlers.invalidate() |
| 8162 | |
| 8163 | methods, method_warnings = object_source.source_method_report(code) |
| 8164 | await _send_json( |
| 8165 | send, |
| 8166 | { |
| 8167 | "status": "ok", |
| 8168 | "message": f"Code updated to version {version_id}", |
| 8169 | "version_id": version_id, |
| 8170 | "object_id": object_id, |
| 8171 | "methods": methods, |
| 8172 | "warnings": method_warnings, |
| 8173 | "correlation_id": object_correlation.current_correlation_id(), |
| 8174 | }, |
| 8175 | ) |
| 8176 | _append_source_change_log( |
| 8177 | object_id, |
| 8178 | action="source_update", |
| 8179 | version_id=version_id, |
| 8180 | actor=author, |
| 8181 | message=message, |
| 8182 | correlation_id=correlation_id, |
| 8183 | ) |
| 8184 | |
| 8185 | |
| 8186 | async def _handle_object_destroy( |
| 8187 | send, |
| 8188 | object_id: str, |
| 8189 | headers: dict[str, str], |
| 8190 | ) -> None: |
| 8191 | """DELETE /objects/{id}?destroy=true: remove the source, never execute it. |
| 8192 | |
| 8193 | Same gates as the source PUT. Versions, state and logs are kept. |
| 8194 | """ |
| 8195 | if "@" in object_id: |
| 8196 | await _send_json( |
| 8197 | send, |
| 8198 | {"status": "error", "error": "Station routing is not available in this server"}, |
| 8199 | status=400, |
| 8200 | ) |
| 8201 | return |
| 8202 | |
| 8203 | gate_error = _object_source_write_gate_error(headers, object_id) |
| 8204 | if gate_error is not None: |
| 8205 | status, message = gate_error |
| 8206 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 8207 | return |
| 8208 | |
| 8209 | if await _send_permission_denied_if_needed( |
| 8210 | send, |
| 8211 | headers, |
| 8212 | object_permissions.SOURCE, |
| 8213 | object_id=object_id, |
| 8214 | method="DELETE", |
| 8215 | ): |
| 8216 | return |
| 8217 | |
| 8218 | author = _source_actor_from_headers(headers) |
| 8219 | message = "Destroyed via API" |
| 8220 | correlation_id = object_correlation.current_correlation_id() |
| 8221 | |
| 8222 | try: |
| 8223 | version_id = object_source.destroy_object_source( |
| 8224 | object_id=object_id, |
| 8225 | author=author, |
| 8226 | message=message, |
| 8227 | version_manager=_version_manager(), |
| 8228 | correlation_id=correlation_id, |
| 8229 | ) |
| 8230 | except InvalidObjectIdError as exc: |
| 8231 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8232 | return |
| 8233 | except object_source.ObjectSourceNotFoundError as exc: |
| 8234 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 8235 | return |
| 8236 | |
| 8237 | object_handlers.invalidate() |
| 8238 | # What the object scheduled for itself (_schedule) goes with it; a |
| 8239 | # package's declared schedules stay with the package. |
| 8240 | unscheduled = object_schedule.remove_object_tasks(object_id, base_dir=_data_dir()) |
| 8241 | |
| 8242 | await _send_json( |
| 8243 | send, |
| 8244 | { |
| 8245 | "status": "ok", |
| 8246 | "message": f"Object destroyed: {object_id}", |
| 8247 | "unscheduled": unscheduled, |
| 8248 | "object_id": object_id, |
| 8249 | "version_id": version_id, |
| 8250 | "correlation_id": correlation_id, |
| 8251 | }, |
| 8252 | ) |
| 8253 | _append_source_change_log( |
| 8254 | object_id, |
| 8255 | action="source_destroy", |
| 8256 | version_id=version_id, |
| 8257 | actor=author, |
| 8258 | message=message, |
| 8259 | correlation_id=correlation_id, |
| 8260 | ) |
| 8261 | |
| 8262 | |
| 8263 | async def _execute_object_method( |
| 8264 | send, |
| 8265 | object_id: str, |
| 8266 | method: str, |
| 8267 | payload: dict[str, Any], |
| 8268 | headers: dict[str, str], |
| 8269 | *, |
| 8270 | permission_action: str, |
| 8271 | ) -> None: |
| 8272 | if await _send_permission_denied_if_needed( |
| 8273 | send, |
| 8274 | headers, |
| 8275 | permission_action, |
| 8276 | object_id=object_id, |
| 8277 | method=method, |
| 8278 | ): |
| 8279 | return |
| 8280 | |
| 8281 | # Fairness: a user object counts against its OWNER's cap before it takes |
| 8282 | # a slot from the shared pool, so one customer's flood is refused with a |
| 8283 | # 429 aimed at that customer and never fills the pool for everyone else. |
| 8284 | # System and package objects (admin code) are not capped per user. |
| 8285 | user_token = None |
| 8286 | parsed_owner = object_namespace.parse_user_object_id(object_id) |
| 8287 | if parsed_owner is not None and not _is_admin_caller(headers): |
| 8288 | user_limit = _max_concurrent_executions_per_user() |
| 8289 | user_token = _user_execution_limiter.try_acquire(str(parsed_owner[0]), user_limit) |
| 8290 | if user_token is None: |
| 8291 | await _send_json( |
| 8292 | send, |
| 8293 | { |
| 8294 | "status": "error", |
| 8295 | "error": ( |
| 8296 | f"Too many concurrent executions for user {parsed_owner[0]}" |
| 8297 | ), |
| 8298 | "limit": "user_object_executions", |
| 8299 | "max_concurrent": user_limit, |
| 8300 | "retry_after": USER_EXECUTION_RETRY_AFTER_SECONDS, |
| 8301 | }, |
| 8302 | status=429, |
| 8303 | headers=[("retry-after", str(USER_EXECUTION_RETRY_AFTER_SECONDS))], |
| 8304 | ) |
| 8305 | return |
| 8306 | |
| 8307 | execution_limit = _max_concurrent_executions() |
| 8308 | execution_token = _execution_limiter.try_acquire(execution_limit) |
| 8309 | if execution_token is None: |
| 8310 | if user_token is not None: |
| 8311 | user_token.release() |
| 8312 | await _send_capacity_error( |
| 8313 | send, |
| 8314 | limit_name="object_executions", |
| 8315 | max_concurrent=execution_limit, |
| 8316 | ) |
| 8317 | return |
| 8318 | |
| 8319 | execution_request = object_execution.ObjectExecutionRequest( |
| 8320 | object_id=object_id, |
| 8321 | method=method, |
| 8322 | payload=_payload_with_identity(payload, headers), |
| 8323 | correlation_id=object_correlation.current_correlation_id(), |
| 8324 | ) |
| 8325 | timeout_seconds = _object_timeout_seconds() |
| 8326 | |
| 8327 | try: |
| 8328 | if object_sandbox.is_user_code(object_id): |
| 8329 | # User code: its own sandboxed worker, never in-process, the warm |
| 8330 | # pool or the spawn path; off the event loop while it runs. |
| 8331 | result = await asyncio.to_thread( |
| 8332 | object_execution.execute_python_object_subprocess, |
| 8333 | execution_request, |
| 8334 | timeout_seconds=timeout_seconds or object_sandbox.default_timeout_seconds(), |
| 8335 | ) |
| 8336 | elif timeout_seconds > 0 and not _object_runs_in_process(object_id): |
| 8337 | pool = await _get_worker_pool() |
| 8338 | if pool is not None: |
| 8339 | result = await pool.execute( |
| 8340 | execution_request, |
| 8341 | timeout_seconds=timeout_seconds, |
| 8342 | ) |
| 8343 | else: |
| 8344 | result = object_execution.execute_python_object_subprocess( |
| 8345 | execution_request, |
| 8346 | timeout_seconds=timeout_seconds, |
| 8347 | ) |
| 8348 | else: |
| 8349 | result = object_execution.execute_object(_runtime, execution_request) |
| 8350 | _append_execution_log(result) |
| 8351 | finally: |
| 8352 | execution_token.release() |
| 8353 | if user_token is not None: |
| 8354 | user_token.release() |
| 8355 | |
| 8356 | if result.ok: |
| 8357 | try: |
| 8358 | response = _normalize_object_response(result.result) |
| 8359 | except _UnencodableObjectResult as exc: |
| 8360 | # The object returned a value JSON cannot hold: the same 500 the |
| 8361 | # warm-pool worker gives, and one log line with the object id |
| 8362 | # and the type only -- never the value. |
| 8363 | print( |
| 8364 | f"object server: {object_id!r} returned a value that is not JSON ({exc.type_name})", |
| 8365 | file=sys.stderr, |
| 8366 | flush=True, |
| 8367 | ) |
| 8368 | result = dataclasses.replace( |
| 8369 | result, |
| 8370 | ok=False, |
| 8371 | result=None, |
| 8372 | error=object_execution.ObjectExecutionError( |
| 8373 | type=object_execution.WORKER_ERROR_TYPE, message=str(exc), traceback="" |
| 8374 | ), |
| 8375 | ) |
| 8376 | else: |
| 8377 | status, response_headers, response_body = response |
| 8378 | await _send_response(send, status=status, headers=response_headers, body=response_body) |
| 8379 | return |
| 8380 | |
| 8381 | _append_ops_execution_error(object_id, method, result, headers) |
| 8382 | await _send_execution_error(send, result) |
| 8383 | |
| 8384 | |
| 8385 | def _payload_with_identity( |
| 8386 | payload: dict[str, Any], |
| 8387 | headers: dict[str, str], |
| 8388 | ) -> dict[str, Any]: |
| 8389 | subject, auth_method = _permission_identity(headers) |
| 8390 | request_payload = dict(payload) |
| 8391 | request_payload["_identity"] = { |
| 8392 | "user_id": subject.user_id, |
| 8393 | "account_id": subject.account_id, |
| 8394 | "roles": list(subject.roles), |
| 8395 | "subscriptions": list(subject.subscriptions), |
| 8396 | "auth_method": auth_method, |
| 8397 | } |
| 8398 | return request_payload |
| 8399 | |
| 8400 | |
| 8401 | def _list_objects_payload(owner_user_id: str | None = None) -> dict[str, Any]: |
| 8402 | """Every object, or (owner_user_id given) that user's plus system ones.""" |
| 8403 | sources = iter_object_sources() |
| 8404 | if owner_user_id is not None: |
| 8405 | # A customer sees their own objects plus the system ones that said |
| 8406 | # they may be listed (LISTED = True); never the rest of the box. |
| 8407 | sources = [ |
| 8408 | source |
| 8409 | for source in sources |
| 8410 | if _object_owner(source.object_id) == owner_user_id |
| 8411 | or ( |
| 8412 | _object_owner(source.object_id) == "system" |
| 8413 | and object_user_access.is_listed(source.path) |
| 8414 | ) |
| 8415 | ] |
| 8416 | objects = [_object_source_payload(source) for source in sources] |
| 8417 | return { |
| 8418 | "status": "ok", |
| 8419 | "objects": objects, |
| 8420 | "count": len(objects), |
| 8421 | } |
| 8422 | |
| 8423 | |
| 8424 | async def _handle_objects_post(send, body: bytes, headers: dict[str, str]) -> None: |
| 8425 | admin_caller = _is_admin_caller(headers) |
| 8426 | user_id = None if admin_caller else _numeric_caller_user_id(headers) |
| 8427 | if user_id is None: |
| 8428 | gate_error = _source_write_gate_error(headers) |
| 8429 | else: |
| 8430 | gate_error = _user_source_write_gate_error(headers, None) |
| 8431 | if gate_error is not None: |
| 8432 | status, message = gate_error |
| 8433 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 8434 | return |
| 8435 | |
| 8436 | try: |
| 8437 | payload = _parse_json_body(body) |
| 8438 | if user_id is None: |
| 8439 | object_id = _created_object_id(payload, headers) |
| 8440 | else: |
| 8441 | object_id = _user_created_object_id(payload, user_id) |
| 8442 | except PermissionError as exc: |
| 8443 | await _send_json(send, {"status": "error", "error": str(exc)}, status=403) |
| 8444 | return |
| 8445 | except ValueError as exc: |
| 8446 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8447 | return |
| 8448 | |
| 8449 | if await _send_permission_denied_if_needed( |
| 8450 | send, |
| 8451 | headers, |
| 8452 | object_permissions.SOURCE, |
| 8453 | object_id=object_id, |
| 8454 | method="POST", |
| 8455 | ): |
| 8456 | return |
| 8457 | |
| 8458 | code = payload.get("code") |
| 8459 | if not isinstance(code, str): |
| 8460 | await _send_json( |
| 8461 | send, |
| 8462 | {"status": "error", "error": "Request JSON field 'code' must be a string"}, |
| 8463 | status=400, |
| 8464 | ) |
| 8465 | return |
| 8466 | |
| 8467 | author = _source_author(payload, headers) |
| 8468 | message = _payload_text(payload, "message", "Created via API") |
| 8469 | correlation_id = object_correlation.current_correlation_id() |
| 8470 | |
| 8471 | try: |
| 8472 | version_id = object_source.create_object_source( |
| 8473 | object_id=object_id, |
| 8474 | code=code, |
| 8475 | author=author, |
| 8476 | message=message, |
| 8477 | version_manager=_version_manager(), |
| 8478 | correlation_id=correlation_id, |
| 8479 | ) |
| 8480 | except InvalidObjectIdError as exc: |
| 8481 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8482 | return |
| 8483 | except object_source.ObjectSourceExistsError as exc: |
| 8484 | await _send_json(send, {"status": "error", "error": str(exc)}, status=409) |
| 8485 | return |
| 8486 | except object_source.ObjectQuotaExceededError as exc: |
| 8487 | await _send_json( |
| 8488 | send, |
| 8489 | {"status": "error", "error": str(exc), "limit": "user_max_objects"}, |
| 8490 | status=403, |
| 8491 | ) |
| 8492 | return |
| 8493 | |
| 8494 | object_handlers.invalidate() |
| 8495 | |
| 8496 | _append_source_change_log( |
| 8497 | object_id, |
| 8498 | action="source_create", |
| 8499 | version_id=version_id, |
| 8500 | actor=author, |
| 8501 | message=message, |
| 8502 | correlation_id=correlation_id, |
| 8503 | details={"description": _payload_text(payload, "description", "")}, |
| 8504 | ) |
| 8505 | |
| 8506 | methods, method_warnings = object_source.source_method_report(code) |
| 8507 | await _send_json( |
| 8508 | send, |
| 8509 | { |
| 8510 | "status": "ok", |
| 8511 | "message": f"Object created: {object_id}", |
| 8512 | "object_id": object_id, |
| 8513 | "version_id": version_id, |
| 8514 | "methods": methods, |
| 8515 | "warnings": method_warnings, |
| 8516 | "correlation_id": object_correlation.current_correlation_id(), |
| 8517 | }, |
| 8518 | status=201, |
| 8519 | ) |
| 8520 | |
| 8521 | |
| 8522 | USER_FILES_ENABLED_ENV = "DBBASIC_ENABLE_USER_FILES" |
| 8523 | USER_FILES_QUOTA_ENV = "DBBASIC_USER_FILES_QUOTA_BYTES" |
| 8524 | DEFAULT_USER_FILES_QUOTA = 104_857_600 |
| 8525 | USER_FILES_COLLECTION = "files" |
| 8526 | _INLINE_CONTENT_TYPES = frozenset( |
| 8527 | {"image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf", "text/plain"} |
| 8528 | ) |
| 8529 | |
| 8530 | |
| 8531 | async def _handle_user_file_upload( |
| 8532 | send, |
| 8533 | method: str, |
| 8534 | body: bytes, |
| 8535 | headers: dict[str, str], |
| 8536 | ) -> None: |
| 8537 | """Accept one multipart upload; bytes to disk, metadata to the files collection. |
| 8538 | |
| 8539 | The metadata record is the authority: owner_id comes from the session |
| 8540 | (unspoofable), size and content type are measured server-side, and the |
| 8541 | create is permission-checked like any record write. Quotas count real |
| 8542 | bytes on disk. |
| 8543 | """ |
| 8544 | if method != "POST": |
| 8545 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 8546 | return |
| 8547 | if not _env_enabled(USER_FILES_ENABLED_ENV): |
| 8548 | await _send_json( |
| 8549 | send, |
| 8550 | {"status": "error", "error": f"User files are disabled. Set {USER_FILES_ENABLED_ENV}=true."}, |
| 8551 | status=403, |
| 8552 | ) |
| 8553 | return |
| 8554 | session = _current_identity_session(headers) |
| 8555 | if session is None: |
| 8556 | await _send_json( |
| 8557 | send, {"status": "error", "error": "File uploads require a signed-in session."}, status=401 |
| 8558 | ) |
| 8559 | return |
| 8560 | # A cross-origin request that carries only the session cookie never gets |
| 8561 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 8562 | # request rejected") before any handler runs. |
| 8563 | |
| 8564 | content_type = headers.get("content-type", "") |
| 8565 | if not object_multipart.is_multipart_content_type(content_type): |
| 8566 | await _send_json( |
| 8567 | send, |
| 8568 | {"status": "error", "error": "Upload must be multipart/form-data with a file field."}, |
| 8569 | status=400, |
| 8570 | ) |
| 8571 | return |
| 8572 | try: |
| 8573 | payload = object_multipart.parse_multipart(body, content_type) |
| 8574 | except object_multipart.InvalidMultipartError as exc: |
| 8575 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8576 | return |
| 8577 | |
| 8578 | uploads = payload.get("_files") or {} |
| 8579 | upload = uploads.get("file") or next(iter(uploads.values()), None) |
| 8580 | if upload is None: |
| 8581 | await _send_json( |
| 8582 | send, {"status": "error", "error": "Upload needs a file form field."}, status=400 |
| 8583 | ) |
| 8584 | return |
| 8585 | |
| 8586 | content = base64.b64decode(upload.get("content_base64", "")) |
| 8587 | fields = { |
| 8588 | "description": str(payload.get("description") or "")[:300], |
| 8589 | "is_public": str(payload.get("is_public") or "false"), |
| 8590 | } |
| 8591 | if payload.get("project_id"): |
| 8592 | fields["project_id"] = str(payload["project_id"]) |
| 8593 | # Polymorphic attachment: a file uploaded from a record's detail carries |
| 8594 | # the (parent_collection, parent_id) pair the attachments capability uses, |
| 8595 | # so any collection can hold files without a dedicated FK column. Set from |
| 8596 | # the upload form (the widget supplies them); owner_id stays session-set. |
| 8597 | for _pk in ("parent_collection", "parent_id"): |
| 8598 | if payload.get(_pk): |
| 8599 | fields[_pk] = str(payload[_pk])[:120] |
| 8600 | |
| 8601 | created = await _create_user_file( |
| 8602 | send, |
| 8603 | headers, |
| 8604 | owner_id=session.user_id, |
| 8605 | filename=upload.get("filename") or "unnamed", |
| 8606 | content=content, |
| 8607 | content_type=upload.get("content_type") or "application/octet-stream", |
| 8608 | fields=fields, |
| 8609 | ) |
| 8610 | if created is None: |
| 8611 | return |
| 8612 | # The file as its uploader may read it, as every write answers. |
| 8613 | await _send_json( |
| 8614 | send, |
| 8615 | {"status": "ok", "file": created.answer, "url": f"/api/files/{created.record['id']}"}, |
| 8616 | status=201, |
| 8617 | ) |
| 8618 | |
| 8619 | |
| 8620 | def _user_files_quota_error(owner_id: str, adding: int, freeing: int = 0) -> str | None: |
| 8621 | """The quota refusal for storing ``adding`` bytes (after ``freeing`` the |
| 8622 | bytes being replaced), or None when it fits. Counts bytes on disk.""" |
| 8623 | quota = _env_int(USER_FILES_QUOTA_ENV, DEFAULT_USER_FILES_QUOTA) |
| 8624 | used = object_user_files.usage_bytes(owner_id, base_dir=_data_dir()) |
| 8625 | total = used - freeing + adding |
| 8626 | if total > quota: |
| 8627 | return f"Storage quota exceeded: {total} of {quota} bytes." |
| 8628 | return None |
| 8629 | |
| 8630 | |
| 8631 | async def _create_user_file( |
| 8632 | send, |
| 8633 | headers: dict[str, str], |
| 8634 | *, |
| 8635 | owner_id: str, |
| 8636 | filename: str, |
| 8637 | content: bytes, |
| 8638 | content_type: str, |
| 8639 | fields: dict[str, str] | None = None, |
| 8640 | ) -> _WriteDone | None: |
| 8641 | """Store one new file: quota, the metadata record through the write |
| 8642 | path (_gated_create, every step of a record create), then the bytes. |
| 8643 | |
| 8644 | Returns the write (its stored row, and the row as this caller may read |
| 8645 | it), or None when a response has already been sent. Shared by the |
| 8646 | multipart upload and WebDAV PUT/COPY, so the two ways in cannot drift |
| 8647 | apart on quota, gates or what a record holds. |
| 8648 | """ |
| 8649 | quota_error = _user_files_quota_error(owner_id, len(content)) |
| 8650 | if quota_error is not None: |
| 8651 | await _send_json( |
| 8652 | send, |
| 8653 | {"status": "error", "error": quota_error, "code": "quota_exceeded"}, |
| 8654 | status=413, |
| 8655 | ) |
| 8656 | return None |
| 8657 | |
| 8658 | file_id = object_ids.new_uuid4() |
| 8659 | record = { |
| 8660 | "id": file_id, |
| 8661 | "filename": filename[:255], |
| 8662 | "content_type": content_type or "application/octet-stream", |
| 8663 | "size": str(len(content)), |
| 8664 | "description": "", |
| 8665 | "is_public": "false", |
| 8666 | "owner_id": owner_id, |
| 8667 | } |
| 8668 | record.update(fields or {}) |
| 8669 | |
| 8670 | outcome = await _gated_create( |
| 8671 | headers, |
| 8672 | collection=USER_FILES_COLLECTION, |
| 8673 | values=record, |
| 8674 | # The keys the caller chose: the upload's name, type and bytes, and |
| 8675 | # the form's fields. id, owner_id and the defaults are the server's. |
| 8676 | sent_fields=["filename", "content_type", "size", *(fields or {})], |
| 8677 | now=datetime.now(timezone.utc), |
| 8678 | # Kept difference: a file create publishes no change event, where a |
| 8679 | # record API create does. |
| 8680 | publish=False, |
| 8681 | storage_answers=_FILE_CREATE_STORAGE_ANSWERS, |
| 8682 | ) |
| 8683 | if isinstance(outcome, _WriteRefusal): |
| 8684 | await outcome.replay(send) |
| 8685 | return None |
| 8686 | |
| 8687 | object_user_files.save_file(owner_id, file_id, content, base_dir=_data_dir()) |
| 8688 | return outcome |
| 8689 | |
| 8690 | |
| 8691 | def _share_target_record(collection: str, record_id: str) -> dict[str, str] | None: |
| 8692 | try: |
| 8693 | return object_records.get_collection_record(collection, record_id, base_dir=_data_dir()) |
| 8694 | except (LookupError, ValueError, object_collections.CollectionNotFoundError, |
| 8695 | object_collections.InvalidCollectionNameError): |
| 8696 | return None |
| 8697 | |
| 8698 | |
| 8699 | async def _handle_share(send, method: str, query, body: bytes, headers: dict[str, str]) -> None: |
| 8700 | """List or create record-access grants. |
| 8701 | |
| 8702 | The authorization that a row_filter can't express: creating a grant is |
| 8703 | checked against the TARGET record's ownership (a cross-collection fact), so |
| 8704 | only the record's owner (or an admin) can share it. Grants are written here, |
| 8705 | server-side -- there is no create rule on record_shares, so this is the ONLY |
| 8706 | path that mints one. That's what keeps sharing from being self-serve |
| 8707 | privilege escalation. |
| 8708 | """ |
| 8709 | subject = _permission_subject(headers) |
| 8710 | requester = subject.user_id |
| 8711 | if requester is None: |
| 8712 | await _send_json(send, {"status": "error", "error": "Sharing requires a signed-in session."}, status=401) |
| 8713 | return |
| 8714 | is_admin = "admin" in (subject.roles or ()) |
| 8715 | |
| 8716 | if method == "GET": |
| 8717 | collection = str(query.get("collection") or "").strip() |
| 8718 | record_id = str(query.get("record_id") or "").strip() |
| 8719 | if not collection or not record_id: |
| 8720 | await _send_json(send, {"status": "error", "error": "collection and record_id are required."}, status=400) |
| 8721 | return |
| 8722 | target = _share_target_record(collection, record_id) |
| 8723 | if target is None: |
| 8724 | await _send_json(send, {"status": "error", "error": "Record not found."}, status=404) |
| 8725 | return |
| 8726 | if not is_admin and target.get("owner_id") != requester: |
| 8727 | await _send_json(send, {"status": "error", "error": "Only the record's owner can view its shares."}, status=403) |
| 8728 | return |
| 8729 | grants = [ |
| 8730 | r for r in _read_records_or_empty(RECORD_SHARES_COLLECTION) |
| 8731 | if r.get("collection") == collection and r.get("record_id") == record_id |
| 8732 | ] |
| 8733 | await _send_json(send, {"status": "ok", "shares": grants}) |
| 8734 | return |
| 8735 | |
| 8736 | if method != "POST": |
| 8737 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 8738 | return |
| 8739 | |
| 8740 | # A cross-origin request that carries only the session cookie never gets |
| 8741 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 8742 | # request rejected") before any handler runs. |
| 8743 | |
| 8744 | payload = _parse_json_body(body) or {} |
| 8745 | collection = str(payload.get("collection") or "").strip() |
| 8746 | record_id = str(payload.get("record_id") or "").strip() |
| 8747 | grantee = str(payload.get("user_id") or "").strip() |
| 8748 | permission = "write" if str(payload.get("permission") or "read").strip() == "write" else "read" |
| 8749 | if not collection or not record_id or not grantee: |
| 8750 | await _send_json(send, {"status": "error", "error": "collection, record_id and user_id are required."}, status=400) |
| 8751 | return |
| 8752 | target = _share_target_record(collection, record_id) |
| 8753 | if target is None: |
| 8754 | await _send_json(send, {"status": "error", "error": "Record not found."}, status=404) |
| 8755 | return |
| 8756 | if not is_admin and target.get("owner_id") != requester: |
| 8757 | await _send_json(send, {"status": "error", "error": "Only the record's owner can share it."}, status=403) |
| 8758 | return |
| 8759 | grant = { |
| 8760 | "id": object_ids.new_uuid4(), |
| 8761 | "collection": collection, |
| 8762 | "record_id": record_id, |
| 8763 | "user_id": grantee, |
| 8764 | "permission": permission, |
| 8765 | "granted_by": requester, |
| 8766 | } |
| 8767 | try: |
| 8768 | # write-path: record_shares has no policy rules by design; the target-ownership check above is its only gate |
| 8769 | stored = object_records.create_collection_record( |
| 8770 | RECORD_SHARES_COLLECTION, grant, base_dir=_data_dir(), |
| 8771 | actor=_record_change_actor(headers), preserve_read_only=True, |
| 8772 | ) |
| 8773 | except object_collections.CollectionNotFoundError: |
| 8774 | await _send_json(send, {"status": "error", "error": "The record_shares collection is not installed (app-share)."}, status=404) |
| 8775 | return |
| 8776 | except ValueError as exc: |
| 8777 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 8778 | return |
| 8779 | await _send_json(send, {"status": "ok", "share": stored}, status=201) |
| 8780 | |
| 8781 | |
| 8782 | async def _handle_share_revoke(send, method: str, grant_id: str, headers: dict[str, str]) -> None: |
| 8783 | """Revoke one grant. Authorized for the record's owner, the original |
| 8784 | granter, or an admin -- the same target-ownership check as creating one.""" |
| 8785 | if method != "DELETE": |
| 8786 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 8787 | return |
| 8788 | subject = _permission_subject(headers) |
| 8789 | requester = subject.user_id |
| 8790 | if requester is None: |
| 8791 | await _send_json(send, {"status": "error", "error": "Sharing requires a signed-in session."}, status=401) |
| 8792 | return |
| 8793 | # A cross-origin request that carries only the session cookie never gets |
| 8794 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 8795 | # request rejected") before any handler runs. |
| 8796 | if not grant_id or "/" in grant_id: |
| 8797 | await _send_json(send, {"status": "error", "error": "Invalid grant id"}, status=400) |
| 8798 | return |
| 8799 | try: |
| 8800 | grant = object_records.get_collection_record(RECORD_SHARES_COLLECTION, grant_id, base_dir=_data_dir()) |
| 8801 | except (LookupError, ValueError): |
| 8802 | grant = None |
| 8803 | if grant is None: |
| 8804 | await _send_json(send, {"status": "error", "error": "Grant not found."}, status=404) |
| 8805 | return |
| 8806 | is_admin = "admin" in (subject.roles or ()) |
| 8807 | target = _share_target_record(grant.get("collection", ""), grant.get("record_id", "")) |
| 8808 | owns_target = target is not None and target.get("owner_id") == requester |
| 8809 | if not (is_admin or owns_target or grant.get("granted_by") == requester): |
| 8810 | await _send_json(send, {"status": "error", "error": "Not allowed to revoke this grant."}, status=403) |
| 8811 | return |
| 8812 | # The owner/granter/admin check above is this route's permission step: |
| 8813 | # record_shares has no policy rules by design, so the write path is told |
| 8814 | # both questions were asked. Everything after them is a delete like any |
| 8815 | # other (S30): the hook, the judged row, the locks, the change event. |
| 8816 | outcome = await _gated_delete( |
| 8817 | headers, |
| 8818 | collection=RECORD_SHARES_COLLECTION, |
| 8819 | record_id=grant_id, |
| 8820 | now=datetime.now(timezone.utc), |
| 8821 | existing=grant, |
| 8822 | collection_asked=True, |
| 8823 | row_asked=True, |
| 8824 | shape_answer=False, # the route answers with no record |
| 8825 | storage_answers=_SHARE_REVOKE_STORAGE_ANSWERS, |
| 8826 | ) |
| 8827 | if isinstance(outcome, _WriteRefusal): |
| 8828 | await outcome.replay(send) |
| 8829 | return |
| 8830 | await _send_json(send, {"status": "ok"}) |
| 8831 | |
| 8832 | |
| 8833 | async def _handle_user_file( |
| 8834 | send, |
| 8835 | method: str, |
| 8836 | file_id: str, |
| 8837 | headers: dict[str, str], |
| 8838 | ) -> None: |
| 8839 | """Serve or delete one file, authorized against its metadata record.""" |
| 8840 | if not _env_enabled(USER_FILES_ENABLED_ENV): |
| 8841 | await _send_json( |
| 8842 | send, |
| 8843 | {"status": "error", "error": f"User files are disabled. Set {USER_FILES_ENABLED_ENV}=true."}, |
| 8844 | status=403, |
| 8845 | ) |
| 8846 | return |
| 8847 | if "/" in file_id or not file_id: |
| 8848 | await _send_json(send, {"status": "error", "error": "Invalid file id"}, status=400) |
| 8849 | return |
| 8850 | |
| 8851 | action = object_permissions.READ if method == "GET" else object_permissions.DELETE |
| 8852 | enforced = _permission_enforcement_enabled() |
| 8853 | # Under enforcement: the collection-level decision first, then a file the |
| 8854 | # caller may not touch answers exactly like a missing one (it answered |
| 8855 | # 403 for an existing id and 404 for a missing one). |
| 8856 | if not await _user_files_collection_allowed(send, headers, action, method=method): |
| 8857 | return |
| 8858 | |
| 8859 | try: |
| 8860 | record = object_records.get_collection_record( |
| 8861 | USER_FILES_COLLECTION, file_id, base_dir=_data_dir() |
| 8862 | ) |
| 8863 | except (LookupError, ValueError): |
| 8864 | record = None |
| 8865 | |
| 8866 | if enforced and record is None: |
| 8867 | await _send_json(send, {"status": "error", "error": "File not found"}, status=404) |
| 8868 | return |
| 8869 | if not await _user_file_allowed( |
| 8870 | send, headers, action, record=record, method=method, |
| 8871 | deny_as_not_found="File not found" if enforced else None, |
| 8872 | collection_checked=True, |
| 8873 | ): |
| 8874 | return |
| 8875 | |
| 8876 | if record is None: |
| 8877 | await _send_json(send, {"status": "error", "error": "File not found"}, status=404) |
| 8878 | return |
| 8879 | owner_id = record.get("owner_id", "") |
| 8880 | |
| 8881 | if method == "GET": |
| 8882 | try: |
| 8883 | content = object_user_files.read_file(owner_id, file_id, base_dir=_data_dir()) |
| 8884 | except (object_user_files.UserFileNotFoundError, object_user_files.InvalidUserFileError): |
| 8885 | await _send_json(send, {"status": "error", "error": "File bytes missing"}, status=404) |
| 8886 | return |
| 8887 | content_type = record.get("content_type") or "application/octet-stream" |
| 8888 | disposition = "inline" if content_type in _INLINE_CONTENT_TYPES else "attachment" |
| 8889 | filename = (record.get("filename") or "download").replace('"', "") |
| 8890 | await _send_bytes( |
| 8891 | send, |
| 8892 | content, |
| 8893 | content_type=content_type, |
| 8894 | extra_headers=[ |
| 8895 | (b"content-disposition", f'{disposition}; filename="{filename}"'.encode("latin-1", "replace")), |
| 8896 | (b"x-content-type-options", b"nosniff"), |
| 8897 | ], |
| 8898 | ) |
| 8899 | return |
| 8900 | |
| 8901 | if method == "DELETE": |
| 8902 | # A cross-origin DELETE that carries only the session cookie never |
| 8903 | # gets here: app() refuses it for every route (403 "Cross-origin |
| 8904 | # cookie request rejected") before any handler runs. |
| 8905 | if not await _remove_user_file(send, headers, record): |
| 8906 | return |
| 8907 | await _send_json(send, {"status": "ok", "deleted": True, "file_id": file_id}) |
| 8908 | return |
| 8909 | |
| 8910 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 8911 | |
| 8912 | |
| 8913 | async def _user_files_collection_allowed( |
| 8914 | send, headers: dict[str, str], action: str, *, method: str |
| 8915 | ) -> bool: |
| 8916 | """The first question every way into someone's files asks, under |
| 8917 | enforcement: may this subject do `action` on the files collection at |
| 8918 | all? It is asked with no record, so the owner fallback cannot answer |
| 8919 | it -- the same question the record routes ask before they look a row |
| 8920 | up. Sends the refusal and returns False when not allowed. |
| 8921 | |
| 8922 | /api/files asked it and WebDAV did not, so under a policy with no rules |
| 8923 | a mounted folder still listed, served and deleted the owner's files |
| 8924 | that /api/files refused them. |
| 8925 | """ |
| 8926 | if not _permission_enforcement_enabled(): |
| 8927 | return True |
| 8928 | return await _collection_permission_check( |
| 8929 | send, headers, action, collection=USER_FILES_COLLECTION, method=method |
| 8930 | ) is not None |
| 8931 | |
| 8932 | |
| 8933 | async def _user_file_allowed( |
| 8934 | send, |
| 8935 | headers: dict[str, str], |
| 8936 | action: str, |
| 8937 | *, |
| 8938 | record: dict[str, Any] | None, |
| 8939 | method: str, |
| 8940 | deny_as_not_found: str | None = None, |
| 8941 | collection_checked: bool = False, |
| 8942 | ) -> bool: |
| 8943 | """The permission decision for one file (a policy check, or the admin |
| 8944 | token when permission checks are off). Sends the refusal and returns |
| 8945 | False when not allowed. |
| 8946 | |
| 8947 | Asks the collection-level question first (_user_files_collection_allowed) |
| 8948 | unless the caller already did, for this action, before looking the file |
| 8949 | up (collection_checked=True).""" |
| 8950 | if not collection_checked and not await _user_files_collection_allowed( |
| 8951 | send, headers, action, method=method |
| 8952 | ): |
| 8953 | return False |
| 8954 | if _permission_checks_enabled(): |
| 8955 | permission_check = await _collection_permission_check( |
| 8956 | send, |
| 8957 | headers, |
| 8958 | action, |
| 8959 | collection=USER_FILES_COLLECTION, |
| 8960 | method=method, |
| 8961 | record=record, |
| 8962 | deny_as_not_found=deny_as_not_found, |
| 8963 | ) |
| 8964 | if permission_check is None: |
| 8965 | return False |
| 8966 | if permission_check["enforced"]: |
| 8967 | return True |
| 8968 | return not await _send_unenforced_gate_error(send, headers, f"Files require {ADMIN_TOKEN_ENV}.") |
| 8969 | |
| 8970 | |
| 8971 | class _HeldResponse: |
| 8972 | """A `send` that keeps the response instead of sending it, for a caller |
| 8973 | that reuses a helper which answers the client itself but must report the |
| 8974 | outcome its own way.""" |
| 8975 | |
| 8976 | def __init__(self) -> None: |
| 8977 | self.status: int | None = None |
| 8978 | self.headers: list[tuple[bytes, bytes]] = [] |
| 8979 | self.body = b"" |
| 8980 | |
| 8981 | async def __call__(self, message: dict[str, Any]) -> None: |
| 8982 | if message["type"] == "http.response.start": |
| 8983 | self.status = message["status"] |
| 8984 | self.headers = list(message.get("headers") or []) |
| 8985 | elif message["type"] == "http.response.body": |
| 8986 | self.body += message.get("body", b"") |
| 8987 | |
| 8988 | async def replay(self, send) -> None: |
| 8989 | await send({"type": "http.response.start", "status": self.status, "headers": self.headers}) |
| 8990 | await send({"type": "http.response.body", "body": self.body}) |
| 8991 | |
| 8992 | |
| 8993 | async def _user_attachment_readable( |
| 8994 | headers: dict[str, str], record: dict[str, Any] | None |
| 8995 | ) -> "bool | _HeldResponse": |
| 8996 | """May this caller's chat turn read a file's bytes? The same decisions, |
| 8997 | in the same order, as GET /api/files/{id} under enforcement: with |
| 8998 | record=None the collection-level read (asked once, before any lookup, |
| 8999 | so the owner fallback cannot answer it), then with each record the file |
| 9000 | itself. The owner fallback alone therefore does not let a file out to |
| 9001 | an AI provider when the policy grants nothing on files. |
| 9002 | |
| 9003 | Returns True or False; or, when the decision could not be made (the |
| 9004 | policy is unreadable: 503), the held response for the caller to send. |
| 9005 | With enforcement off or in audit mode it is True: the chat route's own |
| 9006 | owner-only rule decides there, as it always has (the off-mode admin |
| 9007 | token gate of /api/files is for the raw file route, not a signed-in |
| 9008 | owner's chat). In audit mode the same two questions are still asked, |
| 9009 | so each decision, a would-be refusal included, is in the permission |
| 9010 | audit log (enforced: false) like every other audited decision; it used |
| 9011 | to return before asking, and an attachment left no audit entry. |
| 9012 | """ |
| 9013 | if not _permission_checks_enabled(): |
| 9014 | return True |
| 9015 | held = _HeldResponse() |
| 9016 | if not _permission_enforcement_enabled(): |
| 9017 | await _collection_permission_check( |
| 9018 | held, headers, object_permissions.READ, |
| 9019 | collection=USER_FILES_COLLECTION, method="GET", record=record, |
| 9020 | ) |
| 9021 | return True |
| 9022 | if record is None: |
| 9023 | allowed = await _user_files_collection_allowed( |
| 9024 | held, headers, object_permissions.READ, method="GET" |
| 9025 | ) |
| 9026 | else: |
| 9027 | allowed = await _user_file_allowed( |
| 9028 | held, headers, object_permissions.READ, record=record, method="GET", |
| 9029 | deny_as_not_found="File not found", collection_checked=True, |
| 9030 | ) |
| 9031 | if allowed: |
| 9032 | return True |
| 9033 | return held if held.status == 503 else False |
| 9034 | |
| 9035 | |
| 9036 | async def _remove_user_file(send, headers: dict[str, str], record: dict[str, Any]) -> bool: |
| 9037 | """Delete a file's record through the write path, then its bytes. Sends |
| 9038 | the error and returns False when the files hook refuses the delete, or |
| 9039 | the record is gone or unreadable. |
| 9040 | |
| 9041 | The caller has already asked both permission questions through the |
| 9042 | files' own decision (_user_files_collection_allowed, _user_file_allowed), |
| 9043 | shared with the file reads. Kept difference: a file delete publishes no |
| 9044 | change event, where a record API delete does. |
| 9045 | """ |
| 9046 | file_id = str(record.get("id") or "") |
| 9047 | outcome = await _gated_delete( |
| 9048 | headers, |
| 9049 | collection=USER_FILES_COLLECTION, |
| 9050 | record_id=file_id, |
| 9051 | now=datetime.now(timezone.utc), |
| 9052 | existing=record, |
| 9053 | collection_asked=True, |
| 9054 | row_asked=True, |
| 9055 | publish=False, |
| 9056 | shape_answer=False, |
| 9057 | storage_answers=_FILE_DELETE_STORAGE_ANSWERS, |
| 9058 | ) |
| 9059 | if isinstance(outcome, _WriteRefusal): |
| 9060 | await outcome.replay(send) |
| 9061 | return False |
| 9062 | try: |
| 9063 | object_user_files.delete_file(str(record.get("owner_id") or ""), file_id, base_dir=_data_dir()) |
| 9064 | except object_user_files.InvalidUserFileError: |
| 9065 | pass |
| 9066 | return True |
| 9067 | |
| 9068 | |
| 9069 | # --------------------------------------------------------------------------- |
| 9070 | # WebDAV: a person's files as a folder any desktop can mount (/dav/files/). |
| 9071 | # The pure half (names, paths, XML, ranges) and the decisions behind it are in |
| 9072 | # object_webdav.py. Every write goes through the same helpers as /api/files and |
| 9073 | # the collection routes, so a file stored or renamed here passes the same |
| 9074 | # quota, permission and hook gates. |
| 9075 | # --------------------------------------------------------------------------- |
| 9076 | |
| 9077 | WEBDAV_ENABLED_ENV = "DBBASIC_ENABLE_WEBDAV" |
| 9078 | WEBDAV_MAX_FILE_BYTES_ENV = "DBBASIC_WEBDAV_MAX_FILE_BYTES" |
| 9079 | # One PUT is read into memory whole, like every request here: this bounds it. |
| 9080 | DEFAULT_WEBDAV_MAX_FILE_BYTES = 52_428_800 |
| 9081 | _WEBDAV_ALLOW = "OPTIONS, PROPFIND, PROPPATCH, GET, HEAD, PUT, DELETE, MOVE, COPY" |
| 9082 | _WEBDAV_REALM = 'Basic realm="DBBASIC files", charset="UTF-8"' |
| 9083 | # The verbs that read the caller's folder (to list it or find a file in it), |
| 9084 | # and so need read on the files collection like the JSON list route does. |
| 9085 | _WEBDAV_FOLDER_METHODS = frozenset({"PROPFIND", "PROPPATCH", "GET", "HEAD", "PUT", "DELETE", "MOVE", "COPY"}) |
| 9086 | |
| 9087 | |
| 9088 | def _webdav_enabled() -> bool: |
| 9089 | return _env_enabled(WEBDAV_ENABLED_ENV) and _env_enabled(USER_FILES_ENABLED_ENV) |
| 9090 | |
| 9091 | |
| 9092 | def _webdav_body_limit(method: str, path: str) -> int | None: |
| 9093 | """A PUT under /dav/ is a whole file, so it may be bigger than the |
| 9094 | general request cap; everything else keeps that cap.""" |
| 9095 | if method != "PUT" or not path.startswith(http_api_contract.WEBDAV_PATH + "/") or not _webdav_enabled(): |
| 9096 | return None |
| 9097 | return max(_max_request_bytes(), _env_int(WEBDAV_MAX_FILE_BYTES_ENV, DEFAULT_WEBDAV_MAX_FILE_BYTES)) |
| 9098 | |
| 9099 | |
| 9100 | def _webdav_identity(headers: dict[str, str]) -> tuple[dict[str, str], str] | None: |
| 9101 | """(headers to authorize with, user id) for a request carrying an API key. |
| 9102 | |
| 9103 | Desktops speak HTTP Basic, so the key comes as the password (any user |
| 9104 | name). Only API keys are accepted, never an account password: a password |
| 9105 | here would be a second login with none of /identity/login's rate limits, |
| 9106 | and a key can be revoked alone. Cookies are dropped, not just ignored: a |
| 9107 | folder mounted by a desktop has none, and a browser's session cookie must |
| 9108 | not turn a cross-site PUT or DELETE into the signed-in user's. |
| 9109 | """ |
| 9110 | authorization = headers.get("authorization", "") |
| 9111 | scheme, _, value = authorization.partition(" ") |
| 9112 | token = None |
| 9113 | if scheme.lower() == "basic": |
| 9114 | try: |
| 9115 | decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8") |
| 9116 | except (ValueError, UnicodeDecodeError): |
| 9117 | return None |
| 9118 | token = decoded.partition(":")[2] |
| 9119 | elif scheme.lower() in {"bearer", "token"}: |
| 9120 | token = value.strip() |
| 9121 | if not token or not token.startswith(object_api_keys.TOKEN_PREFIX): |
| 9122 | return None |
| 9123 | user_id = _resolve_api_key_user(token) |
| 9124 | if not user_id: |
| 9125 | return None |
| 9126 | dav_headers = {k: v for k, v in headers.items() if k not in {"authorization", "cookie"}} |
| 9127 | dav_headers["authorization"] = f"Bearer {token}" |
| 9128 | return dav_headers, user_id |
| 9129 | |
| 9130 | |
| 9131 | def _webdav_timestamp(value: Any) -> float | None: |
| 9132 | text = str(value or "").strip() |
| 9133 | if not text: |
| 9134 | return None |
| 9135 | try: |
| 9136 | parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 9137 | except ValueError: |
| 9138 | return None |
| 9139 | if parsed.tzinfo is None: |
| 9140 | parsed = parsed.replace(tzinfo=timezone.utc) |
| 9141 | return parsed.timestamp() |
| 9142 | |
| 9143 | |
| 9144 | def _webdav_folder(dav_headers: dict[str, str], user_id: str) -> dict[str, object_webdav.DavFile]: |
| 9145 | """The caller's own files, as the folder shows them (name -> file). |
| 9146 | |
| 9147 | Own files only: a public file or one shared through a project belongs to |
| 9148 | someone else's folder, and listing it here would let a rename or delete |
| 9149 | from a desktop reach it. With enforcement on, each is also checked for |
| 9150 | read like any GET. |
| 9151 | """ |
| 9152 | subject = _permission_subject(dav_headers) |
| 9153 | enforced = _permission_checks_enabled() and _permission_enforcement_enabled() |
| 9154 | policy = None |
| 9155 | if enforced: |
| 9156 | try: |
| 9157 | policy = object_permission_store.load_policy(_data_dir()) |
| 9158 | except (OSError, ValueError) as exc: |
| 9159 | # Never an empty folder: a sync client reads that as "every file |
| 9160 | # was deleted" and deletes its copies. It answered 207 with an |
| 9161 | # empty listing (and 404 for each file) while the policy was broken. |
| 9162 | raise object_webdav.DavRequestError(503, PERMISSION_POLICY_UNAVAILABLE_MESSAGE) from exc |
| 9163 | try: |
| 9164 | records = object_records.read_collection_records(USER_FILES_COLLECTION, base_dir=_data_dir()) |
| 9165 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 9166 | records = [] # no file uploaded yet: a genuinely empty folder |
| 9167 | except (OSError, ValueError) as exc: |
| 9168 | raise object_webdav.DavRequestError( |
| 9169 | 503, "Your files are temporarily unavailable. Try again shortly." |
| 9170 | ) from exc |
| 9171 | mine = [] |
| 9172 | for record in records: |
| 9173 | if record.get("owner_id") != user_id: |
| 9174 | continue |
| 9175 | if enforced and not object_permissions.check_permission( |
| 9176 | subject, object_permissions.READ, policy=policy, |
| 9177 | collection=USER_FILES_COLLECTION, record=record, |
| 9178 | ).allowed: |
| 9179 | continue |
| 9180 | mine.append(record) |
| 9181 | |
| 9182 | folder: dict[str, object_webdav.DavFile] = {} |
| 9183 | for name, record in object_webdav.folder_names(mine).items(): |
| 9184 | created = _webdav_timestamp(record.get("created_at")) |
| 9185 | try: |
| 9186 | stat = object_user_files.file_path( |
| 9187 | user_id, str(record.get("id") or ""), base_dir=_data_dir() |
| 9188 | ).stat() |
| 9189 | size, modified = stat.st_size, stat.st_mtime |
| 9190 | except (OSError, object_user_files.InvalidUserFileError): |
| 9191 | # the bytes are missing: still listed (the record exists), and |
| 9192 | # a GET says so with a 404 rather than the file vanishing |
| 9193 | try: |
| 9194 | size = int(record.get("size") or 0) |
| 9195 | except ValueError: |
| 9196 | size = 0 |
| 9197 | modified = created or 0.0 |
| 9198 | folder[name] = object_webdav.DavFile( |
| 9199 | name=name, record=record, size=size, modified=modified, created=created or modified |
| 9200 | ) |
| 9201 | return folder |
| 9202 | |
| 9203 | |
| 9204 | def _webdav_folder_modified(folder: dict[str, object_webdav.DavFile]) -> float: |
| 9205 | """When the folder last changed: the files collection's own file moves |
| 9206 | on every create, rename and delete, which the files' times alone miss.""" |
| 9207 | records = Path(_data_dir()) / "collections" / USER_FILES_COLLECTION / "records.tsv" |
| 9208 | try: |
| 9209 | return records.stat().st_mtime |
| 9210 | except OSError: |
| 9211 | return max((f.modified for f in folder.values()), default=0.0) |
| 9212 | |
| 9213 | |
| 9214 | async def _send_webdav_error(send, status: int, message: str, extra: list[tuple[str, str]] | None = None) -> None: |
| 9215 | await _send_response( |
| 9216 | send, |
| 9217 | status=status, |
| 9218 | headers=[("content-type", "text/plain; charset=utf-8")] + (extra or []), |
| 9219 | body=(message + "\n").encode("utf-8"), |
| 9220 | ) |
| 9221 | |
| 9222 | |
| 9223 | async def _handle_webdav(send, method: str, path: str, body: bytes, headers: dict[str, str]) -> None: |
| 9224 | """Serve /dav/: a person's files as a folder (WebDAV class 1).""" |
| 9225 | if not _webdav_enabled(): |
| 9226 | await _send_json( |
| 9227 | send, |
| 9228 | { |
| 9229 | "status": "error", |
| 9230 | "error": f"WebDAV is disabled. Set {WEBDAV_ENABLED_ENV}=true and {USER_FILES_ENABLED_ENV}=true.", |
| 9231 | }, |
| 9232 | status=404, |
| 9233 | ) |
| 9234 | return |
| 9235 | if method == "OPTIONS": |
| 9236 | await _send_response( |
| 9237 | send, |
| 9238 | status=200, |
| 9239 | headers=[("dav", "1"), ("allow", _WEBDAV_ALLOW), ("ms-author-via", "DAV"), ("content-length", "0")], |
| 9240 | body=b"", |
| 9241 | ) |
| 9242 | return |
| 9243 | identity = _webdav_identity(headers) |
| 9244 | if identity is None: |
| 9245 | await _send_webdav_error( |
| 9246 | send, 401, |
| 9247 | "Sign in with any user name and one of your API keys (dbk_...) as the password.", |
| 9248 | [("www-authenticate", _WEBDAV_REALM)], |
| 9249 | ) |
| 9250 | return |
| 9251 | dav_headers, user_id = identity |
| 9252 | if method in _WEBDAV_FOLDER_METHODS and not await _user_files_collection_allowed( |
| 9253 | send, dav_headers, object_permissions.READ, method=method |
| 9254 | ): |
| 9255 | # Refused, never an empty folder: a sync client deletes its copies |
| 9256 | # of files it is told are gone. 403 like the JSON list route. |
| 9257 | return |
| 9258 | try: |
| 9259 | kind, name = object_webdav.split_path(path) |
| 9260 | if method == "PROPFIND": |
| 9261 | await _webdav_propfind(send, dav_headers, user_id, kind, name, body) |
| 9262 | elif method in {"GET", "HEAD"}: |
| 9263 | await _webdav_get(send, dav_headers, user_id, kind, name, head=method == "HEAD") |
| 9264 | elif method == "PUT": |
| 9265 | await _webdav_put(send, dav_headers, user_id, kind, name, body) |
| 9266 | elif method == "DELETE": |
| 9267 | await _webdav_delete(send, dav_headers, user_id, kind, name) |
| 9268 | elif method in {"MOVE", "COPY"}: |
| 9269 | await _webdav_move_or_copy(send, dav_headers, user_id, kind, name, copy=method == "COPY") |
| 9270 | elif method == "PROPPATCH": |
| 9271 | await _webdav_proppatch(send, dav_headers, user_id, kind, name, body) |
| 9272 | elif method == "MKCOL": |
| 9273 | await _send_webdav_error( |
| 9274 | send, 405, "Folders are not supported here: your files are one list.", |
| 9275 | [("allow", _WEBDAV_ALLOW)], |
| 9276 | ) |
| 9277 | else: |
| 9278 | # LOCK/UNLOCK included: see object_webdav on why there is no fake lock |
| 9279 | await _send_webdav_error(send, 405, f"{method} is not supported.", [("allow", _WEBDAV_ALLOW)]) |
| 9280 | except object_webdav.DavRequestError as exc: |
| 9281 | await _send_webdav_error(send, exc.status, str(exc)) |
| 9282 | |
| 9283 | |
| 9284 | def _webdav_file(folder: dict[str, object_webdav.DavFile], name: str | None) -> object_webdav.DavFile: |
| 9285 | found = object_webdav.lookup(folder, name or "") |
| 9286 | if found is None: |
| 9287 | raise object_webdav.DavRequestError(404, "No such file.") |
| 9288 | return folder[found] |
| 9289 | |
| 9290 | |
| 9291 | async def _webdav_propfind(send, dav_headers, user_id, kind, name, body) -> None: |
| 9292 | depth = object_webdav.parse_depth(dav_headers.get("depth")) |
| 9293 | wanted = object_webdav.parse_propfind(body) |
| 9294 | folder = _webdav_folder(dav_headers, user_id) |
| 9295 | folder_time = _webdav_folder_modified(folder) |
| 9296 | # the files quota, so a desktop shows real free space rather than its disk's |
| 9297 | used = object_user_files.usage_bytes(user_id, base_dir=_data_dir()) |
| 9298 | quota = _env_int(USER_FILES_QUOTA_ENV, DEFAULT_USER_FILES_QUOTA) |
| 9299 | files_entry = ( |
| 9300 | object_webdav.href(object_webdav.FILES_FOLDER, folder=True), |
| 9301 | object_webdav.folder_props(object_webdav.FILES_FOLDER, folder_time, used=used, available=quota - used), |
| 9302 | ) |
| 9303 | file_entries = [ |
| 9304 | (object_webdav.href(object_webdav.FILES_FOLDER, f.name), object_webdav.file_props(f)) |
| 9305 | for f in folder.values() |
| 9306 | ] |
| 9307 | # The tree is two levels deep, so Depth: infinity is answered in full |
| 9308 | # rather than refused: it costs no more than Depth: 1 on the files folder. |
| 9309 | if kind == "root": |
| 9310 | responses = [(object_webdav.href(folder=True), object_webdav.folder_props("dav", folder_time))] |
| 9311 | if depth != "0": |
| 9312 | responses.append(files_entry) |
| 9313 | if depth == "infinity": |
| 9314 | responses.extend(file_entries) |
| 9315 | elif kind == "files": |
| 9316 | responses = [files_entry] + (file_entries if depth != "0" else []) |
| 9317 | else: |
| 9318 | f = _webdav_file(folder, name) |
| 9319 | responses = [(object_webdav.href(object_webdav.FILES_FOLDER, f.name), object_webdav.file_props(f))] |
| 9320 | await _send_response( |
| 9321 | send, |
| 9322 | status=207, |
| 9323 | headers=[("content-type", "application/xml; charset=utf-8")], |
| 9324 | body=object_webdav.multistatus(responses, wanted), |
| 9325 | ) |
| 9326 | |
| 9327 | |
| 9328 | async def _webdav_get(send, dav_headers, user_id, kind, name, *, head: bool) -> None: |
| 9329 | folder = _webdav_folder(dav_headers, user_id) |
| 9330 | if kind != "file": |
| 9331 | entries = ( |
| 9332 | [(object_webdav.href(object_webdav.FILES_FOLDER, folder=True), object_webdav.FILES_FOLDER + "/")] |
| 9333 | if kind == "root" |
| 9334 | else [(object_webdav.href(object_webdav.FILES_FOLDER, n), n) for n in sorted(folder, key=str.lower)] |
| 9335 | ) |
| 9336 | page = object_webdav.folder_html("Files" if kind == "files" else "dav", entries) |
| 9337 | await _send_response( |
| 9338 | send, status=200, |
| 9339 | headers=[("content-type", "text/html; charset=utf-8"), ("content-length", str(len(page)))], |
| 9340 | body=b"" if head else page, |
| 9341 | ) |
| 9342 | return |
| 9343 | f = _webdav_file(folder, name) |
| 9344 | if not await _user_file_allowed( |
| 9345 | send, dav_headers, object_permissions.READ, record=f.record, method="GET", collection_checked=True |
| 9346 | ): |
| 9347 | return |
| 9348 | common = [ |
| 9349 | ("etag", f.etag), |
| 9350 | ("last-modified", object_webdav.http_date(f.modified)), |
| 9351 | ("accept-ranges", "bytes"), |
| 9352 | ("x-content-type-options", "nosniff"), |
| 9353 | # served from the server's own origin: an uploaded page must not run |
| 9354 | ("content-security-policy", "sandbox"), |
| 9355 | ] |
| 9356 | if object_webdav.etag_matches(dav_headers.get("if-none-match"), f.etag): |
| 9357 | await _send_response(send, status=304, headers=common, body=b"") |
| 9358 | return |
| 9359 | try: |
| 9360 | content = object_user_files.read_file(user_id, f.record_id, base_dir=_data_dir()) |
| 9361 | except (object_user_files.UserFileNotFoundError, object_user_files.InvalidUserFileError): |
| 9362 | raise object_webdav.DavRequestError(404, "File bytes missing.") from None |
| 9363 | content_type = f.content_type |
| 9364 | disposition = "inline" if content_type in _INLINE_CONTENT_TYPES else "attachment" |
| 9365 | headers = [("content-type", content_type), ("content-disposition", disposition)] + common |
| 9366 | try: |
| 9367 | wanted = object_webdav.parse_range(dav_headers.get("range"), len(content)) |
| 9368 | except object_webdav.DavRequestError: |
| 9369 | await _send_response( |
| 9370 | send, status=416, headers=[("content-range", f"bytes */{len(content)}")], body=b"" |
| 9371 | ) |
| 9372 | return |
| 9373 | status = 200 |
| 9374 | if wanted is not None: |
| 9375 | start, end = wanted |
| 9376 | content = content[start:end + 1] |
| 9377 | status = 206 |
| 9378 | headers.append(("content-range", f"bytes {start}-{end}/{f.size}")) |
| 9379 | headers.append(("content-length", str(len(content)))) |
| 9380 | await _send_response(send, status=status, headers=headers, body=b"" if head else content) |
| 9381 | |
| 9382 | |
| 9383 | def _webdav_preconditions(dav_headers, existing: object_webdav.DavFile | None) -> None: |
| 9384 | """If-Match / If-None-Match against the file a write would touch: how a |
| 9385 | client that read a file makes sure it is not overwriting someone else's |
| 9386 | newer copy, and how "create, but only if new" is asked.""" |
| 9387 | etag = existing.etag if existing else None |
| 9388 | if_match = dav_headers.get("if-match") |
| 9389 | if if_match and not object_webdav.etag_matches(if_match, etag): |
| 9390 | raise object_webdav.DavRequestError(412, "The file changed (If-Match).") |
| 9391 | if_none_match = dav_headers.get("if-none-match") |
| 9392 | if if_none_match and object_webdav.etag_matches(if_none_match, etag): |
| 9393 | raise object_webdav.DavRequestError(412, "The file exists (If-None-Match).") |
| 9394 | |
| 9395 | |
| 9396 | def _webdav_content_type(name: str, sent: str | None) -> str: |
| 9397 | guessed = object_webdav.guess_type(name) |
| 9398 | sent = (sent or "").split(";")[0].strip().lower() |
| 9399 | if guessed == "application/octet-stream" and sent: |
| 9400 | return sent |
| 9401 | return guessed |
| 9402 | |
| 9403 | |
| 9404 | async def _webdav_put(send, dav_headers, user_id, kind, name, body) -> None: |
| 9405 | if kind != "file": |
| 9406 | raise object_webdav.DavRequestError(405, "A folder cannot be written; PUT a file inside /dav/files/.") |
| 9407 | name = object_webdav.check_new_name(name or "") |
| 9408 | folder = _webdav_folder(dav_headers, user_id) |
| 9409 | found = object_webdav.lookup(folder, name) |
| 9410 | existing = folder[found] if found else None |
| 9411 | _webdav_preconditions(dav_headers, existing) |
| 9412 | content_type = _webdav_content_type(name, dav_headers.get("content-type")) |
| 9413 | if existing is None: |
| 9414 | stored = await _create_user_file( |
| 9415 | send, dav_headers, owner_id=user_id, filename=name, content=body, content_type=content_type |
| 9416 | ) |
| 9417 | if stored is not None: |
| 9418 | await _send_response(send, status=201, headers=[("content-length", "0")], body=b"") |
| 9419 | return |
| 9420 | quota_error = _user_files_quota_error(user_id, len(body), freeing=existing.size) |
| 9421 | if quota_error is not None: |
| 9422 | raise object_webdav.DavRequestError(507, quota_error) |
| 9423 | # The file's If-Match was judged above against the row the gates judge; |
| 9424 | # the write refuses if the row under the lock is another (S52). |
| 9425 | updated = await _gated_update( |
| 9426 | dav_headers, |
| 9427 | collection=USER_FILES_COLLECTION, |
| 9428 | record_id=existing.record_id, |
| 9429 | existing=existing.record, |
| 9430 | changes={"size": str(len(body)), "content_type": content_type}, |
| 9431 | now=datetime.now(timezone.utc), |
| 9432 | shape_answer=False, # WebDAV answers with no body |
| 9433 | ) |
| 9434 | if isinstance(updated, _WriteRefusal): |
| 9435 | await updated.replay(send) |
| 9436 | return |
| 9437 | object_user_files.save_file(user_id, existing.record_id, body, base_dir=_data_dir()) |
| 9438 | await _send_response(send, status=204, headers=[], body=b"") |
| 9439 | |
| 9440 | |
| 9441 | async def _webdav_delete(send, dav_headers, user_id, kind, name) -> None: |
| 9442 | if kind != "file": |
| 9443 | raise object_webdav.DavRequestError(403, "The folder itself cannot be deleted.") |
| 9444 | # decided before the lookup, as DELETE /api/files/{id} is |
| 9445 | if not await _user_files_collection_allowed(send, dav_headers, object_permissions.DELETE, method="DELETE"): |
| 9446 | return |
| 9447 | f = _webdav_file(_webdav_folder(dav_headers, user_id), name) |
| 9448 | _webdav_preconditions(dav_headers, f) |
| 9449 | if not await _user_file_allowed( |
| 9450 | send, dav_headers, object_permissions.DELETE, record=f.record, method="DELETE", collection_checked=True |
| 9451 | ): |
| 9452 | return |
| 9453 | if await _remove_user_file(send, dav_headers, f.record): |
| 9454 | await _send_response(send, status=204, headers=[], body=b"") |
| 9455 | |
| 9456 | |
| 9457 | async def _webdav_move_or_copy(send, dav_headers, user_id, kind, name, *, copy: bool) -> None: |
| 9458 | if kind != "file": |
| 9459 | raise object_webdav.DavRequestError(403, "Folders cannot be moved or copied.") |
| 9460 | dest_kind, dest_name = object_webdav.split_path( |
| 9461 | object_webdav.destination_path(dav_headers.get("destination")) |
| 9462 | ) |
| 9463 | if dest_kind != "file": |
| 9464 | raise object_webdav.DavRequestError(403, "Files can only move or copy within /dav/files/.") |
| 9465 | dest_name = object_webdav.check_new_name(dest_name or "") |
| 9466 | overwrite = object_webdav.parse_overwrite(dav_headers.get("overwrite")) |
| 9467 | # a rename is a record update: its U1 is decided before the lookup, as |
| 9468 | # the record route decides it (_gated_update is told: collection_asked) |
| 9469 | now = datetime.now(timezone.utc) |
| 9470 | if not copy and await _record_write_denied_before_lookup( |
| 9471 | send, dav_headers, object_permissions.UPDATE, collection=USER_FILES_COLLECTION, now=now |
| 9472 | ): |
| 9473 | return |
| 9474 | folder = _webdav_folder(dav_headers, user_id) |
| 9475 | source = _webdav_file(folder, name) |
| 9476 | found = object_webdav.lookup(folder, dest_name) |
| 9477 | target = folder[found] if found else None |
| 9478 | if target is not None and target.record_id == source.record_id: |
| 9479 | if copy or dest_name == source.name: |
| 9480 | raise object_webdav.DavRequestError(403, "Source and destination are the same file.") |
| 9481 | target = None # a rename that only changes case |
| 9482 | if target is not None: |
| 9483 | if not overwrite: |
| 9484 | raise object_webdav.DavRequestError(412, "The destination exists (Overwrite: F).") |
| 9485 | if not await _user_file_allowed(send, dav_headers, object_permissions.DELETE, record=target.record, method="DELETE"): |
| 9486 | return |
| 9487 | content_type = _webdav_content_type(dest_name, source.content_type) |
| 9488 | |
| 9489 | if copy: |
| 9490 | if not await _user_file_allowed( |
| 9491 | send, dav_headers, object_permissions.READ, record=source.record, method="GET", |
| 9492 | collection_checked=True, |
| 9493 | ): |
| 9494 | return |
| 9495 | try: |
| 9496 | content = object_user_files.read_file(user_id, source.record_id, base_dir=_data_dir()) |
| 9497 | except (object_user_files.UserFileNotFoundError, object_user_files.InvalidUserFileError): |
| 9498 | raise object_webdav.DavRequestError(404, "File bytes missing.") from None |
| 9499 | if target is not None and not await _remove_user_file(send, dav_headers, target.record): |
| 9500 | return |
| 9501 | stored = await _create_user_file( |
| 9502 | send, dav_headers, owner_id=user_id, filename=dest_name, content=content, content_type=content_type |
| 9503 | ) |
| 9504 | if stored is not None: |
| 9505 | await _send_response(send, status=204 if target else 201, headers=[], body=b"") |
| 9506 | return |
| 9507 | |
| 9508 | # Kept difference: an overwriting rename removes the destination |
| 9509 | # before the rename's own gates run, so a rename they refuse has |
| 9510 | # already removed it. Reordering would change which refusal wins. |
| 9511 | if target is not None and not await _remove_user_file(send, dav_headers, target.record): |
| 9512 | return |
| 9513 | updated = await _gated_update( |
| 9514 | dav_headers, |
| 9515 | collection=USER_FILES_COLLECTION, |
| 9516 | record_id=source.record_id, |
| 9517 | existing=source.record, |
| 9518 | changes={"filename": dest_name, "content_type": content_type}, |
| 9519 | now=now, |
| 9520 | collection_asked=True, |
| 9521 | shape_answer=False, # WebDAV answers with no body |
| 9522 | ) |
| 9523 | if isinstance(updated, _WriteRefusal): |
| 9524 | await updated.replay(send) |
| 9525 | return |
| 9526 | await _send_response(send, status=204 if target else 201, headers=[], body=b"") |
| 9527 | |
| 9528 | |
| 9529 | async def _webdav_proppatch(send, dav_headers, user_id, kind, name, body) -> None: |
| 9530 | """No property here is writable (sizes and times are the file's own); |
| 9531 | each one a client tries to set is refused with 403, which clients that |
| 9532 | set times after an upload (Windows, Finder) accept and carry on.""" |
| 9533 | names = object_webdav.parse_proppatch(body) |
| 9534 | if kind == "file": |
| 9535 | f = _webdav_file(_webdav_folder(dav_headers, user_id), name) |
| 9536 | target = object_webdav.href(object_webdav.FILES_FOLDER, f.name) |
| 9537 | else: |
| 9538 | target = object_webdav.href(*( [object_webdav.FILES_FOLDER] if kind == "files" else []), folder=True) |
| 9539 | await _send_response( |
| 9540 | send, |
| 9541 | status=207, |
| 9542 | headers=[("content-type", "application/xml; charset=utf-8")], |
| 9543 | body=object_webdav.proppatch_refused(target, names), |
| 9544 | ) |
| 9545 | |
| 9546 | |
| 9547 | async def _send_bytes( |
| 9548 | send, |
| 9549 | content: bytes, |
| 9550 | *, |
| 9551 | content_type: str, |
| 9552 | status: int = 200, |
| 9553 | extra_headers: list[tuple[bytes, bytes]] | None = None, |
| 9554 | ) -> None: |
| 9555 | response_headers = [ |
| 9556 | (b"content-type", content_type.encode("latin-1", "replace")), |
| 9557 | (b"content-length", str(len(content)).encode("ascii")), |
| 9558 | ] |
| 9559 | response_headers.extend(extra_headers or []) |
| 9560 | await send( |
| 9561 | {"type": "http.response.start", "status": status, "headers": response_headers} |
| 9562 | ) |
| 9563 | await send({"type": "http.response.body", "body": content}) |
| 9564 | |
| 9565 | |
| 9566 | def _env_int(name: str, default: int) -> int: |
| 9567 | raw = os.environ.get(name, "").strip() |
| 9568 | if not raw: |
| 9569 | return default |
| 9570 | try: |
| 9571 | value = int(raw) |
| 9572 | except ValueError: |
| 9573 | return default |
| 9574 | return value if value > 0 else default |
| 9575 | |
| 9576 | |
| 9577 | AI_CHAT_ENABLED_ENV = "DBBASIC_ENABLE_AI_CHAT" |
| 9578 | AI_CHAT_TIMEOUT_ENV = "DBBASIC_AI_TIMEOUT_SECONDS" |
| 9579 | AI_DEFAULT_MODEL_ENV = "DBBASIC_AI_DEFAULT_MODEL" |
| 9580 | AI_EFFORT_ENV = "DBBASIC_AI_EFFORT" |
| 9581 | AI_BUILDER_EFFORT_ENV = "DBBASIC_AI_BUILDER_EFFORT" |
| 9582 | AI_MAX_TOKENS_CAP_ENV = "DBBASIC_AI_MAX_TOKENS_CAP" |
| 9583 | DEFAULT_AI_MODEL = "anthropic:claude-haiku-5-5" |
| 9584 | DEFAULT_AI_TIMEOUT_SECONDS = 60.0 |
| 9585 | AI_PRICES_COLLECTION = "ai_prices" |
| 9586 | AI_USAGE_COLLECTION = "ai_usage" |
| 9587 | |
| 9588 | |
| 9589 | def _env_choice(name: str, choices: tuple[str, ...], default: str) -> str: |
| 9590 | raw = os.environ.get(name, "").strip().lower() |
| 9591 | return raw if raw in choices else default |
| 9592 | |
| 9593 | |
| 9594 | def _text_field(value) -> str: |
| 9595 | return str(value if value is not None else "").strip() |
| 9596 | |
| 9597 | |
| 9598 | def _utc_now_iso() -> str: |
| 9599 | from datetime import datetime, timezone |
| 9600 | return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 9601 | |
| 9602 | |
| 9603 | async def _handle_ai_chat( |
| 9604 | send, |
| 9605 | method: str, |
| 9606 | body: bytes, |
| 9607 | headers: dict[str, str], |
| 9608 | ) -> None: |
| 9609 | """One AI conversation turn using the caller's stored provider key. |
| 9610 | |
| 9611 | The model may call a caller-chosen subset of the MCP tool catalog; |
| 9612 | every tool call dispatches through the server's own routing with the |
| 9613 | caller's credentials, so the AI can do exactly what the caller could |
| 9614 | do directly — nothing more — and it all lands in the audit trail. |
| 9615 | """ |
| 9616 | if method != "POST": |
| 9617 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 9618 | return |
| 9619 | |
| 9620 | if not _env_enabled(AI_CHAT_ENABLED_ENV): |
| 9621 | await _send_json( |
| 9622 | send, |
| 9623 | {"status": "error", "error": f"AI chat is disabled. Set {AI_CHAT_ENABLED_ENV}=true."}, |
| 9624 | status=403, |
| 9625 | ) |
| 9626 | return |
| 9627 | |
| 9628 | session = _current_identity_session(headers) |
| 9629 | if session is None: |
| 9630 | await _send_json( |
| 9631 | send, |
| 9632 | {"status": "error", "error": "AI chat requires a signed-in session."}, |
| 9633 | status=401, |
| 9634 | ) |
| 9635 | return |
| 9636 | |
| 9637 | # A cross-origin request that carries only the session cookie never gets |
| 9638 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 9639 | # request rejected") before any handler runs. |
| 9640 | |
| 9641 | try: |
| 9642 | payload = _parse_json_body(body) |
| 9643 | except ValueError as exc: |
| 9644 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 9645 | return |
| 9646 | |
| 9647 | message = payload.get("message") |
| 9648 | model = payload.get("model") or os.environ.get(AI_DEFAULT_MODEL_ENV, DEFAULT_AI_MODEL) |
| 9649 | tool_names = payload.get("tools") or [] |
| 9650 | system = payload.get("system") |
| 9651 | # Per-request system text (the local time, the last page read). Kept |
| 9652 | # out of `system` so the stable instructions can be prompt-cached; see |
| 9653 | # object_ai's CACHE_CONTROL comment. |
| 9654 | context = payload.get("context") |
| 9655 | |
| 9656 | if not isinstance(tool_names, list) or not all( |
| 9657 | isinstance(name, str) and name for name in tool_names |
| 9658 | ): |
| 9659 | await _send_json( |
| 9660 | send, |
| 9661 | {"status": "error", "error": "tools must be a list of MCP tool names"}, |
| 9662 | status=400, |
| 9663 | ) |
| 9664 | return |
| 9665 | |
| 9666 | try: |
| 9667 | service, model_name = object_ai.split_model(model) |
| 9668 | provider_tools = object_ai.mcp_tools_as_provider_tools( |
| 9669 | tool_names, object_mcp.TOOLS, service=service |
| 9670 | ) |
| 9671 | max_rounds_raw = payload.get("max_rounds", object_ai.DEFAULT_MAX_ROUNDS) |
| 9672 | if isinstance(max_rounds_raw, bool) or not isinstance(max_rounds_raw, int): |
| 9673 | raise object_ai.InvalidChatRequestError("max_rounds must be an integer") |
| 9674 | max_rounds = max_rounds_raw |
| 9675 | stream = payload.get("stream", False) |
| 9676 | if not isinstance(stream, bool): |
| 9677 | raise object_ai.InvalidChatRequestError("stream must be true or false") |
| 9678 | mode = object_ai.chat_mode(tool_names) |
| 9679 | max_tokens = object_ai.resolve_max_tokens( |
| 9680 | payload.get("max_tokens"), mode=mode, stream=stream, |
| 9681 | cap=_env_int(AI_MAX_TOKENS_CAP_ENV, 0) or None, |
| 9682 | ) |
| 9683 | effort = object_ai.resolve_effort( |
| 9684 | payload.get("effort"), mode=mode, |
| 9685 | conversation_default=_env_choice( |
| 9686 | AI_EFFORT_ENV, object_ai.EFFORT_LEVELS, object_ai.DEFAULT_CONVERSATION_EFFORT), |
| 9687 | builder_default=_env_choice( |
| 9688 | AI_BUILDER_EFFORT_ENV, object_ai.EFFORT_LEVELS, object_ai.DEFAULT_BUILDER_EFFORT), |
| 9689 | ) |
| 9690 | except (object_ai.InvalidChatRequestError, ValueError) as exc: |
| 9691 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 9692 | return |
| 9693 | |
| 9694 | # --- chat attachments: file ids -> provider-neutral parts ---------------- |
| 9695 | # |
| 9696 | # Resolved HERE, after the key check and before any provider call, so a |
| 9697 | # refused attachment costs nothing. The split of labour: this handler |
| 9698 | # does all the I/O (ownership, record lookup, blob read) and |
| 9699 | # object_ai.attachment_part does the pure classification, so the gate |
| 9700 | # logic is testable without a data directory. |
| 9701 | # |
| 9702 | # OWNERSHIP IS STRICT in v1: the caller may attach only files whose |
| 9703 | # record they own. Deliberately not consulting record_shares yet -- a |
| 9704 | # share grants READ of the record, and whether that extends to feeding |
| 9705 | # the blob into an AI provider is a real question (the provider sees |
| 9706 | # the content), so it waits to be decided rather than being implied. |
| 9707 | # The refusal says so. |
| 9708 | # |
| 9709 | # Owning the file is not enough under enforcement: sending its bytes to |
| 9710 | # a provider is a read, so it also needs what GET /api/files/{id} needs |
| 9711 | # (_user_attachment_readable). Without that, a policy granting nothing |
| 9712 | # on files still let the owner fallback feed the file to the provider. |
| 9713 | # |
| 9714 | # Every problem is reported at once (the blockers idiom): a user who |
| 9715 | # attached four files does not want them peeled back one error at a |
| 9716 | # time. |
| 9717 | attachment_ids = payload.get("attachments") or [] |
| 9718 | attachment_parts: list[dict[str, Any]] = [] |
| 9719 | if attachment_ids: |
| 9720 | if not isinstance(attachment_ids, list) or not all( |
| 9721 | isinstance(fid, str) and fid for fid in attachment_ids |
| 9722 | ): |
| 9723 | await _send_json( |
| 9724 | send, |
| 9725 | {"status": "error", "error": "attachments must be a list of file ids"}, |
| 9726 | status=400, |
| 9727 | ) |
| 9728 | return |
| 9729 | problems: list[str] = [] |
| 9730 | # asked before any file is looked up, as GET /api/files/{id} asks it |
| 9731 | files_readable = await _user_attachment_readable(headers, None) |
| 9732 | if files_readable is not True and files_readable is not False: |
| 9733 | # the policy could not be read (503): the server's problem, not |
| 9734 | # the attachments' |
| 9735 | await files_readable.replay(send) |
| 9736 | return |
| 9737 | if files_readable is False: |
| 9738 | # the same for every id, existing or not, so it says nothing |
| 9739 | # about which files exist |
| 9740 | problems.append( |
| 9741 | "Attachments are read as files, and the permission policy " |
| 9742 | "does not let you read files." |
| 9743 | ) |
| 9744 | checked_ids = attachment_ids[: object_ai.MAX_ATTACHMENTS_PER_TURN + 1] if files_readable else [] |
| 9745 | for fid in checked_ids: |
| 9746 | # Someone else's file answers exactly like a missing one: naming |
| 9747 | # it ("<filename>: not your file") let any signed-in user read |
| 9748 | # other people's filenames by guessing ids. |
| 9749 | not_found = ( |
| 9750 | f"{fid}: no such file among yours. Chat " |
| 9751 | f"attachments are owner-only for now -- a share grants " |
| 9752 | f"read of the record, and whether that extends to sending " |
| 9753 | f"the content to an AI provider is deliberately not yet " |
| 9754 | f"decided." |
| 9755 | ) |
| 9756 | try: |
| 9757 | record = object_records.get_collection_record( |
| 9758 | USER_FILES_COLLECTION, fid, base_dir=_data_dir() |
| 9759 | ) |
| 9760 | except Exception: |
| 9761 | problems.append(not_found) |
| 9762 | continue |
| 9763 | if str(record.get("owner_id") or "") != str(session.user_id): |
| 9764 | problems.append(not_found) |
| 9765 | continue |
| 9766 | readable = await _user_attachment_readable(headers, record) |
| 9767 | if readable is not True: |
| 9768 | if readable is not False: |
| 9769 | await readable.replay(send) # 503, as above |
| 9770 | return |
| 9771 | problems.append(not_found) |
| 9772 | continue |
| 9773 | try: |
| 9774 | blob = object_user_files.read_file( |
| 9775 | str(record.get("owner_id")), fid, base_dir=_data_dir() |
| 9776 | ) |
| 9777 | except Exception: |
| 9778 | problems.append(f"{record.get('filename') or fid}: bytes are missing") |
| 9779 | continue |
| 9780 | try: |
| 9781 | attachment_parts.append(object_ai.attachment_part( |
| 9782 | str(record.get("filename") or fid), |
| 9783 | str(record.get("content_type") or ""), |
| 9784 | blob, |
| 9785 | )) |
| 9786 | except object_ai.InvalidChatRequestError as exc: |
| 9787 | problems.append(str(exc)) |
| 9788 | if len(attachment_ids) > object_ai.MAX_ATTACHMENTS_PER_TURN: |
| 9789 | problems.append( |
| 9790 | f"{len(attachment_ids)} attachments; the limit is " |
| 9791 | f"{object_ai.MAX_ATTACHMENTS_PER_TURN} per message." |
| 9792 | ) |
| 9793 | if problems: |
| 9794 | await _send_json( |
| 9795 | send, |
| 9796 | {"status": "error", |
| 9797 | "error": " ".join(problems), "problems": problems}, |
| 9798 | status=400, |
| 9799 | ) |
| 9800 | return |
| 9801 | |
| 9802 | key = object_service_keys.get_service_key(session.user_id, service, base_dir=_data_dir()) |
| 9803 | if key is None: |
| 9804 | await _send_json( |
| 9805 | send, |
| 9806 | { |
| 9807 | "status": "error", |
| 9808 | "error": ( |
| 9809 | f"No {service} key stored. Set one with " |
| 9810 | f"PUT /identity/users/{session.user_id}/service-keys." |
| 9811 | ), |
| 9812 | }, |
| 9813 | status=400, |
| 9814 | ) |
| 9815 | return |
| 9816 | |
| 9817 | authorization = headers.get("authorization") or f"Bearer {cookie_token}" |
| 9818 | allowed_tools = set(tool_names) |
| 9819 | loop = asyncio.get_running_loop() |
| 9820 | timeout = _env_float(AI_CHAT_TIMEOUT_ENV, DEFAULT_AI_TIMEOUT_SECONDS) |
| 9821 | |
| 9822 | def send_http(url: str, request_headers, request_body: bytes) -> tuple[int, bytes]: |
| 9823 | request = urllib.request.Request( |
| 9824 | url, data=request_body, method="POST", headers=dict(request_headers) |
| 9825 | ) |
| 9826 | try: |
| 9827 | with urllib.request.urlopen(request, timeout=timeout) as response: |
| 9828 | return response.status, response.read() |
| 9829 | except urllib.error.HTTPError as exc: |
| 9830 | return exc.code, exc.read() |
| 9831 | |
| 9832 | def dispatch_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: |
| 9833 | if name not in allowed_tools: |
| 9834 | return {"http_status": 400, "response": {"error": f"Tool not offered: {name}"}} |
| 9835 | try: |
| 9836 | tool_method, tool_path, tool_query, tool_body = object_mcp.tool_route( |
| 9837 | name, dict(arguments or {}) |
| 9838 | ) |
| 9839 | except ValueError as exc: |
| 9840 | return {"http_status": 400, "response": {"error": str(exc)}} |
| 9841 | future = asyncio.run_coroutine_threadsafe( |
| 9842 | _internal_request( |
| 9843 | tool_method, tool_path, tool_query, tool_body, authorization=authorization |
| 9844 | ), |
| 9845 | loop, |
| 9846 | ) |
| 9847 | status, response_payload = future.result(timeout=timeout) |
| 9848 | return {"http_status": status, "response": response_payload} |
| 9849 | |
| 9850 | def send_http_stream(url: str, request_headers, request_body: bytes): |
| 9851 | request = urllib.request.Request( |
| 9852 | url, data=request_body, method="POST", headers=dict(request_headers) |
| 9853 | ) |
| 9854 | try: |
| 9855 | response = urllib.request.urlopen(request, timeout=timeout) |
| 9856 | except urllib.error.HTTPError as exc: |
| 9857 | return exc.code, [exc.read()] |
| 9858 | |
| 9859 | def lines(): |
| 9860 | # Closed when the parser stops reading (message_stop) or fails; |
| 9861 | # urlopen's timeout bounds each read, so a stalled stream ends |
| 9862 | # in an OSError rather than a hung turn. |
| 9863 | with response: |
| 9864 | yield from response |
| 9865 | |
| 9866 | return response.status, lines() |
| 9867 | |
| 9868 | turn_started = time.monotonic() |
| 9869 | run_kwargs = dict( |
| 9870 | send_http=send_http, |
| 9871 | dispatch_tool=dispatch_tool, |
| 9872 | service=service, |
| 9873 | model=model_name, |
| 9874 | key=key, |
| 9875 | message=message, |
| 9876 | system=system if isinstance(system, str) else None, |
| 9877 | context=context if isinstance(context, str) else None, |
| 9878 | tools=provider_tools, |
| 9879 | history=payload.get("history"), |
| 9880 | attachments=attachment_parts or None, |
| 9881 | max_rounds=max_rounds, |
| 9882 | max_tokens=max_tokens, |
| 9883 | effort=effort, |
| 9884 | ) |
| 9885 | |
| 9886 | def finish_turn(result: dict[str, Any]) -> dict[str, Any]: |
| 9887 | """Record the turn (cost, usage, history) and build the response. |
| 9888 | |
| 9889 | Shared by the JSON and the streamed response, so a streamed turn is |
| 9890 | priced and recorded by exactly the same code. |
| 9891 | """ |
| 9892 | # Cost recording is server-authoritative: the client never sees this |
| 9893 | # write and cannot omit or falsify it. Prices live in the ai_prices |
| 9894 | # collection (editable live, never hardcoded) -- a missing price row |
| 9895 | # still records the turn's tokens, just with a null cost, so pricing |
| 9896 | # gaps never fail a chat that otherwise succeeded. |
| 9897 | usage = result.get("usage") or {} |
| 9898 | tokens_in = int(usage.get("input_tokens") or 0) |
| 9899 | tokens_out = int(usage.get("output_tokens") or 0) |
| 9900 | price_row = object_ai.select_price_row( |
| 9901 | _read_ai_prices_or_empty(), provider=service, model=model_name |
| 9902 | ) |
| 9903 | cost_cents = object_ai.cost_cents_for_usage(usage, price_row) |
| 9904 | usage["cost_cents"] = cost_cents |
| 9905 | |
| 9906 | # The TURN record is server-authoritative for the same reason the cost |
| 9907 | # is: the client used to write its own history row after the reply, |
| 9908 | # fire-and-forget, which lost any turn whose page died first (a real |
| 9909 | # one vanished that way during live debugging -- billed in ai_usage, |
| 9910 | # absent from history) and stamped no timestamp at all. The server |
| 9911 | # writes it here, before the reply is even sent, so history survives |
| 9912 | # whatever the page does next. session_id is minted by the page and |
| 9913 | # merely recorded -- grouping is the client's claim, existence is the |
| 9914 | # server's fact. Best-effort by design: a history write must never |
| 9915 | # fail a chat that succeeded. |
| 9916 | turn_record = { |
| 9917 | "id": object_ids.new_uuid4(), |
| 9918 | "input": message[:8000], |
| 9919 | # run_chat's key is "reply" -- "text" was a straight typo, live |
| 9920 | # since this write was added, and every source-presence test |
| 9921 | # passed anyway because none of them checked the RECORDED VALUE, |
| 9922 | # only that the strings existed somewhere in the file. Every |
| 9923 | # turn recorded before this fix has output == "" regardless of |
| 9924 | # what the model actually said; the reply the USER saw was |
| 9925 | # correct the whole time (the HTTP response spreads **result |
| 9926 | # directly), so this was invisible everywhere except the log |
| 9927 | # meant to make turns inspectable -- exactly where a session |
| 9928 | # review found it. |
| 9929 | "output": _text_field(result.get("reply"))[:20000], |
| 9930 | "kind": "ai", |
| 9931 | "owner_id": session.user_id, |
| 9932 | "session_id": _text_field(payload.get("session_id"))[:64], |
| 9933 | "source": _text_field(payload.get("source"))[:16] or "api", |
| 9934 | "model": f"{service}:{model_name}", |
| 9935 | "duration_ms": str(int((time.monotonic() - turn_started) * 1000)), |
| 9936 | "tool_calls": json.dumps([c.get("name") for c in |
| 9937 | (result.get("tool_calls") or []) if c.get("name")]), |
| 9938 | "created_at": _utc_now_iso(), |
| 9939 | } |
| 9940 | try: |
| 9941 | # write-path: the server's own history of a chat turn it just answered |
| 9942 | object_records.create_collection_record( |
| 9943 | "shell_commands", turn_record, base_dir=_data_dir(), actor=session.user_id) |
| 9944 | except Exception: |
| 9945 | pass # the reply matters more than the record of it |
| 9946 | |
| 9947 | usage_record = { |
| 9948 | "id": object_ids.new_uuid4(), |
| 9949 | "owner_id": session.user_id, |
| 9950 | "provider": service, |
| 9951 | "model": model_name, |
| 9952 | "tokens_in": tokens_in, |
| 9953 | "tokens_out": tokens_out, |
| 9954 | # Cached prompt tokens are reported beside tokens_in, not inside |
| 9955 | # it, and billed at their own rates -- recorded separately so a |
| 9956 | # cached turn's spend can be re-derived from the row alone. |
| 9957 | "tokens_cache_read": int(usage.get("cache_read_input_tokens") or 0), |
| 9958 | "tokens_cache_write": int(usage.get("cache_creation_input_tokens") or 0), |
| 9959 | } |
| 9960 | if cost_cents is not None: |
| 9961 | usage_record["cost_cents"] = cost_cents |
| 9962 | try: |
| 9963 | # write-path: the server's own spend bookkeeping for a provider call |
| 9964 | object_records.create_collection_record( |
| 9965 | AI_USAGE_COLLECTION, |
| 9966 | usage_record, |
| 9967 | base_dir=_data_dir(), |
| 9968 | roots=get_object_roots(), |
| 9969 | actor=session.user_id, |
| 9970 | ) |
| 9971 | except Exception as exc: |
| 9972 | # Recording usage is bookkeeping: the provider call already |
| 9973 | # happened and the user is owed the reply. Say so loudly in the |
| 9974 | # log (a missing row is lost spend data) but never fail the chat. |
| 9975 | _LOG.warning( |
| 9976 | "ai_usage row not recorded for user %s (%s:%s): %s: %s", |
| 9977 | session.user_id, service, model_name, type(exc).__name__, exc, |
| 9978 | ) |
| 9979 | |
| 9980 | return {"status": "ok", "model": model, **result} |
| 9981 | |
| 9982 | if stream: |
| 9983 | await _stream_ai_chat(send, run_kwargs, send_http_stream, finish_turn, |
| 9984 | loop=loop, timeout=timeout) |
| 9985 | return |
| 9986 | |
| 9987 | try: |
| 9988 | result = await asyncio.to_thread(object_ai.run_chat, **run_kwargs) |
| 9989 | except object_ai.InvalidChatRequestError as exc: |
| 9990 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 9991 | return |
| 9992 | except object_ai.AIProviderError as exc: |
| 9993 | await _send_json(send, {"status": "error", "error": str(exc)}, status=502) |
| 9994 | return |
| 9995 | except (TimeoutError, OSError) as exc: |
| 9996 | await _send_json( |
| 9997 | send, |
| 9998 | {"status": "error", "error": f"AI provider request failed: {exc}"}, |
| 9999 | status=502, |
| 10000 | ) |
| 10001 | return |
| 10002 | |
| 10003 | await _send_json(send, finish_turn(result)) |
| 10004 | |
| 10005 | |
| 10006 | def _sse_event(kind: str, data: Any) -> bytes: |
| 10007 | return f"event: {kind}\ndata: {json.dumps(data, default=str)}\n\n".encode("utf-8") |
| 10008 | |
| 10009 | |
| 10010 | async def _stream_ai_chat(send, run_kwargs, send_http_stream, finish_turn, *, |
| 10011 | loop, timeout: float) -> None: |
| 10012 | """The streamed form of one chat turn, as server-sent events. |
| 10013 | |
| 10014 | Events: ``text`` ({"text": delta}) while the model writes, |
| 10015 | ``tool_call`` (the tool log entry) after each tool runs, then exactly |
| 10016 | one of ``done`` (the same JSON the non-streamed endpoint returns, |
| 10017 | written after the turn is recorded) or ``error`` ({"status": "error", |
| 10018 | "error", "http_status"} -- the status the JSON endpoint would have |
| 10019 | used). Every check that can refuse a turn (flag, session, origin, |
| 10020 | body, model, tools, attachments, key) has already run, so those |
| 10021 | refusals stay ordinary JSON responses with their real status codes. |
| 10022 | |
| 10023 | The turn runs in a worker thread exactly like the JSON path; text and |
| 10024 | tool events hop back to the event loop to be written. A browser that |
| 10025 | goes away mid-turn does not stop it: the provider has been paid |
| 10026 | either way, so the turn finishes, runs its tools as the JSON path |
| 10027 | would, and is recorded -- only the writes to the closed connection |
| 10028 | are dropped. |
| 10029 | """ |
| 10030 | await send({ |
| 10031 | "type": "http.response.start", |
| 10032 | "status": 200, |
| 10033 | "headers": [ |
| 10034 | (b"content-type", b"text/event-stream; charset=utf-8"), |
| 10035 | (b"cache-control", b"no-cache"), |
| 10036 | # Proxies (nginx) buffer responses by default, which would hold |
| 10037 | # every delta until the turn ends. |
| 10038 | (b"x-accel-buffering", b"no"), |
| 10039 | ], |
| 10040 | }) |
| 10041 | client_gone = False |
| 10042 | |
| 10043 | async def write(kind: str, data: Any) -> None: |
| 10044 | nonlocal client_gone |
| 10045 | if client_gone: |
| 10046 | return |
| 10047 | try: |
| 10048 | await send({"type": "http.response.body", "body": _sse_event(kind, data), |
| 10049 | "more_body": True}) |
| 10050 | except Exception: # noqa: BLE001 -- a closed connection must not fail the turn |
| 10051 | client_gone = True |
| 10052 | |
| 10053 | def on_event(kind: str, data: dict[str, Any]) -> None: |
| 10054 | future = asyncio.run_coroutine_threadsafe(write(kind, data), loop) |
| 10055 | try: |
| 10056 | future.result(timeout=timeout) |
| 10057 | except Exception: # noqa: BLE001 -- see write() |
| 10058 | pass |
| 10059 | |
| 10060 | error: tuple[int, str] | None = None |
| 10061 | try: |
| 10062 | result = await asyncio.to_thread( |
| 10063 | object_ai.run_chat, **run_kwargs, stream=True, |
| 10064 | send_http_stream=send_http_stream, on_event=on_event) |
| 10065 | except object_ai.InvalidChatRequestError as exc: |
| 10066 | error = (400, str(exc)) |
| 10067 | except object_ai.AIProviderError as exc: |
| 10068 | error = (502, str(exc)) |
| 10069 | except (TimeoutError, OSError) as exc: |
| 10070 | error = (502, f"AI provider request failed: {exc}") |
| 10071 | |
| 10072 | if error is None: |
| 10073 | try: |
| 10074 | done = finish_turn(result) |
| 10075 | except Exception as exc: # noqa: BLE001 -- the JSON path would 500 here |
| 10076 | error = (500, f"The turn ran but could not be recorded: {exc}") |
| 10077 | else: |
| 10078 | await write("done", done) |
| 10079 | if error is not None: |
| 10080 | await write("error", {"status": "error", "error": error[1], "http_status": error[0]}) |
| 10081 | if not client_gone: |
| 10082 | try: |
| 10083 | await send({"type": "http.response.body", "body": b"", "more_body": False}) |
| 10084 | except Exception: # noqa: BLE001 |
| 10085 | pass |
| 10086 | |
| 10087 | |
| 10088 | def _read_ai_prices_or_empty() -> list[dict[str, str]]: |
| 10089 | try: |
| 10090 | return object_records.read_collection_records( |
| 10091 | AI_PRICES_COLLECTION, base_dir=_data_dir(), roots=get_object_roots() |
| 10092 | ) |
| 10093 | except ( |
| 10094 | object_collections.CollectionNotFoundError, |
| 10095 | object_collections.InvalidCollectionNameError, |
| 10096 | OSError, |
| 10097 | ValueError, |
| 10098 | ): |
| 10099 | return [] |
| 10100 | |
| 10101 | |
| 10102 | def _env_float(name: str, default: float) -> float: |
| 10103 | raw = os.environ.get(name, "").strip() |
| 10104 | if not raw: |
| 10105 | return default |
| 10106 | try: |
| 10107 | value = float(raw) |
| 10108 | except ValueError: |
| 10109 | return default |
| 10110 | return value if value > 0 else default |
| 10111 | |
| 10112 | |
| 10113 | TTS_ENABLED_ENV = "DBBASIC_ENABLE_TTS" |
| 10114 | TTS_MAX_CHARS = 800 |
| 10115 | TTS_CLOUD_TIMEOUT_ENV = "DBBASIC_TTS_CLOUD_TIMEOUT_SECONDS" |
| 10116 | DEFAULT_TTS_CLOUD_TIMEOUT_SECONDS = 30.0 |
| 10117 | TTS_ENGINES = ("local", "openai") |
| 10118 | |
| 10119 | |
| 10120 | async def _handle_tts( |
| 10121 | send, |
| 10122 | method: str, |
| 10123 | body: bytes, |
| 10124 | headers: dict[str, str], |
| 10125 | ) -> None: |
| 10126 | """Speak one line of text through whatever engine is installed. |
| 10127 | |
| 10128 | Mirrors _handle_ai_chat's gating exactly: a feature flag first (off by |
| 10129 | default), then a signed-in session (app() has already refused a |
| 10130 | cross-origin cookie request, as for every route). Successful audio is cached |
| 10131 | to disk (object_tts.cache_path) so a repeated line costs one |
| 10132 | synthesis, not one per request. |
| 10133 | |
| 10134 | Two engines, chosen per request via the "engine" field ("local", the |
| 10135 | default, or "openai"): local shells out to whatever's on the box |
| 10136 | (espeak-ng in production, robotic but free and always available); |
| 10137 | openai calls the caller's own stored key against a real cloud TTS |
| 10138 | model for a real per-call cost. Neither silently falls back to the |
| 10139 | other -- a caller who asked for cloud quality and hits a provider |
| 10140 | error should see that error, not a surprise robot voice. |
| 10141 | """ |
| 10142 | if method != "POST": |
| 10143 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10144 | return |
| 10145 | |
| 10146 | if not _env_enabled(TTS_ENABLED_ENV): |
| 10147 | await _send_json( |
| 10148 | send, |
| 10149 | {"status": "error", "error": f"TTS is disabled. Set {TTS_ENABLED_ENV}=true."}, |
| 10150 | status=403, |
| 10151 | ) |
| 10152 | return |
| 10153 | |
| 10154 | session = _current_identity_session(headers) |
| 10155 | if session is None: |
| 10156 | await _send_json( |
| 10157 | send, {"status": "error", "error": "TTS requires a signed-in session."}, status=401 |
| 10158 | ) |
| 10159 | return |
| 10160 | |
| 10161 | # A cross-origin request that carries only the session cookie never gets |
| 10162 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 10163 | # request rejected") before any handler runs. |
| 10164 | |
| 10165 | try: |
| 10166 | payload = _parse_json_body(body) |
| 10167 | except ValueError as exc: |
| 10168 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10169 | return |
| 10170 | |
| 10171 | text = payload.get("text") |
| 10172 | if not isinstance(text, str) or not text.strip(): |
| 10173 | await _send_json(send, {"status": "error", "error": "text is required"}, status=400) |
| 10174 | return |
| 10175 | if len(text) > TTS_MAX_CHARS: |
| 10176 | await _send_json( |
| 10177 | send, |
| 10178 | {"status": "error", "error": f"text exceeds {TTS_MAX_CHARS} characters"}, |
| 10179 | status=413, |
| 10180 | ) |
| 10181 | return |
| 10182 | |
| 10183 | voice = payload.get("voice") |
| 10184 | if voice is not None and not isinstance(voice, str): |
| 10185 | await _send_json(send, {"status": "error", "error": "voice must be a string"}, status=400) |
| 10186 | return |
| 10187 | |
| 10188 | engine = payload.get("engine") or "local" |
| 10189 | if engine not in TTS_ENGINES: |
| 10190 | await _send_json( |
| 10191 | send, |
| 10192 | {"status": "error", "error": f"engine must be one of {TTS_ENGINES}"}, |
| 10193 | status=400, |
| 10194 | ) |
| 10195 | return |
| 10196 | |
| 10197 | if engine == "openai": |
| 10198 | key = object_service_keys.get_service_key(session.user_id, "openai", base_dir=_data_dir()) |
| 10199 | if key is None: |
| 10200 | await _send_json( |
| 10201 | send, |
| 10202 | { |
| 10203 | "status": "error", |
| 10204 | "error": ( |
| 10205 | "No openai key stored. Set one with " |
| 10206 | f"PUT /identity/users/{session.user_id}/service-keys." |
| 10207 | ), |
| 10208 | }, |
| 10209 | status=400, |
| 10210 | ) |
| 10211 | return |
| 10212 | |
| 10213 | timeout = _env_float(TTS_CLOUD_TIMEOUT_ENV, DEFAULT_TTS_CLOUD_TIMEOUT_SECONDS) |
| 10214 | |
| 10215 | def send_http(url: str, request_headers, request_body: bytes) -> tuple[int, bytes]: |
| 10216 | request = urllib.request.Request( |
| 10217 | url, data=request_body, method="POST", headers=dict(request_headers) |
| 10218 | ) |
| 10219 | try: |
| 10220 | with urllib.request.urlopen(request, timeout=timeout) as response: |
| 10221 | return response.status, response.read() |
| 10222 | except urllib.error.HTTPError as exc: |
| 10223 | return exc.code, exc.read() |
| 10224 | |
| 10225 | try: |
| 10226 | audio, content_type, _from_cache = await asyncio.to_thread( |
| 10227 | object_tts.synthesize_cloud, text, voice, key, |
| 10228 | send_http=send_http, base_dir=_data_dir(), |
| 10229 | ) |
| 10230 | except object_tts.TTSProviderError as exc: |
| 10231 | await _send_json(send, {"status": "error", "error": str(exc)}, status=502) |
| 10232 | return |
| 10233 | |
| 10234 | await _send_bytes(send, audio, content_type=content_type) |
| 10235 | return |
| 10236 | |
| 10237 | try: |
| 10238 | audio, _from_cache = await asyncio.to_thread( |
| 10239 | object_tts.synthesize, text, voice, base_dir=_data_dir() |
| 10240 | ) |
| 10241 | except object_tts.TTSEngineNotFoundError as exc: |
| 10242 | await _send_json(send, {"status": "error", "error": str(exc)}, status=503) |
| 10243 | return |
| 10244 | except object_tts.TTSNotSupportedError as exc: |
| 10245 | await _send_json(send, {"status": "error", "error": str(exc)}, status=501) |
| 10246 | return |
| 10247 | except object_tts.TTSSynthesisError as exc: |
| 10248 | await _send_json(send, {"status": "error", "error": str(exc)}, status=502) |
| 10249 | return |
| 10250 | |
| 10251 | await _send_bytes(send, audio, content_type="audio/wav") |
| 10252 | |
| 10253 | |
| 10254 | STT_ENABLED_ENV = "DBBASIC_ENABLE_STT" |
| 10255 | STT_MAX_BYTES = 10_000_000 |
| 10256 | STT_TIMEOUT_ENV = "DBBASIC_STT_TIMEOUT_SECONDS" |
| 10257 | DEFAULT_STT_TIMEOUT_SECONDS = 30.0 |
| 10258 | DEFAULT_STT_CONTENT_TYPE = "audio/webm" |
| 10259 | |
| 10260 | |
| 10261 | async def _handle_stt( |
| 10262 | send, |
| 10263 | method: str, |
| 10264 | body: bytes, |
| 10265 | headers: dict[str, str], |
| 10266 | ) -> None: |
| 10267 | """Transcribe one recorded audio clip through OpenAI's cloud STT. |
| 10268 | |
| 10269 | Mirrors _handle_tts's gating exactly (feature flag, then session; app() |
| 10270 | refuses a cross-origin cookie request first). There is no local-engine path here to fall |
| 10271 | back to -- see object_stt.py's docstring for why: voice input in this |
| 10272 | codebase is otherwise 100% browser-native SpeechRecognition, which |
| 10273 | never reaches the server at all. This is the "not on device" |
| 10274 | alternative, for browsers/devices that lack that API entirely. |
| 10275 | |
| 10276 | The request body is the raw audio bytes themselves (whatever |
| 10277 | MediaRecorder produced client-side), not JSON -- the client's own |
| 10278 | Content-Type header says what format it is. |
| 10279 | """ |
| 10280 | if method != "POST": |
| 10281 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10282 | return |
| 10283 | |
| 10284 | if not _env_enabled(STT_ENABLED_ENV): |
| 10285 | await _send_json( |
| 10286 | send, |
| 10287 | {"status": "error", "error": f"STT is disabled. Set {STT_ENABLED_ENV}=true."}, |
| 10288 | status=403, |
| 10289 | ) |
| 10290 | return |
| 10291 | |
| 10292 | session = _current_identity_session(headers) |
| 10293 | if session is None: |
| 10294 | await _send_json( |
| 10295 | send, {"status": "error", "error": "STT requires a signed-in session."}, status=401 |
| 10296 | ) |
| 10297 | return |
| 10298 | |
| 10299 | # A cross-origin request that carries only the session cookie never gets |
| 10300 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 10301 | # request rejected") before any handler runs. |
| 10302 | |
| 10303 | if not body: |
| 10304 | await _send_json(send, {"status": "error", "error": "audio body is required"}, status=400) |
| 10305 | return |
| 10306 | if len(body) > STT_MAX_BYTES: |
| 10307 | await _send_json( |
| 10308 | send, |
| 10309 | {"status": "error", "error": f"audio exceeds {STT_MAX_BYTES} bytes"}, |
| 10310 | status=413, |
| 10311 | ) |
| 10312 | return |
| 10313 | |
| 10314 | key = object_service_keys.get_service_key(session.user_id, "openai", base_dir=_data_dir()) |
| 10315 | if key is None: |
| 10316 | await _send_json( |
| 10317 | send, |
| 10318 | { |
| 10319 | "status": "error", |
| 10320 | "error": ( |
| 10321 | "No openai key stored. Set one with " |
| 10322 | f"PUT /identity/users/{session.user_id}/service-keys." |
| 10323 | ), |
| 10324 | }, |
| 10325 | status=400, |
| 10326 | ) |
| 10327 | return |
| 10328 | |
| 10329 | content_type = (headers.get("content-type") or DEFAULT_STT_CONTENT_TYPE).strip() |
| 10330 | timeout = _env_float(STT_TIMEOUT_ENV, DEFAULT_STT_TIMEOUT_SECONDS) |
| 10331 | |
| 10332 | def send_http(url: str, request_headers, request_body: bytes) -> tuple[int, bytes]: |
| 10333 | request = urllib.request.Request( |
| 10334 | url, data=request_body, method="POST", headers=dict(request_headers) |
| 10335 | ) |
| 10336 | try: |
| 10337 | with urllib.request.urlopen(request, timeout=timeout) as response: |
| 10338 | return response.status, response.read() |
| 10339 | except urllib.error.HTTPError as exc: |
| 10340 | return exc.code, exc.read() |
| 10341 | |
| 10342 | try: |
| 10343 | text = await asyncio.to_thread( |
| 10344 | object_stt.transcribe_cloud, body, content_type, key, send_http=send_http, |
| 10345 | ) |
| 10346 | except object_stt.STTProviderError as exc: |
| 10347 | await _send_json(send, {"status": "error", "error": str(exc)}, status=502) |
| 10348 | return |
| 10349 | |
| 10350 | await _send_json(send, {"status": "ok", "text": text}) |
| 10351 | |
| 10352 | |
| 10353 | READER_ENABLED_ENV = "DBBASIC_ENABLE_READER" |
| 10354 | READER_TIMEOUT_SECONDS_ENV = "DBBASIC_READER_TIMEOUT_SECONDS" |
| 10355 | READER_MAX_BYTES_ENV = "DBBASIC_READER_MAX_BYTES" |
| 10356 | DEFAULT_READER_TIMEOUT_SECONDS = 10.0 |
| 10357 | DEFAULT_READER_MAX_BYTES = 2_000_000 |
| 10358 | |
| 10359 | |
| 10360 | async def _handle_read( |
| 10361 | send, |
| 10362 | method: str, |
| 10363 | body: bytes, |
| 10364 | headers: dict[str, str], |
| 10365 | ) -> None: |
| 10366 | """Fetch one URL server-side and return {title, text, links}. |
| 10367 | |
| 10368 | Mirrors _handle_tts's gating shape exactly: a feature flag first (off |
| 10369 | by default), then a signed-in session (app() has already refused a |
| 10370 | cross-origin cookie request, as for every route) -- the capability |
| 10371 | being gated is the server reaching outbound, not the fetched content |
| 10372 | (which is public web data either way). The global per-request rate |
| 10373 | limiter above already covers this path like every other route; the |
| 10374 | SSRF gate itself lives in object_reader and cannot be bypassed here. |
| 10375 | """ |
| 10376 | if method != "POST": |
| 10377 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10378 | return |
| 10379 | |
| 10380 | if not _env_enabled(READER_ENABLED_ENV): |
| 10381 | await _send_json( |
| 10382 | send, |
| 10383 | {"status": "error", "error": f"Reader is disabled. Set {READER_ENABLED_ENV}=true."}, |
| 10384 | status=403, |
| 10385 | ) |
| 10386 | return |
| 10387 | |
| 10388 | session = _current_identity_session(headers) |
| 10389 | if session is None: |
| 10390 | await _send_json( |
| 10391 | send, {"status": "error", "error": "Reader requires a signed-in session."}, status=401 |
| 10392 | ) |
| 10393 | return |
| 10394 | |
| 10395 | # A cross-origin request that carries only the session cookie never gets |
| 10396 | # here: app() refuses it for every route (403 "Cross-origin cookie |
| 10397 | # request rejected") before any handler runs. |
| 10398 | |
| 10399 | try: |
| 10400 | payload = _parse_json_body(body) |
| 10401 | except ValueError as exc: |
| 10402 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10403 | return |
| 10404 | |
| 10405 | url = payload.get("url") |
| 10406 | if not isinstance(url, str) or not url.strip(): |
| 10407 | await _send_json(send, {"status": "error", "error": "url is required"}, status=400) |
| 10408 | return |
| 10409 | |
| 10410 | timeout = _env_float(READER_TIMEOUT_SECONDS_ENV, DEFAULT_READER_TIMEOUT_SECONDS) |
| 10411 | max_bytes = _env_int(READER_MAX_BYTES_ENV, DEFAULT_READER_MAX_BYTES) |
| 10412 | |
| 10413 | try: |
| 10414 | result = await asyncio.to_thread( |
| 10415 | object_reader.read_page, url.strip(), timeout=timeout, max_bytes=max_bytes |
| 10416 | ) |
| 10417 | except object_reader.ReaderError as exc: |
| 10418 | try: |
| 10419 | object_logs.append_object_log( |
| 10420 | "object_reader", "WARNING", f"read_page refused/failed: {exc}", base_dir=_data_dir() |
| 10421 | ) |
| 10422 | except Exception: |
| 10423 | pass |
| 10424 | await _send_json(send, {"status": "error", "error": str(exc)}, status=502) |
| 10425 | return |
| 10426 | |
| 10427 | try: |
| 10428 | object_logs.append_object_log( |
| 10429 | "object_reader", |
| 10430 | "INFO", |
| 10431 | f"read_page fetched {url.strip()} -> {result['final_url']} " |
| 10432 | f"truncated={result['truncated']} actor={session.user_id}", |
| 10433 | base_dir=_data_dir(), |
| 10434 | ) |
| 10435 | except Exception: |
| 10436 | pass |
| 10437 | |
| 10438 | await _send_json(send, {"status": "ok", **result}) |
| 10439 | |
| 10440 | |
| 10441 | async def _handle_search( |
| 10442 | send, |
| 10443 | method: str, |
| 10444 | query: dict[str, str], |
| 10445 | headers: dict[str, str], |
| 10446 | ) -> None: |
| 10447 | if method != "GET": |
| 10448 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10449 | return |
| 10450 | |
| 10451 | search_query = (query.get("q") or "").strip() |
| 10452 | if not search_query: |
| 10453 | await _send_json( |
| 10454 | send, |
| 10455 | {"status": "error", "error": "Search requires a q query parameter."}, |
| 10456 | status=400, |
| 10457 | ) |
| 10458 | return |
| 10459 | |
| 10460 | try: |
| 10461 | limit = _query_int( |
| 10462 | query, |
| 10463 | "limit", |
| 10464 | default=object_search.DEFAULT_COLLECTION_LIMIT, |
| 10465 | minimum=1, |
| 10466 | maximum=object_search.MAX_COLLECTION_LIMIT, |
| 10467 | ) |
| 10468 | except ValueError as exc: |
| 10469 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10470 | return |
| 10471 | |
| 10472 | requested_raw = (query.get("collections") or "").strip() |
| 10473 | requested = {name.strip() for name in requested_raw.split(",") if name.strip()} or None |
| 10474 | |
| 10475 | subject = None |
| 10476 | policy = None |
| 10477 | enforced = _permission_enforcement_enabled() |
| 10478 | # Not enforced (off or audit): the off-mode admin gate decides. In audit |
| 10479 | # mode a refused request is still decided per collection and logged below. |
| 10480 | gate_error = None |
| 10481 | if not enforced: |
| 10482 | gate_error = _admin_token_gate_error(headers, f"Search requires {ADMIN_TOKEN_ENV}.") |
| 10483 | if _permission_checks_enabled(): |
| 10484 | subject = _permission_subject(headers) |
| 10485 | policy, policy_error = _load_policy_for_request(headers) |
| 10486 | if policy is None: |
| 10487 | if enforced: |
| 10488 | await _send_policy_unavailable(send, headers, policy_error or "") |
| 10489 | return |
| 10490 | subject = None # audit only, nothing to decide against |
| 10491 | if gate_error is not None and subject is None: |
| 10492 | status, message = gate_error |
| 10493 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10494 | return |
| 10495 | |
| 10496 | results: dict[str, list[dict[str, str]]] = {} |
| 10497 | warnings: list[str] = [] |
| 10498 | total = 0 |
| 10499 | now = datetime.now(timezone.utc) # one instant for every decision below |
| 10500 | try: |
| 10501 | # Lists every collection name, policy rules included, and so raises |
| 10502 | # while the policy file is broken (object_collections keeps a name |
| 10503 | # from quietly becoming known or unknown then). Reached only by the |
| 10504 | # admin token in that state; it gets the 503 with the detail. |
| 10505 | schema_summaries = object_schemas.list_schemas(base_dir=_data_dir()) |
| 10506 | except (OSError, ValueError) as exc: |
| 10507 | await _send_policy_unavailable(send, headers, _policy_unavailable_error(exc)) |
| 10508 | return |
| 10509 | for summary in schema_summaries: |
| 10510 | name = summary["name"] |
| 10511 | if requested is not None and name not in requested: |
| 10512 | continue |
| 10513 | try: |
| 10514 | schema = object_schemas.get_schema(name, base_dir=_data_dir()) |
| 10515 | except (LookupError, ValueError): |
| 10516 | continue |
| 10517 | |
| 10518 | try: |
| 10519 | config = object_search.search_config(schema) |
| 10520 | except object_search.InvalidSearchConfigError as exc: |
| 10521 | warnings.append(f"{name}: {exc}") |
| 10522 | continue |
| 10523 | if config is None: |
| 10524 | continue |
| 10525 | |
| 10526 | if subject is not None and policy is not None: |
| 10527 | decision = object_permissions.check_permission( |
| 10528 | subject, |
| 10529 | object_permissions.READ, |
| 10530 | policy=policy, |
| 10531 | collection=name, |
| 10532 | now=now, |
| 10533 | ) |
| 10534 | _append_permission_audit_entry( |
| 10535 | action=object_permissions.READ, |
| 10536 | object_id=None, |
| 10537 | collection=name, |
| 10538 | method="GET", |
| 10539 | subject=subject, |
| 10540 | enforced=enforced, |
| 10541 | decision=decision, |
| 10542 | ) |
| 10543 | if enforced and not decision.allowed: |
| 10544 | continue |
| 10545 | if gate_error is not None: |
| 10546 | continue # audit mode, refused by the admin gate: logged, nothing read |
| 10547 | |
| 10548 | row_filtered = subject is not None and policy is not None and enforced |
| 10549 | row_read = None |
| 10550 | try: |
| 10551 | if row_filtered: |
| 10552 | row_read = _read_records_for_row_filter(name, subject=subject, policy=policy, now=now) |
| 10553 | records = row_read.records |
| 10554 | else: |
| 10555 | records = object_records.read_collection_records(name, base_dir=_data_dir()) |
| 10556 | except ( |
| 10557 | object_collections.CollectionNotFoundError, |
| 10558 | object_collections.InvalidCollectionNameError, |
| 10559 | ): |
| 10560 | records = [] |
| 10561 | row_read = None |
| 10562 | except ValueError: |
| 10563 | continue |
| 10564 | |
| 10565 | if row_filtered and row_read is not None: |
| 10566 | records = _filter_records_for_row_read( |
| 10567 | row_read, |
| 10568 | collection=name, |
| 10569 | subject=subject, |
| 10570 | policy=policy, |
| 10571 | ) |
| 10572 | |
| 10573 | matches = object_search.search_records(records, search_query, config, limit=limit) |
| 10574 | results[name] = matches |
| 10575 | total += len(matches) |
| 10576 | |
| 10577 | if gate_error is not None: |
| 10578 | status, message = gate_error |
| 10579 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10580 | return |
| 10581 | |
| 10582 | payload: dict[str, Any] = { |
| 10583 | "status": "ok", |
| 10584 | "query": search_query, |
| 10585 | "limit": limit, |
| 10586 | "results": results, |
| 10587 | "total_count": total, |
| 10588 | } |
| 10589 | if warnings: |
| 10590 | payload["warnings"] = warnings |
| 10591 | await _send_json(send, payload) |
| 10592 | |
| 10593 | |
| 10594 | async def _handle_collections( |
| 10595 | send, |
| 10596 | method: str, |
| 10597 | headers: dict[str, str], |
| 10598 | ) -> None: |
| 10599 | if method != "GET": |
| 10600 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10601 | return |
| 10602 | |
| 10603 | gate_error = _admin_token_gate_error( |
| 10604 | headers, |
| 10605 | f"Collection listing requires {ADMIN_TOKEN_ENV}.", |
| 10606 | ) |
| 10607 | if gate_error is not None: |
| 10608 | status, message = gate_error |
| 10609 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10610 | return |
| 10611 | |
| 10612 | try: |
| 10613 | collections = object_collections.list_collections(base_dir=_data_dir()) |
| 10614 | user_objects = object_collections.list_user_object_groups(base_dir=_data_dir()) |
| 10615 | except (OSError, ValueError) as exc: |
| 10616 | await _send_collection_names_error(send, headers, exc) |
| 10617 | return |
| 10618 | |
| 10619 | await _send_json( |
| 10620 | send, |
| 10621 | { |
| 10622 | "status": "ok", |
| 10623 | "collections": collections, |
| 10624 | "count": len(collections), |
| 10625 | # User objects (u_<id>_<name>) belong to no collection; they are |
| 10626 | # summarised per owner here instead. |
| 10627 | "user_objects": user_objects, |
| 10628 | }, |
| 10629 | ) |
| 10630 | |
| 10631 | |
| 10632 | async def _send_collection_names_error(send, headers: dict[str, str], exc: BaseException) -> None: |
| 10633 | """Which names are collections depends on the permission policy's rules. |
| 10634 | |
| 10635 | While the policy cannot be read the answer is a 503 permission_policy_unavailable |
| 10636 | (with error_detail for the admin token), never a guess that would make a |
| 10637 | collection quietly known or unknown. Any other failure stays a 500. |
| 10638 | """ |
| 10639 | error = _policy_read_error() |
| 10640 | if error is not None: |
| 10641 | await _send_policy_unavailable(send, headers, error) |
| 10642 | return |
| 10643 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 10644 | |
| 10645 | |
| 10646 | async def _send_if_collection_missing(send, collection: str, headers: dict[str, str]) -> bool: |
| 10647 | """True when the collection does not exist or cannot be checked; the answer is sent.""" |
| 10648 | try: |
| 10649 | object_collections.get_collection(collection, base_dir=_data_dir()) |
| 10650 | except object_collections.InvalidCollectionNameError as exc: |
| 10651 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10652 | except object_collections.CollectionNotFoundError as exc: |
| 10653 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 10654 | except (OSError, ValueError) as exc: |
| 10655 | await _send_collection_names_error(send, headers, exc) |
| 10656 | else: |
| 10657 | return False |
| 10658 | return True |
| 10659 | |
| 10660 | |
| 10661 | async def _handle_collection_get( |
| 10662 | send, |
| 10663 | method: str, |
| 10664 | collection: str, |
| 10665 | headers: dict[str, str], |
| 10666 | ) -> None: |
| 10667 | if method != "GET": |
| 10668 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10669 | return |
| 10670 | |
| 10671 | gate_error = _admin_token_gate_error( |
| 10672 | headers, |
| 10673 | f"Collection detail requires {ADMIN_TOKEN_ENV}.", |
| 10674 | ) |
| 10675 | if gate_error is not None: |
| 10676 | status, message = gate_error |
| 10677 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10678 | return |
| 10679 | |
| 10680 | try: |
| 10681 | summary = object_collections.get_collection(collection, base_dir=_data_dir()) |
| 10682 | except object_collections.InvalidCollectionNameError as exc: |
| 10683 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10684 | return |
| 10685 | except object_collections.CollectionNotFoundError as exc: |
| 10686 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 10687 | return |
| 10688 | except (OSError, ValueError) as exc: |
| 10689 | await _send_collection_names_error(send, headers, exc) |
| 10690 | return |
| 10691 | |
| 10692 | await _send_json( |
| 10693 | send, |
| 10694 | { |
| 10695 | "status": "ok", |
| 10696 | "collection": summary, |
| 10697 | }, |
| 10698 | ) |
| 10699 | |
| 10700 | |
| 10701 | async def _handle_collection_records( |
| 10702 | send, |
| 10703 | method: str, |
| 10704 | collection: str, |
| 10705 | query: dict[str, str], |
| 10706 | body: bytes, |
| 10707 | headers: dict[str, str], |
| 10708 | ) -> None: |
| 10709 | if method == "GET": |
| 10710 | await _handle_collection_records_get(send, collection, query, headers) |
| 10711 | return |
| 10712 | |
| 10713 | if method == "POST": |
| 10714 | await _handle_collection_record_create(send, collection, body, headers) |
| 10715 | return |
| 10716 | |
| 10717 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10718 | |
| 10719 | |
| 10720 | async def _handle_collection_records_get( |
| 10721 | send, |
| 10722 | collection: str, |
| 10723 | query: dict[str, str], |
| 10724 | headers: dict[str, str], |
| 10725 | ) -> None: |
| 10726 | # One reading of the clock for every decision this request makes: the |
| 10727 | # collection gate, the row filter, the field filter and the redaction. |
| 10728 | # Read per decision, a rule whose window closed mid-request let a row |
| 10729 | # through under the rule and then redacted it under no rule (nothing). |
| 10730 | now = datetime.now(timezone.utc) |
| 10731 | permission_check = None |
| 10732 | if _permission_checks_enabled(): |
| 10733 | permission_check = await _collection_permission_check( |
| 10734 | send, |
| 10735 | headers, |
| 10736 | object_permissions.READ, |
| 10737 | collection=collection, |
| 10738 | method="GET", |
| 10739 | now=now, |
| 10740 | ) |
| 10741 | if permission_check is None: |
| 10742 | return |
| 10743 | enforced = permission_check is not None and permission_check["enforced"] |
| 10744 | if not enforced and await _send_unenforced_gate_error( |
| 10745 | send, headers, f"Collection records require {ADMIN_TOKEN_ENV}." |
| 10746 | ): |
| 10747 | return |
| 10748 | |
| 10749 | row_read = None |
| 10750 | try: |
| 10751 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 10752 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 10753 | if enforced: |
| 10754 | # Every row, unless DBBASIC_ROW_FILTER_INDEX narrows the read to |
| 10755 | # the rows the subject could be allowed -- the row filter below |
| 10756 | # then runs on those. Same errors at the same point either way. |
| 10757 | row_read = _read_records_for_row_filter( |
| 10758 | collection, |
| 10759 | subject=permission_check["subject"], |
| 10760 | policy=permission_check["policy"], |
| 10761 | now=now, |
| 10762 | ) |
| 10763 | records = row_read.records |
| 10764 | else: |
| 10765 | records = object_records.read_collection_records(collection, base_dir=_data_dir()) |
| 10766 | except object_collections.InvalidCollectionNameError as exc: |
| 10767 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10768 | return |
| 10769 | except object_collections.CollectionNotFoundError as exc: |
| 10770 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 10771 | return |
| 10772 | except ValueError as exc: |
| 10773 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10774 | return |
| 10775 | |
| 10776 | # 58's field filter (plan/vocabulary/58-query-filter-spec.md). Parsed |
| 10777 | # here, against the schema now known-valid (the read above already |
| 10778 | # confirmed the collection exists), but APPLIED below only after the |
| 10779 | # permission row filter has already run -- see the ordering note there. |
| 10780 | normalized_where: dict[str, list[dict[str, Any]]] = {} |
| 10781 | if _filtering_enabled(): |
| 10782 | is_filterable = ( |
| 10783 | _filterable_field_predicate( |
| 10784 | collection, |
| 10785 | subject=permission_check["subject"], |
| 10786 | policy=permission_check["policy"], |
| 10787 | decision=permission_check["decision"], |
| 10788 | ) |
| 10789 | if enforced |
| 10790 | else _always_filterable |
| 10791 | ) |
| 10792 | try: |
| 10793 | normalized_where = _parse_collection_record_filters( |
| 10794 | query, |
| 10795 | collection=collection, |
| 10796 | is_filterable=is_filterable, |
| 10797 | ) |
| 10798 | except FilterParamError as exc: |
| 10799 | await _send_json( |
| 10800 | send, |
| 10801 | { |
| 10802 | "status": "error", |
| 10803 | "error": str(exc), |
| 10804 | "code": "invalid_filter", |
| 10805 | "param": exc.param, |
| 10806 | }, |
| 10807 | status=400, |
| 10808 | ) |
| 10809 | return |
| 10810 | elif any(key not in FILTER_RESERVED_PARAMS for key in query): |
| 10811 | _note_filtering_disabled_once() |
| 10812 | |
| 10813 | if enforced: |
| 10814 | try: |
| 10815 | # The permission row filter: applied first, unconditionally, |
| 10816 | # over every record read above. redact=False: field redaction |
| 10817 | # is deferred past the field filter below, so a filter on a |
| 10818 | # field an admin may filter but not see (schema-hidden) can |
| 10819 | # still match against its real value -- see |
| 10820 | # _filter_records_for_permission's docstring. |
| 10821 | records = _filter_records_for_row_read( |
| 10822 | row_read, |
| 10823 | collection=collection, |
| 10824 | subject=permission_check["subject"], |
| 10825 | policy=permission_check["policy"], |
| 10826 | redact=False, |
| 10827 | ) |
| 10828 | except ValueError as exc: |
| 10829 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 10830 | return |
| 10831 | |
| 10832 | if normalized_where: |
| 10833 | if enforced: |
| 10834 | # Which fields may be filtered on was decided above for the |
| 10835 | # collection as a whole; what a caller may see is decided per |
| 10836 | # row. A row whose filtered field this caller cannot read on |
| 10837 | # THAT row never matches, so the filter cannot tell them the |
| 10838 | # value the row's redaction hides. |
| 10839 | records = _rows_with_readable_fields( |
| 10840 | records, |
| 10841 | normalized_where.keys(), |
| 10842 | collection=collection, |
| 10843 | subject=permission_check["subject"], |
| 10844 | policy=permission_check["policy"], |
| 10845 | now=now, |
| 10846 | ) |
| 10847 | # The field filter: an ADDITIONAL AND over the row filter's own |
| 10848 | # output only (never the original `records`), which is what |
| 10849 | # structurally guarantees it can narrow the readable set but |
| 10850 | # never widen it -- see object_records.filter_records. |
| 10851 | records = object_records.filter_records(records, normalized_where) |
| 10852 | |
| 10853 | # 63: a `_rev` per row, computed HERE -- after the row filter (so it |
| 10854 | # only covers rows the caller may see) and BEFORE field redaction (so |
| 10855 | # it is taken over the full surfaced record the write-side precondition |
| 10856 | # will compare against). Getting that order wrong is the whole subtlety: |
| 10857 | # a rev computed over a trimmed row can never match update's, and every |
| 10858 | # If-Match built from a list would 409 forever. |
| 10859 | # |
| 10860 | # WHY THIS EXISTS. Without it a claiming agent had to GET each candidate |
| 10861 | # individually just to obtain a rev before it could claim safely -- an |
| 10862 | # extra round trip per attempt on the one path 63 was written for |
| 10863 | # ("claim becomes race-safe"). A list that hands back rows you cannot |
| 10864 | # act on without re-reading them is a list that made the caller do the |
| 10865 | # work twice. |
| 10866 | # |
| 10867 | # Only the WINDOW is hashed, never the whole filtered set: the cost is |
| 10868 | # one HMAC per returned row (<=1000, default 100), not per matching |
| 10869 | # row, so a narrow page over a large collection stays cheap. |
| 10870 | revs = None |
| 10871 | if _concurrency_enabled(): |
| 10872 | rev_dir = _data_dir() |
| 10873 | revs = { |
| 10874 | # Keyed, as the single-record read's: see client_record_rev. |
| 10875 | str(record["id"]): object_records.client_record_rev(collection, record, base_dir=rev_dir) |
| 10876 | for record in records[offset:offset + limit] |
| 10877 | if record.get("id") |
| 10878 | } |
| 10879 | |
| 10880 | if enforced: |
| 10881 | try: |
| 10882 | records = _redact_records_for_permission( |
| 10883 | records, |
| 10884 | collection=collection, |
| 10885 | subject=permission_check["subject"], |
| 10886 | policy=permission_check["policy"], |
| 10887 | now=now, |
| 10888 | ) |
| 10889 | except ValueError as exc: |
| 10890 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 10891 | return |
| 10892 | |
| 10893 | records_payload = object_records.collection_records_payload( |
| 10894 | collection, |
| 10895 | records, |
| 10896 | limit=limit, |
| 10897 | offset=offset, |
| 10898 | ) |
| 10899 | # A parallel MAP rather than a `_rev` on each row, because the record |
| 10900 | # shape is a contract: the single-record read documents `_rev` as |
| 10901 | # "sibling metadata, never merged into record fields (must never |
| 10902 | # collide with a schema field or appear on write-back)". Merging it |
| 10903 | # into rows here would break that rule in the one place records are |
| 10904 | # most likely to be echoed straight back into a write. |
| 10905 | if revs is not None: |
| 10906 | records_payload["revs"] = revs |
| 10907 | await _send_json(send, {"status": "ok", **records_payload}) |
| 10908 | |
| 10909 | |
| 10910 | async def _handle_collection_changes( |
| 10911 | send, |
| 10912 | method: str, |
| 10913 | collection: str, |
| 10914 | query: dict[str, str], |
| 10915 | headers: dict[str, str], |
| 10916 | ) -> None: |
| 10917 | if method != "GET": |
| 10918 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10919 | return |
| 10920 | |
| 10921 | gate_error = _admin_token_gate_error( |
| 10922 | headers, |
| 10923 | f"Collection change history requires {ADMIN_TOKEN_ENV}.", |
| 10924 | ) |
| 10925 | if gate_error is not None: |
| 10926 | status, message = gate_error |
| 10927 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10928 | return |
| 10929 | |
| 10930 | if await _send_if_collection_missing(send, collection, headers): |
| 10931 | return |
| 10932 | |
| 10933 | try: |
| 10934 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 10935 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 10936 | changes = object_record_changes.list_record_changes( |
| 10937 | collection, |
| 10938 | base_dir=_data_dir(), |
| 10939 | limit=limit, |
| 10940 | offset=offset, |
| 10941 | ) |
| 10942 | except object_collections.InvalidCollectionNameError as exc: |
| 10943 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10944 | return |
| 10945 | except object_collections.CollectionNotFoundError as exc: |
| 10946 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 10947 | return |
| 10948 | except ValueError as exc: |
| 10949 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10950 | return |
| 10951 | |
| 10952 | await _send_json(send, {"status": "ok", **changes}) |
| 10953 | |
| 10954 | |
| 10955 | async def _handle_collection_record_changes( |
| 10956 | send, |
| 10957 | method: str, |
| 10958 | collection: str, |
| 10959 | record_id: str, |
| 10960 | query: dict[str, str], |
| 10961 | headers: dict[str, str], |
| 10962 | ) -> None: |
| 10963 | if method != "GET": |
| 10964 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 10965 | return |
| 10966 | |
| 10967 | gate_error = _admin_token_gate_error( |
| 10968 | headers, |
| 10969 | f"Collection record change history requires {ADMIN_TOKEN_ENV}.", |
| 10970 | ) |
| 10971 | if gate_error is not None: |
| 10972 | status, message = gate_error |
| 10973 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 10974 | return |
| 10975 | |
| 10976 | if await _send_if_collection_missing(send, collection, headers): |
| 10977 | return |
| 10978 | |
| 10979 | try: |
| 10980 | limit = _query_int(query, "limit", default=100, minimum=1, maximum=1000) |
| 10981 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 10982 | changes = object_record_changes.list_record_changes( |
| 10983 | collection, |
| 10984 | record_id=record_id, |
| 10985 | base_dir=_data_dir(), |
| 10986 | limit=limit, |
| 10987 | offset=offset, |
| 10988 | ) |
| 10989 | except object_collections.InvalidCollectionNameError as exc: |
| 10990 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10991 | return |
| 10992 | except object_records.InvalidRecordIdError as exc: |
| 10993 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 10994 | return |
| 10995 | except object_collections.CollectionNotFoundError as exc: |
| 10996 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 10997 | return |
| 10998 | except ValueError as exc: |
| 10999 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 11000 | return |
| 11001 | |
| 11002 | await _send_json(send, {"status": "ok", **changes}) |
| 11003 | |
| 11004 | |
| 11005 | def _collection_has_owner_field(collection: str) -> bool: |
| 11006 | """True if the collection's schema declares an owner_id field. |
| 11007 | |
| 11008 | Used to decide whether a create should be stamped with the session's |
| 11009 | user as the owner. Schemaless or unknown collections return False (no |
| 11010 | field to stamp). |
| 11011 | """ |
| 11012 | try: |
| 11013 | schema = object_schemas.get_schema(collection, base_dir=_data_dir()) |
| 11014 | except Exception: |
| 11015 | return False |
| 11016 | return any(f.get("name") == "owner_id" for f in (schema.get("fields") or [])) |
| 11017 | |
| 11018 | |
| 11019 | _HOOK_METHOD = "BEFORE_WRITE" |
| 11020 | |
| 11021 | |
| 11022 | def _before_write_hook_id(collection: str) -> str | None: |
| 11023 | """The collection's declared pre-write hook object id, if any. |
| 11024 | |
| 11025 | Declared as `hooks: {"before_write": "<object_id>"}` at the schema root |
| 11026 | (whitelisted in object_schemas normalization; deliberately NOT exposed via |
| 11027 | /api/schema -- a server-side concern, never a client hint). Absent or |
| 11028 | blank -> no hook, and the write path pays one cached-schema dict lookup. |
| 11029 | """ |
| 11030 | try: |
| 11031 | schema = object_schemas.get_schema(collection, base_dir=_data_dir()) |
| 11032 | except (LookupError, OSError, ValueError): |
| 11033 | return None |
| 11034 | hooks = schema.get("hooks") |
| 11035 | if isinstance(hooks, dict): |
| 11036 | hook_id = hooks.get("before_write") |
| 11037 | if isinstance(hook_id, str) and hook_id.strip(): |
| 11038 | return hook_id.strip() |
| 11039 | return None |
| 11040 | |
| 11041 | |
| 11042 | def _hook_protected_fields(collection: str) -> set[str]: |
| 11043 | """Fields a hook transform may never change: identity/ownership plus every |
| 11044 | read-only/computed field. The hook has rejection power and transform power |
| 11045 | over ordinary fields only -- it cannot reassign a record or forge |
| 11046 | server-owned values.""" |
| 11047 | protected = {"id", "owner_id"} |
| 11048 | try: |
| 11049 | schema = object_schemas.get_schema(collection, base_dir=_data_dir()) |
| 11050 | except (LookupError, OSError, ValueError): |
| 11051 | return protected |
| 11052 | for field in schema.get("fields", []): |
| 11053 | if not isinstance(field, dict): |
| 11054 | continue |
| 11055 | field_type = str(field.get("type") or "").lower() |
| 11056 | if ( |
| 11057 | field.get("read_only") |
| 11058 | or field.get("readonly") |
| 11059 | or field.get("computed") |
| 11060 | or field_type == "computed" |
| 11061 | ): |
| 11062 | name = field.get("name") |
| 11063 | if name: |
| 11064 | protected.add(str(name)) |
| 11065 | return protected |
| 11066 | |
| 11067 | |
| 11068 | def _owner_value(value: Any) -> str: |
| 11069 | return "" if value is None else str(value).strip() |
| 11070 | |
| 11071 | |
| 11072 | async def _refuse_owner_change( |
| 11073 | send, |
| 11074 | headers: dict[str, str], |
| 11075 | *, |
| 11076 | collection: str, |
| 11077 | existing: dict[str, Any], |
| 11078 | changes: dict[str, Any], |
| 11079 | candidate: dict[str, Any], |
| 11080 | permission_check: dict[str, Any], |
| 11081 | now: datetime | None = None, |
| 11082 | ) -> bool: |
| 11083 | """Refuse an update that moves a record to another owner, unless the |
| 11084 | caller could have created it with that owner. True when a refusal has |
| 11085 | been sent. |
| 11086 | |
| 11087 | The create path refuses an owner_id naming somebody else unless an |
| 11088 | admin role or an `on_behalf` grant allows it (docs/permissions-model.md, |
| 11089 | "Who owns a record you create"). Update asked nothing of the kind: a |
| 11090 | role with an unconditional update grant (a billing manager on invoices, |
| 11091 | a manager on expenses or time logs, an assignee on a task) could PUT |
| 11092 | `owner_id` and hand the row to any user, who then read and edited it |
| 11093 | through the owner rules -- a client's bill given to a stranger. An |
| 11094 | owner's own row-filtered grant was never the hole: the rule is judged |
| 11095 | on the record as it would be, so it already refuses giving a row away. |
| 11096 | |
| 11097 | Changing owner_id now needs exactly what creating the row with the new |
| 11098 | owner_id needs, asked of the record as it would be: an admin role, or |
| 11099 | an allow with `on_behalf: true` covering create on this collection whose |
| 11100 | row filter matches. Taking a row for yourself is a change of owner too |
| 11101 | (the old owner loses it), so it is asked the same way. An owner_id sent |
| 11102 | unchanged is no change: an honest client PUTs the whole record back. |
| 11103 | Only under enforcement, and never for the admin token (an operator, as |
| 11104 | on create); in-process writers (actions, the daemon) do not come here. |
| 11105 | Asked whether or not the schema declares owner_id: the owner rules read |
| 11106 | the stored value either way. |
| 11107 | """ |
| 11108 | if not permission_check.get("enforced") or "owner_id" not in changes: |
| 11109 | return False |
| 11110 | if _owner_value(changes.get("owner_id")) == _owner_value(existing.get("owner_id")): |
| 11111 | return False |
| 11112 | if _request_is_operator(headers): |
| 11113 | return False |
| 11114 | try: |
| 11115 | decision = object_permissions.check_create_on_behalf( |
| 11116 | permission_check["subject"], |
| 11117 | policy=permission_check["policy"], |
| 11118 | collection=collection, |
| 11119 | record=candidate, |
| 11120 | now=now, |
| 11121 | ) |
| 11122 | except ValueError as exc: |
| 11123 | await _send_json( |
| 11124 | send, |
| 11125 | {"status": "error", "error": f"Permission policy is invalid: {exc}"}, |
| 11126 | status=500, |
| 11127 | ) |
| 11128 | return True |
| 11129 | if decision.allowed: |
| 11130 | return False |
| 11131 | await _send_json( |
| 11132 | send, |
| 11133 | { |
| 11134 | "status": "error", |
| 11135 | "error": ( |
| 11136 | "owner_id would move this record to another owner. Only an admin, or a " |
| 11137 | "role granted create with \"on_behalf\": true on this collection, may " |
| 11138 | "change who owns a record. Nothing was written." |
| 11139 | ), |
| 11140 | "code": "forbidden", |
| 11141 | "field": "owner_id", |
| 11142 | }, |
| 11143 | status=403, |
| 11144 | ) |
| 11145 | return True |
| 11146 | |
| 11147 | |
| 11148 | async def _refuse_unreachable_relations( |
| 11149 | send, |
| 11150 | *, |
| 11151 | collection: str, |
| 11152 | record: dict[str, Any], |
| 11153 | existing: dict[str, Any] | None, |
| 11154 | permission_check: dict[str, Any], |
| 11155 | ) -> bool: |
| 11156 | """Refuse a write that points a relation at a record the writer may not |
| 11157 | act on. True when a refusal has been sent. |
| 11158 | |
| 11159 | The rules decide who may write THIS row; until this check nothing asked |
| 11160 | whether the writer may touch the row it points at. A registered user's |
| 11161 | refund needed only its own owner_id to be theirs, so any signed-in user |
| 11162 | could refund any customer's payment (and record a payment against any |
| 11163 | invoice, a line on any order, a stock move on any product): the child |
| 11164 | is the writer's, the money it moves is someone else's. A relation that |
| 11165 | declares `requires` now has its target read under the same policy for |
| 11166 | the same subject, and the write goes ahead only if the engine would let |
| 11167 | that subject `read` it and, for `update`, `update` it -- the record API's |
| 11168 | answer for the target row, owner fallback included. |
| 11169 | |
| 11170 | Checked on create for every such relation with a value, and on update |
| 11171 | for each one whose value changes (a row may keep pointing where it was |
| 11172 | allowed to point). Only when enforcement is on: with it off, only the |
| 11173 | admin token gets in, and an admin is allowed by the engine anyway. |
| 11174 | Fails closed: a target that cannot be read is 503, a policy that cannot |
| 11175 | be evaluated 500. A target the writer may not even read is answered |
| 11176 | exactly like a missing one (the 400 relation validation gives), so this |
| 11177 | is no oracle for which ids exist. A missing target is left to that |
| 11178 | validation. |
| 11179 | |
| 11180 | Trusted server-side writers (actions, the daemon, webhooks) write |
| 11181 | through object_records and never reach this: an action that writes a |
| 11182 | row with a pointer it took from the request asks the same question |
| 11183 | through object_access.Access.relation_refusal, which is this check |
| 11184 | (docs/permissions-model.md, "Objects That Read Storage Directly"). |
| 11185 | """ |
| 11186 | if not permission_check.get("enforced"): |
| 11187 | return False |
| 11188 | refusal = object_access.relation_refusal( |
| 11189 | collection, |
| 11190 | record, |
| 11191 | subject=permission_check["subject"], |
| 11192 | policy=permission_check["policy"], |
| 11193 | base_dir=_data_dir(), |
| 11194 | existing=existing, |
| 11195 | ) |
| 11196 | if refusal is None: |
| 11197 | return False |
| 11198 | status, body = refusal |
| 11199 | await _send_json(send, body, status=status) |
| 11200 | return True |
| 11201 | |
| 11202 | |
| 11203 | async def _apply_before_write_hook( |
| 11204 | send, |
| 11205 | headers: dict[str, str], |
| 11206 | *, |
| 11207 | collection: str, |
| 11208 | action: str, |
| 11209 | record: dict[str, Any], |
| 11210 | existing: dict[str, Any] | None, |
| 11211 | changes: dict[str, Any], |
| 11212 | ) -> dict[str, Any] | None: |
| 11213 | """Run the collection's pre-write hook and return the record to persist. |
| 11214 | |
| 11215 | Returns None when a response has already been sent (the hook rejected the |
| 11216 | write, or the hook itself failed). The contract |
| 11217 | (plan/pre-write-hook-spec.md): the hook object's BEFORE_WRITE(request) |
| 11218 | receives {collection, action, record, existing, changes, subject} and |
| 11219 | returns None/{} to allow, {"error", "status"?} to reject (4xx, or 503 |
| 11220 | for a read it could not make; its own message), or {"record": {...}} to transform. |
| 11221 | |
| 11222 | `action` is "create", "update" or "delete": |
| 11223 | - create: `record` is the row to be written, `existing` is None, |
| 11224 | `changes` is the same row. |
| 11225 | - update: `existing` is the stored row before this write, `record` is |
| 11226 | that row with the caller's changes applied, `changes` is only what |
| 11227 | the caller sent. |
| 11228 | - delete: `existing` is the row about to go, `record` is the same row |
| 11229 | (the row being acted on, as the permission check sees it), `changes` |
| 11230 | is {}. A hook may allow or reject a delete. It may NOT transform |
| 11231 | one: there is nothing to persist, so {"record": ...} in answer to a |
| 11232 | delete means the hook decided about some other question, and is |
| 11233 | treated like any other non-contract answer (500, nothing deleted). |
| 11234 | Before deletes reached hooks at all, a rule such as "approved time |
| 11235 | is frozen" held against an edit and not against removing the row. |
| 11236 | |
| 11237 | `existing` (and so `record` on update and delete) is read BEFORE the |
| 11238 | write lock, so a hook's check is advisory against a concurrent writer. |
| 11239 | "This value appears once" is a schema `unique` constraint and "this |
| 11240 | record is settled" a schema `locked_when` rule; object_records |
| 11241 | enforces both inside the lock. |
| 11242 | |
| 11243 | Ordering and safety: |
| 11244 | - Runs AFTER permission/field checks -- a denied subject never reaches the |
| 11245 | hook, so a hook side effect can't leak that a write was attempted. |
| 11246 | - Fails CLOSED: declared-but-missing, raising, or non-contract hooks |
| 11247 | reject the write with 500 -- a validation gate that silently passes on |
| 11248 | error is not a gate. |
| 11249 | - Transforms cannot touch id/owner_id/read-only/computed fields |
| 11250 | (_hook_protected_fields), and the transformed record still goes through |
| 11251 | full schema validation in the persist call. |
| 11252 | - Executes in-process through the same path as any object |
| 11253 | (object_execution.execute_object + the execution log), so hook runs are |
| 11254 | observable like every other object run. Trusted server-side writers |
| 11255 | (daemon, migrations, seed-merge) call object_records directly and bypass |
| 11256 | hooks deliberately -- hooks gate the public write surface. |
| 11257 | """ |
| 11258 | hook_id = _before_write_hook_id(collection) |
| 11259 | if hook_id is None: |
| 11260 | return record |
| 11261 | |
| 11262 | subject = _permission_subject(headers) |
| 11263 | payload = { |
| 11264 | "collection": collection, |
| 11265 | "action": action, |
| 11266 | "record": dict(record), |
| 11267 | "existing": dict(existing) if existing is not None else None, |
| 11268 | "changes": dict(changes), |
| 11269 | "subject": {"user_id": subject.user_id, "roles": list(subject.roles or ())}, |
| 11270 | } |
| 11271 | execution_request = object_execution.ObjectExecutionRequest( |
| 11272 | object_id=hook_id, |
| 11273 | method=_HOOK_METHOD, |
| 11274 | payload=payload, |
| 11275 | correlation_id=object_correlation.current_correlation_id(), |
| 11276 | ) |
| 11277 | try: |
| 11278 | result = object_execution.execute_object(_runtime, execution_request) |
| 11279 | _append_execution_log(result) |
| 11280 | except Exception: |
| 11281 | result = None |
| 11282 | |
| 11283 | async def _fail() -> None: |
| 11284 | await _send_json( |
| 11285 | send, |
| 11286 | { |
| 11287 | "status": "error", |
| 11288 | "error": f"Pre-write hook failed: {hook_id}", |
| 11289 | "code": "hook_failed", |
| 11290 | }, |
| 11291 | status=500, |
| 11292 | ) |
| 11293 | |
| 11294 | if result is None or not result.ok: |
| 11295 | await _fail() |
| 11296 | return None |
| 11297 | outcome = result.result |
| 11298 | if outcome is None or outcome == {}: |
| 11299 | return record |
| 11300 | if not isinstance(outcome, dict): |
| 11301 | await _fail() |
| 11302 | return None |
| 11303 | error_message = outcome.get("error") |
| 11304 | if error_message: |
| 11305 | try: |
| 11306 | status = int(outcome.get("status") or 400) |
| 11307 | except (TypeError, ValueError): |
| 11308 | status = 400 |
| 11309 | # A refusal is a 4xx, or a 503 for "I could not read what I gate on" |
| 11310 | # (validation-and-logic.md): the client should retry that, not fix |
| 11311 | # its input. Nothing else is relayed -- a hook does not get to say |
| 11312 | # 200, 3xx or 500 for a write it refused. |
| 11313 | if not (400 <= status <= 499 or status == 503): |
| 11314 | status = 400 |
| 11315 | await _send_json( |
| 11316 | send, |
| 11317 | {"status": "error", "error": str(error_message), "code": "hook_rejected"}, |
| 11318 | status=status, |
| 11319 | ) |
| 11320 | return None |
| 11321 | transformed = outcome.get("record") |
| 11322 | if transformed is None: |
| 11323 | return record |
| 11324 | if action == "delete" or not isinstance(transformed, dict): |
| 11325 | await _fail() |
| 11326 | return None |
| 11327 | final = dict(transformed) |
| 11328 | for name in _hook_protected_fields(collection): |
| 11329 | if name in record: |
| 11330 | final[name] = record[name] |
| 11331 | else: |
| 11332 | final.pop(name, None) |
| 11333 | return final |
| 11334 | |
| 11335 | |
| 11336 | async def _delete_allowed_by_hook( |
| 11337 | send, |
| 11338 | headers: dict[str, str], |
| 11339 | *, |
| 11340 | collection: str, |
| 11341 | existing: dict[str, Any], |
| 11342 | ) -> bool: |
| 11343 | """Ask the collection's pre-write hook about a delete (already |
| 11344 | permission-checked). False when a response has been sent: the hook |
| 11345 | refused, failed, or answered with a transform. |
| 11346 | |
| 11347 | One function so that every surface that deletes a record on a caller's |
| 11348 | behalf (the collection route, /api/files, WebDAV) asks the same way. |
| 11349 | """ |
| 11350 | hooked = await _apply_before_write_hook( |
| 11351 | send, |
| 11352 | headers, |
| 11353 | collection=collection, |
| 11354 | action="delete", |
| 11355 | record=existing, |
| 11356 | existing=existing, |
| 11357 | changes={}, |
| 11358 | ) |
| 11359 | return hooked is not None |
| 11360 | |
| 11361 | |
| 11362 | async def _handle_collection_record_create( |
| 11363 | send, |
| 11364 | collection: str, |
| 11365 | body: bytes, |
| 11366 | headers: dict[str, str], |
| 11367 | ) -> None: |
| 11368 | outcome = await _gated_create( |
| 11369 | headers, |
| 11370 | collection=collection, |
| 11371 | parse=lambda: _record_payload_from_body(body, require_id=True), |
| 11372 | now=datetime.now(timezone.utc), |
| 11373 | ) |
| 11374 | if isinstance(outcome, _WriteRefusal): |
| 11375 | await outcome.replay(send) |
| 11376 | return |
| 11377 | await _send_json( |
| 11378 | send, |
| 11379 | { |
| 11380 | "status": "ok", |
| 11381 | "collection": collection, |
| 11382 | "record": outcome.answer, |
| 11383 | }, |
| 11384 | status=201, |
| 11385 | ) |
| 11386 | |
| 11387 | |
| 11388 | async def _handle_collection_record( |
| 11389 | send, |
| 11390 | method: str, |
| 11391 | collection: str, |
| 11392 | record_id: str, |
| 11393 | body: bytes, |
| 11394 | headers: dict[str, str], |
| 11395 | ) -> None: |
| 11396 | if method == "GET": |
| 11397 | await _handle_collection_record_get(send, collection, record_id, headers) |
| 11398 | return |
| 11399 | |
| 11400 | if method == "PUT": |
| 11401 | await _handle_collection_record_update(send, collection, record_id, body, headers) |
| 11402 | return |
| 11403 | |
| 11404 | if method == "DELETE": |
| 11405 | await _handle_collection_record_delete(send, collection, record_id, headers) |
| 11406 | return |
| 11407 | |
| 11408 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 11409 | |
| 11410 | |
| 11411 | async def _handle_collection_record_get( |
| 11412 | send, |
| 11413 | collection: str, |
| 11414 | record_id: str, |
| 11415 | headers: dict[str, str], |
| 11416 | ) -> None: |
| 11417 | if not _permission_enforcement_enabled(): |
| 11418 | # Off and audit alike (see _send_unenforced_gate_error); audit mode |
| 11419 | # still logs the decision for the callers who pass. |
| 11420 | gate_error = _admin_token_gate_error( |
| 11421 | headers, |
| 11422 | f"Collection record detail requires {ADMIN_TOKEN_ENV}.", |
| 11423 | ) |
| 11424 | if gate_error is not None: |
| 11425 | status, message = gate_error |
| 11426 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 11427 | return |
| 11428 | else: |
| 11429 | # Decide at the collection level before looking the record up, as the |
| 11430 | # write routes do (_record_write_denied_before_lookup). Looking it up |
| 11431 | # first answered 403 for an id that exists and 404 for one that does |
| 11432 | # not, to callers who may read neither; with a broken policy, a |
| 11433 | # collection with no schema file even answered the parse error as a 400. |
| 11434 | if await _collection_permission_check( |
| 11435 | send, headers, object_permissions.READ, collection=collection, method="GET" |
| 11436 | ) is None: |
| 11437 | return |
| 11438 | |
| 11439 | try: |
| 11440 | record = object_records.get_collection_record( |
| 11441 | collection, |
| 11442 | record_id, |
| 11443 | base_dir=_data_dir(), |
| 11444 | ) |
| 11445 | except object_collections.InvalidCollectionNameError as exc: |
| 11446 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 11447 | return |
| 11448 | except object_records.InvalidRecordIdError as exc: |
| 11449 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 11450 | return |
| 11451 | except (object_collections.CollectionNotFoundError, object_records.RecordNotFoundError) as exc: |
| 11452 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 11453 | return |
| 11454 | except ValueError as exc: |
| 11455 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 11456 | return |
| 11457 | |
| 11458 | # 63: fingerprint the FULL stored record, before any field-visibility |
| 11459 | # policy trims it -- the write-side precondition (update_collection_record, |
| 11460 | # inside the lock) compares against the full surfaced row, so the token |
| 11461 | # a caller reads here must be computed over the same full record for the |
| 11462 | # two to agree. A caller who can't see a field still gets a `_rev` that |
| 11463 | # depends on it, which only ever fails CLOSED (a hidden-field change 409s |
| 11464 | # them conservatively). It is KEYED (client_record_rev): an unkeyed hash |
| 11465 | # of the full row let a caller who sees every other field hash each |
| 11466 | # candidate value of a hidden one and compare. |
| 11467 | rev = object_records.client_record_rev(collection, record, base_dir=_data_dir()) |
| 11468 | |
| 11469 | if _permission_checks_enabled(): |
| 11470 | permission_check = await _collection_permission_check( |
| 11471 | send, |
| 11472 | headers, |
| 11473 | object_permissions.READ, |
| 11474 | collection=collection, |
| 11475 | method="GET", |
| 11476 | record=record, |
| 11477 | # A row the caller may not read answers like a missing one. |
| 11478 | deny_as_not_found=f"Record not found: {collection}/{record_id}", |
| 11479 | ) |
| 11480 | if permission_check is None: |
| 11481 | return |
| 11482 | if permission_check["enforced"]: |
| 11483 | try: |
| 11484 | record = _apply_record_field_policy( |
| 11485 | record, |
| 11486 | permission_check["decision"], |
| 11487 | collection=collection, |
| 11488 | subject=permission_check["subject"], |
| 11489 | policy=permission_check["policy"], |
| 11490 | ) |
| 11491 | except ValueError as exc: |
| 11492 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 11493 | return |
| 11494 | |
| 11495 | await _send_json( |
| 11496 | send, |
| 11497 | { |
| 11498 | "status": "ok", |
| 11499 | "collection": collection, |
| 11500 | "record": record, |
| 11501 | # Sibling metadata, never merged into record fields (must never |
| 11502 | # collide with a schema field or appear on write-back). |
| 11503 | object_records.REV_FIELD: rev, |
| 11504 | }, |
| 11505 | ) |
| 11506 | |
| 11507 | |
| 11508 | async def _handle_collection_record_update( |
| 11509 | send, |
| 11510 | collection: str, |
| 11511 | record_id: str, |
| 11512 | body: bytes, |
| 11513 | headers: dict[str, str], |
| 11514 | ) -> None: |
| 11515 | def parse() -> tuple[dict[str, Any], str | None]: |
| 11516 | changes = _record_payload_from_body(body) |
| 11517 | # 63: the optimistic-concurrency precondition. HTTP callers send it |
| 11518 | # as an `If-Match` header; the MCP bridge (no header channel) sends |
| 11519 | # it as a reserved `expected_rev` body key. Both are stripped here so |
| 11520 | # neither -- nor a `_rev` a client round-tripped back from a |
| 11521 | # full-record read -- is ever treated as a field write. Header wins |
| 11522 | # if both are present. |
| 11523 | expected_rev = headers.get("if-match") |
| 11524 | body_expected = changes.pop("expected_rev", None) |
| 11525 | changes.pop(object_records.REV_FIELD, None) |
| 11526 | if expected_rev is None and isinstance(body_expected, str): |
| 11527 | expected_rev = body_expected |
| 11528 | if expected_rev is not None: |
| 11529 | expected_rev = expected_rev.strip() or None |
| 11530 | return changes, expected_rev |
| 11531 | |
| 11532 | outcome = await _gated_update( |
| 11533 | headers, |
| 11534 | collection=collection, |
| 11535 | record_id=record_id, |
| 11536 | parse=parse, |
| 11537 | now=datetime.now(timezone.utc), |
| 11538 | ) |
| 11539 | if isinstance(outcome, _WriteRefusal): |
| 11540 | await outcome.replay(send) |
| 11541 | return |
| 11542 | |
| 11543 | payload: dict[str, Any] = { |
| 11544 | "status": "ok", |
| 11545 | "collection": collection, |
| 11546 | "record": outcome.answer, |
| 11547 | } |
| 11548 | if outcome.readable: |
| 11549 | # 63: the new fingerprint after this write -- a caller doing a |
| 11550 | # read-modify-write loop uses it as the If-Match for its next PUT |
| 11551 | # without a separate GET round-trip. Over the full stored row, as a |
| 11552 | # GET computes it; left out when a GET would not answer at all. |
| 11553 | payload[object_records.REV_FIELD] = object_records.client_record_rev( |
| 11554 | collection, outcome.record, base_dir=_data_dir()) |
| 11555 | await _send_json(send, payload) |
| 11556 | |
| 11557 | |
| 11558 | # --------------------------------------------------------------------------- |
| 11559 | # The write path: one gated function per operation (_gated_create, |
| 11560 | # _gated_update, _gated_delete) that every network route creating, updating |
| 11561 | # or deleting a collection record calls. Each runs the steps of |
| 11562 | # docs/dron-write-semantics.md for its operation, in the order stated there, |
| 11563 | # and returns either a _WriteRefusal (the answer, never written) or a |
| 11564 | # _WriteDone (the stored row and the row as this caller may read it). A |
| 11565 | # route parses its request, calls one of them and formats the answer; none |
| 11566 | # calls object_records' writers itself (tests/test_write_path_guard.py). |
| 11567 | # |
| 11568 | # A route that must ask a step earlier than the function would, because it |
| 11569 | # has its own steps in between (WebDAV looks a file up by name, checks its |
| 11570 | # preconditions and quota), asks it through the same helper and says so |
| 11571 | # (collection_asked=True, row_asked=True). Where routes differ for no reason |
| 11572 | # of their own and making them agree would change an answer, the difference |
| 11573 | # is kept and marked "kept difference" below. |
| 11574 | # --------------------------------------------------------------------------- |
| 11575 | |
| 11576 | |
| 11577 | class _WriteRefusal(_HeldResponse): |
| 11578 | """A refused write, as its route answers it. |
| 11579 | |
| 11580 | The gate helpers answer through a `send`; this is the `send` the gated |
| 11581 | functions hand them, so a refusal is exactly the response the route |
| 11582 | used to send itself: `status`, `headers` and the JSON body, whose |
| 11583 | `error`, `code` and other keys `payload` gives. `exc` is the storage |
| 11584 | exception behind a refusal from the write itself (None for a gate's). |
| 11585 | Nothing was written when one is returned (S60). |
| 11586 | """ |
| 11587 | |
| 11588 | def __init__(self) -> None: |
| 11589 | super().__init__() |
| 11590 | self.exc: BaseException | None = None |
| 11591 | |
| 11592 | @property |
| 11593 | def payload(self) -> dict[str, Any]: |
| 11594 | return json.loads(self.body or b"{}") |
| 11595 | |
| 11596 | |
| 11597 | @dataclasses.dataclass |
| 11598 | class _WriteDone: |
| 11599 | """A write that landed: the stored row (for a delete, the row removed) |
| 11600 | and, when the route asked for it, the row as this caller's GET would |
| 11601 | show it (_record_for_write_answer).""" |
| 11602 | |
| 11603 | record: dict[str, Any] |
| 11604 | answer: dict[str, Any] | None = None |
| 11605 | readable: bool = False |
| 11606 | |
| 11607 | |
| 11608 | def _plain_refusal(status: int): |
| 11609 | return lambda exc: (status, {"status": "error", "error": str(exc)}) |
| 11610 | |
| 11611 | |
| 11612 | def _conflict_refusal(exc): |
| 11613 | # 63: the record changed since the caller read it -- no write, no side |
| 11614 | # effects. The caller re-GETs to see current state (and its new `_rev`) |
| 11615 | # and retries; the server does not echo the current row here. Also |
| 11616 | # RecordChangedError: changed since THIS request's gates read it (S52). |
| 11617 | return 409, {"status": "error", "error": str(exc), "code": "conflict"} |
| 11618 | |
| 11619 | |
| 11620 | def _unique_refusal(exc): |
| 11621 | # Names the constraint, never the id of the row holding the key (S43). |
| 11622 | return 409, {"status": "error", "error": str(exc), "code": "unique_violation", |
| 11623 | "fields": exc.fields, "scope": exc.scope} |
| 11624 | |
| 11625 | |
| 11626 | def _check_refusal(exc): |
| 11627 | # A schema `locked_checks` entry refused (409 check_refused, or the 4xx |
| 11628 | # the check chose), could not decide (503 check_unavailable: retry), or |
| 11629 | # broke its contract (500 check_failed). The message is the check's own. |
| 11630 | return exc.status, {"status": "error", "error": str(exc), "code": exc.code, "check": exc.check} |
| 11631 | |
| 11632 | |
| 11633 | def _locked_refusal(exc): |
| 11634 | # `fields`: the frozen fields the update tried to change (empty for a delete). |
| 11635 | return 409, {"status": "error", "error": str(exc), "code": "record_locked", "fields": exc.fields} |
| 11636 | |
| 11637 | |
| 11638 | def _storage_failure(verb: str): |
| 11639 | return lambda exc: (500, {"status": "error", "error": f"Could not {verb} collection record: {exc}"}) |
| 11640 | |
| 11641 | |
| 11642 | # What the record API answers for each exception a write raises (S61), in |
| 11643 | # the order they are tried. An exception no entry names is not caught. |
| 11644 | _CREATE_STORAGE_ANSWERS: tuple = ( |
| 11645 | (object_collections.InvalidCollectionNameError, _plain_refusal(400)), |
| 11646 | (object_collections.CollectionNotFoundError, _plain_refusal(404)), |
| 11647 | (object_records.DuplicateRecordIdError, _plain_refusal(409)), |
| 11648 | (object_records.UniqueConstraintError, _unique_refusal), |
| 11649 | (object_records.CheckRefusedError, _check_refusal), |
| 11650 | ((object_records.InvalidRecordIdError, object_records.InvalidRecordPayloadError), _plain_refusal(400)), |
| 11651 | (ValueError, _plain_refusal(400)), |
| 11652 | (OSError, _storage_failure("save")), |
| 11653 | ) |
| 11654 | _UPDATE_STORAGE_ANSWERS: tuple = ( |
| 11655 | (object_records.RecordNotFoundError, _plain_refusal(404)), |
| 11656 | (object_records.VersionConflictError, _conflict_refusal), |
| 11657 | (object_records.UniqueConstraintError, _unique_refusal), |
| 11658 | (object_records.CheckRefusedError, _check_refusal), |
| 11659 | (object_records.RecordLockedError, _locked_refusal), |
| 11660 | (object_records.TransitionNotAllowedError, |
| 11661 | lambda exc: (403, {"status": "error", "error": str(exc), "code": "forbidden"})), |
| 11662 | ((object_records.InvalidRecordIdError, object_records.InvalidRecordPayloadError), _plain_refusal(400)), |
| 11663 | (ValueError, _plain_refusal(400)), |
| 11664 | (OSError, _storage_failure("save")), |
| 11665 | ) |
| 11666 | _DELETE_STORAGE_ANSWERS: tuple = ( |
| 11667 | (object_records.RecordNotFoundError, _plain_refusal(404)), |
| 11668 | (object_records.VersionConflictError, _conflict_refusal), |
| 11669 | (object_records.RecordLockedError, _locked_refusal), |
| 11670 | (object_records.CheckRefusedError, _check_refusal), |
| 11671 | (object_records.InvalidRecordIdError, _plain_refusal(400)), |
| 11672 | (ValueError, _plain_refusal(400)), |
| 11673 | (OSError, _storage_failure("delete")), |
| 11674 | ) |
| 11675 | |
| 11676 | |
| 11677 | async def _storage_write( |
| 11678 | out: _WriteRefusal, |
| 11679 | answers: tuple, |
| 11680 | write: Callable[[], dict[str, Any]], |
| 11681 | ) -> dict[str, Any] | None: |
| 11682 | """Run one object_records write; on an exception `answers` names, put |
| 11683 | its answer in `out` and return None. Any other exception propagates. A |
| 11684 | route's own answers come first in `answers` (see _remove_user_file).""" |
| 11685 | try: |
| 11686 | return write() |
| 11687 | except Exception as exc: |
| 11688 | for types, answer in answers: |
| 11689 | if isinstance(exc, types): |
| 11690 | if answer is None: |
| 11691 | raise |
| 11692 | out.exc = exc |
| 11693 | status, body = answer(exc) |
| 11694 | await _send_json(out, body, status=status) |
| 11695 | return None |
| 11696 | raise |
| 11697 | |
| 11698 | |
| 11699 | async def _write_landed( |
| 11700 | headers: dict[str, str], |
| 11701 | *, |
| 11702 | collection: str, |
| 11703 | record_id: str, |
| 11704 | record: dict[str, Any], |
| 11705 | now: datetime, |
| 11706 | publish: bool, |
| 11707 | shape_answer: bool, |
| 11708 | ) -> _WriteDone: |
| 11709 | """What follows a write that landed: the change event, and the row as |
| 11710 | this caller may read it (never the stored row itself: |
| 11711 | docs/http-api-contract.md, "Write answers").""" |
| 11712 | if publish: |
| 11713 | # object_records already durably appended the attributed change |
| 11714 | # (universal attribution); this only re-reads it so realtime/handler/ |
| 11715 | # event-bus fan-out can use the real persisted change_id/timestamp. |
| 11716 | # A read failure here is not fatal -- the change itself is already |
| 11717 | # safely on disk -- so it only costs this one best-effort publish. |
| 11718 | change = _record_change_for_publish(collection, record_id) |
| 11719 | if change is not None: |
| 11720 | _publish_record_change_event(change, record=record) |
| 11721 | if not shape_answer: |
| 11722 | return _WriteDone(record) |
| 11723 | answer, readable = _record_for_write_answer(record, headers, collection=collection, now=now) |
| 11724 | return _WriteDone(record, answer, readable) |
| 11725 | |
| 11726 | |
| 11727 | async def _gated_create( |
| 11728 | headers: dict[str, str], |
| 11729 | *, |
| 11730 | collection: str, |
| 11731 | now: datetime, |
| 11732 | values: dict[str, Any] | None = None, |
| 11733 | parse: Callable[[], dict[str, Any]] | None = None, |
| 11734 | sent_fields: list[str] | None = None, |
| 11735 | publish: bool = True, |
| 11736 | shape_answer: bool = True, |
| 11737 | storage_answers: tuple = (), |
| 11738 | ) -> "_WriteRefusal | _WriteDone": |
| 11739 | """A create of one record, steps 1-12 of docs/dron-write-semantics.md. |
| 11740 | |
| 11741 | The record is `values`, or what `parse` returns from the request body |
| 11742 | at step 1, before any permission question (S10, an open question): a |
| 11743 | ValueError it raises is the 400. `sent_fields` are the keys the client |
| 11744 | chose, which field permissions are asked about (S14); by default every |
| 11745 | key of the record as sent, before step 2 stamps an owner. A route that |
| 11746 | composes the record itself (a file upload) names the keys it filled on |
| 11747 | the caller's behalf. `storage_answers` come before the record API's |
| 11748 | answers to a storage exception (S61). |
| 11749 | """ |
| 11750 | out = _WriteRefusal() |
| 11751 | # 1: parse. |
| 11752 | if parse is not None: |
| 11753 | try: |
| 11754 | values = parse() |
| 11755 | except ValueError as exc: |
| 11756 | await _send_json(out, {"status": "error", "error": str(exc)}, status=400) |
| 11757 | return out |
| 11758 | assert values is not None |
| 11759 | record_payload = values |
| 11760 | |
| 11761 | # 2: ownership on create (docs/permissions-model.md, "Who owns a record |
| 11762 | # you create"). For a person signed in (a session or one of their API |
| 11763 | # keys) on a collection that declares owner_id: |
| 11764 | # |
| 11765 | # - owner_id omitted or blank: the row is the caller's, stamped HERE, |
| 11766 | # before the permission check, so a rule filtered on |
| 11767 | # `owner_id: $user_id` judges the row the caller will actually own. |
| 11768 | # Stamped after the check (as it was), the same create was refused |
| 11769 | # with "no matching role rule" -- the rule was asked about a row with |
| 11770 | # no owner -- while the docs told authors to send their own id. |
| 11771 | # - owner_id names the caller: unchanged. |
| 11772 | # - owner_id names somebody else: kept exactly as sent and refused, |
| 11773 | # unless an `on_behalf` rule (or an admin role) lets this caller enter |
| 11774 | # records for others -- step 4. It used to be overwritten with the |
| 11775 | # caller's id and answered 201, so a treasurer recording a donor's |
| 11776 | # donation was told it worked and the donor never owned it. A server |
| 11777 | # never silently changes a value the client sent. |
| 11778 | # |
| 11779 | # The admin token is not a person (_signed_in_user_id is None): seeding |
| 11780 | # and migration set owner_id deliberately and it is kept as sent. |
| 11781 | owner = _signed_in_user_id(headers) |
| 11782 | owned_collection = bool(owner) and _collection_has_owner_field(collection) |
| 11783 | if sent_fields is None: |
| 11784 | sent_fields = list(record_payload.keys()) |
| 11785 | if owned_collection and str(record_payload.get("owner_id") or "").strip() == "": |
| 11786 | record_payload = {**record_payload, "owner_id": owner} |
| 11787 | |
| 11788 | # 3: permission to create the record as sent. |
| 11789 | permission_check = await _authorize_collection_write( |
| 11790 | out, |
| 11791 | headers, |
| 11792 | object_permissions.CREATE, |
| 11793 | collection=collection, |
| 11794 | method="POST", |
| 11795 | record=record_payload, |
| 11796 | gate_message=f"Collection record writes require {ADMIN_TOKEN_ENV}.", |
| 11797 | now=now, |
| 11798 | ) |
| 11799 | if permission_check is None: |
| 11800 | return out |
| 11801 | |
| 11802 | # 4: an owner_id naming someone else (S13). |
| 11803 | if owned_collection and str(record_payload.get("owner_id")) != owner: |
| 11804 | try: |
| 11805 | on_behalf = object_permissions.check_create_on_behalf( |
| 11806 | permission_check["subject"], |
| 11807 | policy=permission_check["policy"] if permission_check["enforced"] else None, |
| 11808 | collection=collection, |
| 11809 | record=record_payload, |
| 11810 | now=now, |
| 11811 | ) |
| 11812 | except ValueError as exc: |
| 11813 | await _send_json( |
| 11814 | out, |
| 11815 | {"status": "error", "error": f"Permission policy is invalid: {exc}"}, |
| 11816 | status=500, |
| 11817 | ) |
| 11818 | return out |
| 11819 | if not on_behalf.allowed: |
| 11820 | await _send_json( |
| 11821 | out, |
| 11822 | { |
| 11823 | "status": "error", |
| 11824 | "error": ( |
| 11825 | "owner_id names another user. A record you create is yours: " |
| 11826 | "leave owner_id out (or send your own id) to own it, or have " |
| 11827 | "your role granted create with \"on_behalf\": true to enter " |
| 11828 | "records for others. Nothing was written." |
| 11829 | ), |
| 11830 | "code": "forbidden", |
| 11831 | "field": "owner_id", |
| 11832 | }, |
| 11833 | status=403, |
| 11834 | ) |
| 11835 | return out |
| 11836 | |
| 11837 | # 5: field permissions on what the client sent: an owner_id stamped at |
| 11838 | # step 2 is the server's write, and a schema that makes owner_id |
| 11839 | # server-only (thread_comments) must not refuse it. |
| 11840 | if permission_check["enforced"] and await _refuse_denied_fields( |
| 11841 | out, collection, sent_fields, permission_check=permission_check, record=record_payload |
| 11842 | ): |
| 11843 | return out |
| 11844 | |
| 11845 | # 6: relation.requires on every pointer with a value (S15). |
| 11846 | if await _refuse_unreachable_relations( |
| 11847 | out, |
| 11848 | collection=collection, |
| 11849 | record=record_payload, |
| 11850 | existing=None, |
| 11851 | permission_check=permission_check, |
| 11852 | ): |
| 11853 | return out |
| 11854 | |
| 11855 | # 7: the package's pre-write hook (S16, S19). |
| 11856 | hooked = await _apply_before_write_hook( |
| 11857 | out, |
| 11858 | headers, |
| 11859 | collection=collection, |
| 11860 | action="create", |
| 11861 | record=record_payload, |
| 11862 | existing=None, |
| 11863 | changes=record_payload, |
| 11864 | ) |
| 11865 | if hooked is None: |
| 11866 | return out |
| 11867 | |
| 11868 | # 8-12: storage; the duplicate id, `unique` and `locked_checks` under its lock. |
| 11869 | record = await _storage_write( |
| 11870 | out, |
| 11871 | storage_answers + _CREATE_STORAGE_ANSWERS, |
| 11872 | lambda: object_records.create_collection_record( |
| 11873 | collection, |
| 11874 | hooked, |
| 11875 | base_dir=_data_dir(), |
| 11876 | actor=_record_change_actor(headers), |
| 11877 | ), |
| 11878 | ) |
| 11879 | if record is None: |
| 11880 | return out |
| 11881 | return await _write_landed( |
| 11882 | headers, collection=collection, record_id=record["id"], record=record, now=now, |
| 11883 | publish=publish, shape_answer=shape_answer, |
| 11884 | ) |
| 11885 | |
| 11886 | |
| 11887 | async def _gated_update( |
| 11888 | headers: dict[str, str], |
| 11889 | *, |
| 11890 | collection: str, |
| 11891 | record_id: str, |
| 11892 | now: datetime, |
| 11893 | changes: dict[str, Any] | None = None, |
| 11894 | client_rev: str | None = None, |
| 11895 | parse: Callable[[], tuple[dict[str, Any], str | None]] | None = None, |
| 11896 | existing: dict[str, Any] | None = None, |
| 11897 | collection_asked: bool = False, |
| 11898 | publish: bool = True, |
| 11899 | shape_answer: bool = True, |
| 11900 | ) -> "_WriteRefusal | _WriteDone": |
| 11901 | """An update of one record, steps U1-U18 of docs/dron-write-semantics.md. |
| 11902 | |
| 11903 | The submitted values are `changes` and `client_rev` (If-Match / |
| 11904 | expected_rev), or `parse`, which returns both from the request body |
| 11905 | and is called at U2, after the collection question (S10): a ValueError |
| 11906 | it raises is the 400. `existing` is the row the route already looked |
| 11907 | up (WebDAV finds a file by name); without it U3 looks `record_id` up. |
| 11908 | collection_asked: the route asked U1 itself, through |
| 11909 | _record_write_denied_before_lookup, before a lookup of its own. |
| 11910 | |
| 11911 | Every gate after U3 judges `existing`, read before the write lock: they |
| 11912 | load the policy, read other collections and run the package's hook, |
| 11913 | which must not run under this collection's file lock. The write is |
| 11914 | therefore told which row was judged (`judged_rev`) and refuses with a |
| 11915 | retryable 409 conflict if the row under the lock is any other (S52; |
| 11916 | object_records.RecordChangedError). |
| 11917 | """ |
| 11918 | out = _WriteRefusal() |
| 11919 | # U1: may this caller update this collection at all (no record yet)? |
| 11920 | if not collection_asked and await _record_write_denied_before_lookup( |
| 11921 | out, headers, object_permissions.UPDATE, collection=collection, now=now |
| 11922 | ): |
| 11923 | return out |
| 11924 | |
| 11925 | # U2 parse, U3 look the record up. |
| 11926 | try: |
| 11927 | if parse is not None: |
| 11928 | changes, client_rev = parse() |
| 11929 | if existing is None: |
| 11930 | existing = object_records.get_collection_record(collection, record_id, base_dir=_data_dir()) |
| 11931 | except ValueError as exc: |
| 11932 | await _send_json(out, {"status": "error", "error": str(exc)}, status=400) |
| 11933 | return out |
| 11934 | except (object_collections.CollectionNotFoundError, object_records.RecordNotFoundError) as exc: |
| 11935 | await _send_json(out, {"status": "error", "error": str(exc)}, status=404) |
| 11936 | return out |
| 11937 | assert changes is not None |
| 11938 | if not _concurrency_enabled(): |
| 11939 | client_rev = None # flag off: precondition ignored, last-write-wins |
| 11940 | |
| 11941 | judged_rev = object_records.compute_record_rev(existing) |
| 11942 | candidate = dict(existing) |
| 11943 | candidate.update(changes) |
| 11944 | candidate["id"] = record_id |
| 11945 | |
| 11946 | # U4: the stored row; under enforcement, also the row as it would be. |
| 11947 | permission_check = await _authorize_collection_write( |
| 11948 | out, |
| 11949 | headers, |
| 11950 | object_permissions.UPDATE, |
| 11951 | collection=collection, |
| 11952 | method="PUT", |
| 11953 | record=existing, |
| 11954 | gate_message=f"Collection record writes require {ADMIN_TOKEN_ENV}.", |
| 11955 | now=now, |
| 11956 | ) |
| 11957 | if permission_check is None: |
| 11958 | return out |
| 11959 | if _permission_enforcement_enabled(): |
| 11960 | permission_check = await _authorize_collection_write( |
| 11961 | out, |
| 11962 | headers, |
| 11963 | object_permissions.UPDATE, |
| 11964 | collection=collection, |
| 11965 | method="PUT", |
| 11966 | record=candidate, |
| 11967 | gate_message=f"Collection record writes require {ADMIN_TOKEN_ENV}.", |
| 11968 | now=now, |
| 11969 | ) |
| 11970 | if permission_check is None: |
| 11971 | return out |
| 11972 | |
| 11973 | # U5: a changed owner_id (S13). |
| 11974 | if await _refuse_owner_change( |
| 11975 | out, |
| 11976 | headers, |
| 11977 | collection=collection, |
| 11978 | existing=existing, |
| 11979 | changes=changes, |
| 11980 | candidate=candidate, |
| 11981 | permission_check=permission_check, |
| 11982 | now=now, |
| 11983 | ): |
| 11984 | return out |
| 11985 | |
| 11986 | # U6: field permissions on every key sent (S14). |
| 11987 | if permission_check["enforced"] and await _refuse_denied_fields( |
| 11988 | out, collection, changes.keys(), permission_check=permission_check, record=candidate |
| 11989 | ): |
| 11990 | return out |
| 11991 | |
| 11992 | # U7: relation.requires on every pointer whose value changes (S15). |
| 11993 | if await _refuse_unreachable_relations( |
| 11994 | out, |
| 11995 | collection=collection, |
| 11996 | record=candidate, |
| 11997 | existing=existing, |
| 11998 | permission_check=permission_check, |
| 11999 | ): |
| 12000 | return out |
| 12001 | |
| 12002 | # U8: the package's pre-write hook (S16, S19). |
| 12003 | hooked = await _apply_before_write_hook( |
| 12004 | out, |
| 12005 | headers, |
| 12006 | collection=collection, |
| 12007 | action="update", |
| 12008 | record=candidate, |
| 12009 | existing=existing, |
| 12010 | changes=changes, |
| 12011 | ) |
| 12012 | if hooked is None: |
| 12013 | return out |
| 12014 | if hooked is not candidate: |
| 12015 | # Persist only the delta the hook produced on top of the caller's own |
| 12016 | # changes: update_collection_record treats every submitted key as a |
| 12017 | # field write, so echoing untouched read-only fields (created_at) back |
| 12018 | # through it would be rejected as read-only submissions. A change key |
| 12019 | # the hook dropped from its record is a cancelled change. |
| 12020 | final_changes = {k: v for k, v in changes.items() if k in hooked} |
| 12021 | for key, value in hooked.items(): |
| 12022 | if key == "id": |
| 12023 | continue |
| 12024 | if key not in candidate or candidate.get(key) != value: |
| 12025 | final_changes[key] = value |
| 12026 | changes = final_changes |
| 12027 | |
| 12028 | # U9-U18: storage, under its lock. |
| 12029 | final = changes |
| 12030 | record = await _storage_write(out, _UPDATE_STORAGE_ANSWERS, lambda: object_records.update_collection_record( |
| 12031 | collection, |
| 12032 | record_id, |
| 12033 | final, |
| 12034 | base_dir=_data_dir(), |
| 12035 | actor=_record_change_actor(headers), |
| 12036 | transition_subject=permission_check["subject"], |
| 12037 | # A client's If-Match is compared against the keyed client rev, |
| 12038 | # never the unkeyed fingerprint (object_records.client_record_rev). |
| 12039 | expected_client_rev=client_rev, |
| 12040 | judged_rev=judged_rev, |
| 12041 | )) |
| 12042 | if record is None: |
| 12043 | return out |
| 12044 | return await _write_landed( |
| 12045 | headers, collection=collection, record_id=record_id, record=record, now=now, |
| 12046 | publish=publish, shape_answer=shape_answer, |
| 12047 | ) |
| 12048 | |
| 12049 | |
| 12050 | async def _gated_delete( |
| 12051 | headers: dict[str, str], |
| 12052 | *, |
| 12053 | collection: str, |
| 12054 | record_id: str, |
| 12055 | now: datetime, |
| 12056 | existing: dict[str, Any] | None = None, |
| 12057 | collection_asked: bool = False, |
| 12058 | row_asked: bool = False, |
| 12059 | publish: bool = True, |
| 12060 | shape_answer: bool = True, |
| 12061 | storage_answers: tuple = (), |
| 12062 | ) -> "_WriteRefusal | _WriteDone": |
| 12063 | """A delete of one record, S30 of docs/dron-write-semantics.md: the |
| 12064 | collection question, the lookup, the row permission, the hook, then |
| 12065 | under the lock the row again, the judged row (S52), `locked_when`, |
| 12066 | `locked_checks`, the tombstone. |
| 12067 | |
| 12068 | `existing` is the row the route already looked up. collection_asked / |
| 12069 | row_asked: the route asked that question itself, through the files' |
| 12070 | own decision (_user_files_collection_allowed, _user_file_allowed), |
| 12071 | before steps of its own. `storage_answers` come before the record |
| 12072 | API's answers to a storage exception (S61). |
| 12073 | """ |
| 12074 | out = _WriteRefusal() |
| 12075 | if not collection_asked and await _record_write_denied_before_lookup( |
| 12076 | out, headers, object_permissions.DELETE, collection=collection, now=now |
| 12077 | ): |
| 12078 | return out |
| 12079 | |
| 12080 | if existing is None: |
| 12081 | try: |
| 12082 | existing = object_records.get_collection_record(collection, record_id, base_dir=_data_dir()) |
| 12083 | except ValueError as exc: |
| 12084 | await _send_json(out, {"status": "error", "error": str(exc)}, status=400) |
| 12085 | return out |
| 12086 | except (object_collections.CollectionNotFoundError, object_records.RecordNotFoundError) as exc: |
| 12087 | await _send_json(out, {"status": "error", "error": str(exc)}, status=404) |
| 12088 | return out |
| 12089 | |
| 12090 | if not row_asked and await _authorize_collection_write( |
| 12091 | out, |
| 12092 | headers, |
| 12093 | object_permissions.DELETE, |
| 12094 | collection=collection, |
| 12095 | method="DELETE", |
| 12096 | record=existing, |
| 12097 | gate_message=f"Collection record writes require {ADMIN_TOKEN_ENV}.", |
| 12098 | now=now, |
| 12099 | ) is None: |
| 12100 | return out |
| 12101 | |
| 12102 | if not await _delete_allowed_by_hook(out, headers, collection=collection, existing=existing): |
| 12103 | return out |
| 12104 | |
| 12105 | # The permission and the hook judged `existing`, read before the lock: |
| 12106 | # refuse (409 conflict) if the row under the lock is another (S52). |
| 12107 | judged_rev = object_records.compute_record_rev(existing) |
| 12108 | record = await _storage_write( |
| 12109 | out, |
| 12110 | storage_answers + _DELETE_STORAGE_ANSWERS, |
| 12111 | lambda: object_records.delete_collection_record( |
| 12112 | collection, |
| 12113 | record_id, |
| 12114 | base_dir=_data_dir(), |
| 12115 | actor=_record_change_actor(headers), |
| 12116 | judged_rev=judged_rev, |
| 12117 | ), |
| 12118 | ) |
| 12119 | if record is None: |
| 12120 | return out |
| 12121 | return await _write_landed( |
| 12122 | headers, collection=collection, record_id=record_id, record=record, now=now, |
| 12123 | publish=publish, shape_answer=shape_answer, |
| 12124 | ) |
| 12125 | |
| 12126 | |
| 12127 | # A grant another request revoked between this route's lookup and the lock |
| 12128 | # is answered as the lookup answers a grant that is not there. |
| 12129 | _SHARE_REVOKE_STORAGE_ANSWERS: tuple = ( |
| 12130 | (object_records.RecordNotFoundError, |
| 12131 | lambda exc: (404, {"status": "error", "error": "Grant not found."})), |
| 12132 | ) |
| 12133 | |
| 12134 | |
| 12135 | # How the file routes answered a storage failure of a file's delete before |
| 12136 | # they shared the record API's write path, tried first. Kept differences: |
| 12137 | # the record API answers an invalid id or another ValueError 400 and a disk |
| 12138 | # error 500 with a JSON body; a file delete answered both 404 and let a disk |
| 12139 | # error propagate. Neither is about who may delete what. |
| 12140 | _FILE_DELETE_STORAGE_ANSWERS: tuple = ( |
| 12141 | (object_records.VersionConflictError, _conflict_refusal), |
| 12142 | (object_records.RecordLockedError, _locked_refusal), |
| 12143 | (object_records.CheckRefusedError, _check_refusal), |
| 12144 | ((LookupError, ValueError), _plain_refusal(404)), |
| 12145 | (OSError, None), |
| 12146 | ) |
| 12147 | |
| 12148 | |
| 12149 | # How the file routes answered a storage failure of a file's create before |
| 12150 | # they shared the record API's write path, tried first. Kept differences: |
| 12151 | # the not-installed sentence, a duplicate id as 400 (a fresh UUID; a hook |
| 12152 | # may not change it), and a disk error left to propagate where the record |
| 12153 | # API answers 500 with a JSON body. |
| 12154 | _FILE_CREATE_STORAGE_ANSWERS: tuple = ( |
| 12155 | (object_collections.CollectionNotFoundError, |
| 12156 | lambda exc: (404, {"status": "error", |
| 12157 | "error": "The files collection is not installed (app-files package)."})), |
| 12158 | (object_records.UniqueConstraintError, _unique_refusal), |
| 12159 | (object_records.CheckRefusedError, _check_refusal), |
| 12160 | (ValueError, _plain_refusal(400)), |
| 12161 | (OSError, None), |
| 12162 | ) |
| 12163 | |
| 12164 | |
| 12165 | async def _refuse_denied_fields( |
| 12166 | send, |
| 12167 | collection: str, |
| 12168 | submitted_fields, |
| 12169 | *, |
| 12170 | permission_check: dict[str, Any], |
| 12171 | record: dict[str, Any], |
| 12172 | ) -> bool: |
| 12173 | """Field permissions on the keys a write sends (S14): the 403 with |
| 12174 | `denied_fields`, or a 500 when the schema cannot be read. True when a |
| 12175 | refusal has been sent. Only asked under enforcement (by the caller).""" |
| 12176 | try: |
| 12177 | denied_fields = _schema_denied_write_fields( |
| 12178 | collection, |
| 12179 | submitted_fields, |
| 12180 | subject=permission_check["subject"], |
| 12181 | policy=permission_check["policy"], |
| 12182 | record=record, |
| 12183 | ) |
| 12184 | except ValueError as exc: |
| 12185 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 12186 | return True |
| 12187 | if not denied_fields: |
| 12188 | return False |
| 12189 | await _send_json( |
| 12190 | send, |
| 12191 | { |
| 12192 | "status": "error", |
| 12193 | "error": _field_write_denied_message(denied_fields), |
| 12194 | "code": "forbidden", |
| 12195 | "denied_fields": denied_fields, |
| 12196 | }, |
| 12197 | status=403, |
| 12198 | ) |
| 12199 | return True |
| 12200 | |
| 12201 | |
| 12202 | async def _handle_collection_record_delete( |
| 12203 | send, |
| 12204 | collection: str, |
| 12205 | record_id: str, |
| 12206 | headers: dict[str, str], |
| 12207 | ) -> None: |
| 12208 | outcome = await _gated_delete( |
| 12209 | headers, collection=collection, record_id=record_id, now=datetime.now(timezone.utc) |
| 12210 | ) |
| 12211 | if isinstance(outcome, _WriteRefusal): |
| 12212 | await outcome.replay(send) |
| 12213 | return |
| 12214 | await _send_json( |
| 12215 | send, |
| 12216 | { |
| 12217 | "status": "ok", |
| 12218 | "collection": collection, |
| 12219 | "record": outcome.answer, |
| 12220 | "deleted": True, |
| 12221 | }, |
| 12222 | ) |
| 12223 | |
| 12224 | |
| 12225 | async def _record_write_denied_before_lookup( |
| 12226 | send, |
| 12227 | headers: dict[str, str], |
| 12228 | action: str, |
| 12229 | *, |
| 12230 | collection: str, |
| 12231 | now: datetime | None = None, |
| 12232 | ) -> bool: |
| 12233 | """Deny unauthorized record writes before any record existence lookup. |
| 12234 | |
| 12235 | Without this, a 404 for a missing record would leak record-id existence to |
| 12236 | callers who are not allowed to write at all. Subjects allowed at the |
| 12237 | collection level (including row-filtered allows) proceed to the normal |
| 12238 | record-aware authorization. |
| 12239 | """ |
| 12240 | if not _permission_enforcement_enabled(): |
| 12241 | gate_error = _admin_token_gate_error( |
| 12242 | headers, |
| 12243 | f"Collection record writes require {ADMIN_TOKEN_ENV}.", |
| 12244 | ) |
| 12245 | if gate_error is not None: |
| 12246 | status, message = gate_error |
| 12247 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 12248 | return True |
| 12249 | return False |
| 12250 | |
| 12251 | subject = _permission_subject(headers) |
| 12252 | policy, policy_error = _load_policy_for_request(headers) |
| 12253 | if policy is None: |
| 12254 | # This returned False ("not denied") and let the write go on to the |
| 12255 | # record lookup; a pre-check that cannot decide must refuse. |
| 12256 | await _send_policy_unavailable(send, headers, policy_error or "") |
| 12257 | return True |
| 12258 | try: |
| 12259 | decision = object_permissions.check_permission( |
| 12260 | subject, |
| 12261 | action, |
| 12262 | policy=policy, |
| 12263 | collection=collection, |
| 12264 | now=now, |
| 12265 | ) |
| 12266 | except ValueError as exc: |
| 12267 | await _send_policy_unavailable(send, headers, _policy_unavailable_error(exc)) |
| 12268 | return True |
| 12269 | |
| 12270 | if decision.allowed: |
| 12271 | return False |
| 12272 | |
| 12273 | await _send_json( |
| 12274 | send, |
| 12275 | { |
| 12276 | "status": "error", |
| 12277 | "error": decision.reason, |
| 12278 | "code": decision.code, |
| 12279 | }, |
| 12280 | status=decision.http_status, |
| 12281 | ) |
| 12282 | return True |
| 12283 | |
| 12284 | |
| 12285 | async def _authorize_collection_write( |
| 12286 | send, |
| 12287 | headers: dict[str, str], |
| 12288 | action: str, |
| 12289 | *, |
| 12290 | collection: str, |
| 12291 | method: str, |
| 12292 | record: dict[str, Any], |
| 12293 | gate_message: str, |
| 12294 | now: datetime | None = None, |
| 12295 | ) -> dict[str, Any] | None: |
| 12296 | if _permission_enforcement_enabled(): |
| 12297 | return await _collection_permission_check( |
| 12298 | send, |
| 12299 | headers, |
| 12300 | action, |
| 12301 | collection=collection, |
| 12302 | method=method, |
| 12303 | record=record, |
| 12304 | now=now, |
| 12305 | ) |
| 12306 | |
| 12307 | if _permission_audit_enabled(): |
| 12308 | permission_check = await _collection_permission_check( |
| 12309 | send, |
| 12310 | headers, |
| 12311 | action, |
| 12312 | collection=collection, |
| 12313 | method=method, |
| 12314 | record=record, |
| 12315 | now=now, |
| 12316 | ) |
| 12317 | if permission_check is None: |
| 12318 | return None |
| 12319 | |
| 12320 | gate_error = _admin_token_gate_error(headers, gate_message) |
| 12321 | if gate_error is not None: |
| 12322 | status, message = gate_error |
| 12323 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 12324 | return None |
| 12325 | |
| 12326 | return { |
| 12327 | "subject": _permission_subject(headers), |
| 12328 | "policy": object_permissions.PermissionPolicy(access_mode="public"), |
| 12329 | "decision": object_permissions.PermissionDecision.allow("admin token"), |
| 12330 | "enforced": False, |
| 12331 | } |
| 12332 | |
| 12333 | |
| 12334 | async def _handle_schemas( |
| 12335 | send, |
| 12336 | method: str, |
| 12337 | headers: dict[str, str], |
| 12338 | ) -> None: |
| 12339 | if method != "GET": |
| 12340 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12341 | return |
| 12342 | |
| 12343 | gate_error = _admin_token_gate_error( |
| 12344 | headers, |
| 12345 | f"Schema listing requires {ADMIN_TOKEN_ENV}.", |
| 12346 | ) |
| 12347 | if gate_error is not None: |
| 12348 | status, message = gate_error |
| 12349 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 12350 | return |
| 12351 | |
| 12352 | try: |
| 12353 | schemas = object_schemas.list_schemas(base_dir=_data_dir()) |
| 12354 | except (OSError, ValueError) as exc: |
| 12355 | await _send_collection_names_error(send, headers, exc) |
| 12356 | return |
| 12357 | |
| 12358 | await _send_json( |
| 12359 | send, |
| 12360 | { |
| 12361 | "status": "ok", |
| 12362 | "schemas": schemas, |
| 12363 | "count": len(schemas), |
| 12364 | }, |
| 12365 | ) |
| 12366 | |
| 12367 | |
| 12368 | async def _handle_schema_get( |
| 12369 | send, |
| 12370 | method: str, |
| 12371 | schema: str, |
| 12372 | headers: dict[str, str], |
| 12373 | ) -> None: |
| 12374 | await _handle_schema(send, method, schema, {}, b"", headers) |
| 12375 | |
| 12376 | |
| 12377 | async def _handle_schema_meta(send, method: str, collection: str) -> None: |
| 12378 | """Public schema metadata for building UIs (form/list generators). |
| 12379 | |
| 12380 | Returns the *structure* only — field types, labels, enums, relations, |
| 12381 | validation, forms, views, search — never data. Records stay |
| 12382 | permission-gated; knowing a collection's field shape is not a leak, and |
| 12383 | it lets any surface (web, anonymous public pages, agents) render itself |
| 12384 | from the schema. |
| 12385 | """ |
| 12386 | if method != "GET": |
| 12387 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12388 | return |
| 12389 | try: |
| 12390 | schema = object_schemas.get_schema(collection, base_dir=_data_dir()) |
| 12391 | except object_schemas.InvalidSchemaNameError as exc: |
| 12392 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 12393 | return |
| 12394 | except (LookupError, ValueError): |
| 12395 | await _send_json(send, {"status": "error", "error": "Schema not found"}, status=404) |
| 12396 | return |
| 12397 | |
| 12398 | meta = {key: schema.get(key) |
| 12399 | for key in ("name", "title", "fields", "forms", "views", "search", "flow", "capabilities")} |
| 12400 | await _send_json(send, {"status": "ok", "schema": meta}) |
| 12401 | |
| 12402 | |
| 12403 | USER_PREFS_COLLECTION = "user_prefs" |
| 12404 | FEATURE_FLAGS_COLLECTION = "feature_flags" |
| 12405 | FLAG_PREF_PREFIX = "flag:" |
| 12406 | _PREF_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$") |
| 12407 | |
| 12408 | |
| 12409 | def _valid_pref_key(key: str) -> bool: |
| 12410 | """Route-safe key charset: no slashes, no whitespace, bounded length.""" |
| 12411 | return isinstance(key, str) and bool(_PREF_KEY_RE.fullmatch(key)) |
| 12412 | |
| 12413 | |
| 12414 | def _read_user_prefs_or_empty() -> list[dict[str, str]]: |
| 12415 | try: |
| 12416 | return object_records.read_collection_records( |
| 12417 | USER_PREFS_COLLECTION, base_dir=_data_dir(), roots=get_object_roots() |
| 12418 | ) |
| 12419 | except ( |
| 12420 | object_collections.CollectionNotFoundError, |
| 12421 | object_collections.InvalidCollectionNameError, |
| 12422 | OSError, |
| 12423 | ValueError, |
| 12424 | ): |
| 12425 | return [] |
| 12426 | |
| 12427 | |
| 12428 | def _read_feature_flags_or_empty() -> list[dict[str, str]]: |
| 12429 | try: |
| 12430 | return object_records.read_collection_records( |
| 12431 | FEATURE_FLAGS_COLLECTION, base_dir=_data_dir(), roots=get_object_roots() |
| 12432 | ) |
| 12433 | except ( |
| 12434 | object_collections.CollectionNotFoundError, |
| 12435 | object_collections.InvalidCollectionNameError, |
| 12436 | OSError, |
| 12437 | ValueError, |
| 12438 | ): |
| 12439 | return [] |
| 12440 | |
| 12441 | |
| 12442 | def _user_prefs_map(user_id: str) -> dict[str, str]: |
| 12443 | """Collapse one user's own user_prefs rows to a key -> value map.""" |
| 12444 | prefs: dict[str, str] = {} |
| 12445 | for row in _read_user_prefs_or_empty(): |
| 12446 | if row.get("owner_id") == user_id and row.get("key"): |
| 12447 | prefs[row["key"]] = row.get("value", "") |
| 12448 | return prefs |
| 12449 | |
| 12450 | |
| 12451 | def _find_user_pref(user_id: str, key: str) -> dict[str, str] | None: |
| 12452 | for row in _read_user_prefs_or_empty(): |
| 12453 | if row.get("owner_id") == user_id and row.get("key") == key: |
| 12454 | return row |
| 12455 | return None |
| 12456 | |
| 12457 | |
| 12458 | def _upsert_user_pref(user_id: str, key: str, value: str) -> dict[str, str]: |
| 12459 | """Create or update the caller's own user_prefs row for ``key``. |
| 12460 | |
| 12461 | ``user_id`` must come from the session-derived subject, never from |
| 12462 | client input -- this is the only thing that keeps prefs owner-scoped. |
| 12463 | """ |
| 12464 | existing = _find_user_pref(user_id, key) |
| 12465 | if existing is not None: |
| 12466 | # write-path: the caller's own preference row, keyed by the session's identity |
| 12467 | return object_records.update_collection_record( |
| 12468 | USER_PREFS_COLLECTION, |
| 12469 | existing["id"], |
| 12470 | {"value": value}, |
| 12471 | base_dir=_data_dir(), |
| 12472 | roots=get_object_roots(), |
| 12473 | actor=user_id, |
| 12474 | ) |
| 12475 | # write-path: the caller's own preference row, keyed by the session's identity |
| 12476 | return object_records.create_collection_record( |
| 12477 | USER_PREFS_COLLECTION, |
| 12478 | { |
| 12479 | "id": object_ids.new_uuid4(), |
| 12480 | "owner_id": user_id, |
| 12481 | "key": key, |
| 12482 | "value": value, |
| 12483 | }, |
| 12484 | base_dir=_data_dir(), |
| 12485 | roots=get_object_roots(), |
| 12486 | actor=user_id, |
| 12487 | ) |
| 12488 | |
| 12489 | |
| 12490 | def _resolve_flags(user_id: str | None) -> dict[str, str]: |
| 12491 | """Effective flag values: instance feature_flags overlaid by the |
| 12492 | caller's own ``flag:<name>`` user_prefs entries. |
| 12493 | |
| 12494 | Resolution order is user override -> instance value, per |
| 12495 | docs/upgrade-and-customization.md Rule 5. Anonymous callers (user_id is |
| 12496 | None) only ever see the instance-wide values. |
| 12497 | """ |
| 12498 | flags: dict[str, str] = {} |
| 12499 | for row in _read_feature_flags_or_empty(): |
| 12500 | flag = row.get("flag") |
| 12501 | if flag: |
| 12502 | flags[flag] = row.get("value", "") |
| 12503 | if user_id is not None: |
| 12504 | for row in _read_user_prefs_or_empty(): |
| 12505 | if row.get("owner_id") != user_id: |
| 12506 | continue |
| 12507 | key = row.get("key") or "" |
| 12508 | if key.startswith(FLAG_PREF_PREFIX): |
| 12509 | flags[key[len(FLAG_PREF_PREFIX):]] = row.get("value", "") |
| 12510 | return flags |
| 12511 | |
| 12512 | |
| 12513 | async def _handle_prefs(send, method: str, headers: dict[str, str]) -> None: |
| 12514 | """GET /prefs -> the caller's own user_prefs rows collapsed to a map. |
| 12515 | |
| 12516 | Session-scoped by construction: the owner filter always comes from the |
| 12517 | caller's own identity, so this never needs the general collection |
| 12518 | permission engine. Anonymous callers get an empty map rather than a |
| 12519 | 401 -- reading your own (empty) preferences is harmless. |
| 12520 | """ |
| 12521 | if method != "GET": |
| 12522 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12523 | return |
| 12524 | subject = _permission_subject(headers) |
| 12525 | prefs = _user_prefs_map(subject.user_id) if subject.user_id is not None else {} |
| 12526 | await _send_json(send, {"status": "ok", "prefs": prefs}) |
| 12527 | |
| 12528 | |
| 12529 | async def _handle_pref( |
| 12530 | send, |
| 12531 | method: str, |
| 12532 | key: str, |
| 12533 | body: bytes, |
| 12534 | headers: dict[str, str], |
| 12535 | ) -> None: |
| 12536 | """GET/PUT one preference for the caller, by key. |
| 12537 | |
| 12538 | Never accepts owner_id/user_id from the client -- the row is always |
| 12539 | looked up and written against the session-derived subject. |
| 12540 | """ |
| 12541 | if method not in {"GET", "PUT"}: |
| 12542 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12543 | return |
| 12544 | if not _valid_pref_key(key): |
| 12545 | await _send_json(send, {"status": "error", "error": "Invalid preference key"}, status=400) |
| 12546 | return |
| 12547 | |
| 12548 | subject = _permission_subject(headers) |
| 12549 | |
| 12550 | if method == "GET": |
| 12551 | row = _find_user_pref(subject.user_id, key) if subject.user_id is not None else None |
| 12552 | if row is None: |
| 12553 | await _send_json(send, {"status": "error", "error": "Preference not found"}, status=404) |
| 12554 | return |
| 12555 | await _send_json(send, {"status": "ok", "key": key, "value": row.get("value", "")}) |
| 12556 | return |
| 12557 | |
| 12558 | if subject.user_id is None: |
| 12559 | await _send_json( |
| 12560 | send, |
| 12561 | {"status": "error", "error": "Setting preferences requires a signed-in session."}, |
| 12562 | status=401, |
| 12563 | ) |
| 12564 | return |
| 12565 | |
| 12566 | try: |
| 12567 | payload = _parse_json_body(body) |
| 12568 | except ValueError as exc: |
| 12569 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 12570 | return |
| 12571 | |
| 12572 | value = payload.get("value") |
| 12573 | if not isinstance(value, str): |
| 12574 | await _send_json( |
| 12575 | send, |
| 12576 | {"status": "error", "error": "Request JSON field 'value' must be a string"}, |
| 12577 | status=400, |
| 12578 | ) |
| 12579 | return |
| 12580 | |
| 12581 | try: |
| 12582 | _upsert_user_pref(subject.user_id, key, value) |
| 12583 | except ( |
| 12584 | object_collections.InvalidCollectionNameError, |
| 12585 | object_records.InvalidRecordIdError, |
| 12586 | object_records.InvalidRecordPayloadError, |
| 12587 | ValueError, |
| 12588 | ) as exc: |
| 12589 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 12590 | return |
| 12591 | except object_collections.CollectionNotFoundError as exc: |
| 12592 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 12593 | return |
| 12594 | except OSError as exc: |
| 12595 | await _send_json( |
| 12596 | send, |
| 12597 | {"status": "error", "error": f"Could not save preference: {exc}"}, |
| 12598 | status=500, |
| 12599 | ) |
| 12600 | return |
| 12601 | |
| 12602 | await _send_json(send, {"status": "ok", "key": key, "value": value}) |
| 12603 | |
| 12604 | |
| 12605 | async def _handle_flags(send, method: str, headers: dict[str, str]) -> None: |
| 12606 | """GET /api/flags -> effective feature flags for the caller. |
| 12607 | |
| 12608 | Public/session-aware like /api/schema: works anonymously (instance |
| 12609 | values only) and overlays the caller's own per-user overrides when |
| 12610 | signed in. |
| 12611 | """ |
| 12612 | if method != "GET": |
| 12613 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12614 | return |
| 12615 | subject = _permission_subject(headers) |
| 12616 | flags = _resolve_flags(subject.user_id) |
| 12617 | await _send_json(send, {"status": "ok", "flags": flags}) |
| 12618 | |
| 12619 | |
| 12620 | async def _handle_activity( |
| 12621 | send, |
| 12622 | method: str, |
| 12623 | query: dict[str, str], |
| 12624 | headers: dict[str, str], |
| 12625 | ) -> None: |
| 12626 | """GET /api/activity -> the caller's own recent activity feed. |
| 12627 | |
| 12628 | A thin read-only wrapper over object_activity.recent_activity, scoped to |
| 12629 | the signed-in caller's own changes (see that module's docstring for why |
| 12630 | v1 only does "your activity"). Unlike /prefs, which hands anonymous |
| 12631 | callers an empty map because reading your own (empty) preferences is |
| 12632 | harmless, a feed endpoint rejects anonymous callers outright -- there is |
| 12633 | no legitimate empty-but-still-answerable case here, only "no session". |
| 12634 | """ |
| 12635 | if method != "GET": |
| 12636 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12637 | return |
| 12638 | |
| 12639 | session = _current_identity_session(headers) |
| 12640 | if session is None: |
| 12641 | await _send_json( |
| 12642 | send, |
| 12643 | {"status": "error", "error": "Activity requires a signed-in session."}, |
| 12644 | status=401, |
| 12645 | ) |
| 12646 | return |
| 12647 | |
| 12648 | try: |
| 12649 | limit = _query_int(query, "limit", default=50, minimum=1, maximum=200) |
| 12650 | except ValueError as exc: |
| 12651 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 12652 | return |
| 12653 | |
| 12654 | readable = None |
| 12655 | if _permission_enforcement_enabled(): |
| 12656 | # Titles come from what this caller may read of the row, not from the |
| 12657 | # whole snapshot (a field their schema or rule hides must not become |
| 12658 | # their feed's title). |
| 12659 | subject = _permission_subject(headers) |
| 12660 | access = object_access.Access( |
| 12661 | {"user_id": subject.user_id, "account_id": subject.account_id, |
| 12662 | "roles": list(subject.roles), "subscriptions": list(subject.subscriptions)}, |
| 12663 | base_dir=_data_dir(), |
| 12664 | ) |
| 12665 | readable = access.readable |
| 12666 | entries = object_activity.recent_activity( |
| 12667 | base_dir=_data_dir(), actor=session.user_id, limit=limit, readable=readable |
| 12668 | ) |
| 12669 | await _send_json(send, {"status": "ok", "activity": entries}) |
| 12670 | |
| 12671 | |
| 12672 | async def _handle_stock_levels(send, method: str, headers: dict[str, str]) -> None: |
| 12673 | """GET /api/stock -> Stage-7 get_stock_levels: the caller's on-hand stock, |
| 12674 | folded from stock_moves (object_stock.stock_levels). Owner-scoped -- the |
| 12675 | same fold the site_stock page uses, exposed as JSON for the MCP verb. A |
| 12676 | missing stock_moves collection or an anonymous caller returns an empty, |
| 12677 | non-error summary (nothing to fold), never a 500. |
| 12678 | """ |
| 12679 | if method != "GET": |
| 12680 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12681 | return |
| 12682 | subject = _permission_subject(headers) |
| 12683 | if not subject.user_id: |
| 12684 | await _send_json(send, {"status": "ok", "levels": [], "totals": [], "authenticated": False}) |
| 12685 | return |
| 12686 | try: |
| 12687 | levels = object_stock.stock_levels(base_dir=_data_dir(), owner=subject.user_id) |
| 12688 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 12689 | levels = {"levels": [], "totals": []} |
| 12690 | except (OSError, ValueError) as exc: |
| 12691 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 12692 | return |
| 12693 | await _send_json(send, {"status": "ok", **levels}) |
| 12694 | |
| 12695 | |
| 12696 | async def _handle_finance_summary(send, method: str, headers: dict[str, str]) -> None: |
| 12697 | """GET /api/finance/summary -> Stage-7 get_finance_summary: the caller's |
| 12698 | trial balance (per-account debit/credit totals over POSTED journals), |
| 12699 | folded by object_finance.trial_balance. Owner-scoped, same report the |
| 12700 | site_trial_balance page renders, as JSON for the MCP verb. No journals / |
| 12701 | anonymous -> empty rows, never a 500. |
| 12702 | """ |
| 12703 | if method != "GET": |
| 12704 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12705 | return |
| 12706 | subject = _permission_subject(headers) |
| 12707 | if not subject.user_id: |
| 12708 | await _send_json(send, {"status": "ok", "rows": [], "authenticated": False}) |
| 12709 | return |
| 12710 | try: |
| 12711 | rows = object_finance.trial_balance(base_dir=_data_dir(), owner=subject.user_id) |
| 12712 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 12713 | rows = [] |
| 12714 | except (OSError, ValueError) as exc: |
| 12715 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 12716 | return |
| 12717 | await _send_json(send, {"status": "ok", "rows": rows}) |
| 12718 | |
| 12719 | |
| 12720 | async def _handle_feed( |
| 12721 | send, |
| 12722 | method: str, |
| 12723 | query: dict[str, str], |
| 12724 | headers: dict[str, str], |
| 12725 | ) -> None: |
| 12726 | """GET /api/feed -> 64's composed, permission-gated follow-graph read. |
| 12727 | |
| 12728 | For the signed-in caller V: recent PUBLIC content authored by the |
| 12729 | accounts V follows, newest-first (plan/vocabulary/64-feed-spec.md). |
| 12730 | v1 is a pure filtered-read COMPOSITION -- two existing permission-gated |
| 12731 | /collections/{c}/records reads (58), riding V's own forwarded |
| 12732 | credentials through _internal_request -- never a direct read of the |
| 12733 | record layer. That is what guarantees the core privacy invariant: a |
| 12734 | followed account's PRIVATE content can never enter the feed, because |
| 12735 | every source read is subject to that collection's own row-filtered |
| 12736 | permission rule (e.g. articles' `public read where is_public=true`) |
| 12737 | exactly as if V had queried it directly. Following someone grants no |
| 12738 | additional read access -- it only adds an `owner_id IN (followed set)` |
| 12739 | predicate on top of the row filter that already applies. |
| 12740 | |
| 12741 | No 401 for an anonymous caller (unlike /api/activity above): the spec's |
| 12742 | Surfaces section says the feed is simply "not rendered" for anonymous |
| 12743 | visitors, and Degradation asks for an empty, non-error response in |
| 12744 | every degraded case (feed disabled, no viewer, no follows) -- so every |
| 12745 | early-return here is a 200 with an empty `items` list plus a flag |
| 12746 | saying why, never a 4xx/5xx. |
| 12747 | """ |
| 12748 | if method != "GET": |
| 12749 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12750 | return |
| 12751 | |
| 12752 | subject = _permission_subject(headers) |
| 12753 | viewer_id = subject.user_id |
| 12754 | if not viewer_id: |
| 12755 | await _send_json( |
| 12756 | send, |
| 12757 | {"status": "ok", "items": [], "count": 0, "authenticated": False}, |
| 12758 | ) |
| 12759 | return |
| 12760 | |
| 12761 | if not _feed_enabled(): |
| 12762 | await _send_json( |
| 12763 | send, |
| 12764 | {"status": "ok", "items": [], "count": 0, "enabled": False}, |
| 12765 | ) |
| 12766 | return |
| 12767 | |
| 12768 | try: |
| 12769 | limit = _query_int(query, "limit", default=50, minimum=1, maximum=200) |
| 12770 | offset = _query_int(query, "offset", default=0, minimum=0) |
| 12771 | except ValueError as exc: |
| 12772 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 12773 | return |
| 12774 | |
| 12775 | # Forward V's own credentials to every sub-read: a bearer/admin token |
| 12776 | # header if present, else the session cookie re-expressed as a bearer |
| 12777 | # token (_internal_request only carries an Authorization header, no |
| 12778 | # cookie jar) -- see _permission_identity for the same cookie-or-token |
| 12779 | # resolution order used to build `subject` above. |
| 12780 | authorization = headers.get("authorization") or "" |
| 12781 | if not authorization: |
| 12782 | cookie_token = _session_cookie_token(headers) |
| 12783 | if cookie_token: |
| 12784 | authorization = f"Bearer {cookie_token}" |
| 12785 | |
| 12786 | follows_query = urllib.parse.urlencode([("follower_id.eq", viewer_id), ("limit", "500")]) |
| 12787 | follows_status, follows_payload = await _internal_request( |
| 12788 | "GET", |
| 12789 | "/collections/follows/records", |
| 12790 | follows_query, |
| 12791 | b"", |
| 12792 | authorization=authorization, |
| 12793 | ) |
| 12794 | if await _send_if_unavailable(send, follows_status, follows_payload): |
| 12795 | return |
| 12796 | |
| 12797 | following_ids: list[str] = [] |
| 12798 | if follows_status == 200 and isinstance(follows_payload, dict): |
| 12799 | for row in follows_payload.get("records") or []: |
| 12800 | following_id = row.get("following_id") if isinstance(row, dict) else None |
| 12801 | if following_id and following_id not in following_ids: |
| 12802 | following_ids.append(following_id) |
| 12803 | |
| 12804 | # 58's `in` cap (FILTER_IN_MAX_VALUES) directly bounds how many followed |
| 12805 | # accounts one feed read can scan. Over the cap: truncate to the first |
| 12806 | # N and say so, rather than silently dropping accounts or raising 58's |
| 12807 | # cap on this call site's behalf -- the spec's Storage section names |
| 12808 | # this exact cap-hit as the forcing function for the materialized |
| 12809 | # feed_items path, not something to paper over here. |
| 12810 | truncated_following = len(following_ids) > FILTER_IN_MAX_VALUES |
| 12811 | if truncated_following: |
| 12812 | following_ids = following_ids[:FILTER_IN_MAX_VALUES] |
| 12813 | |
| 12814 | response: dict[str, Any] = {"status": "ok", "authenticated": True} |
| 12815 | if truncated_following: |
| 12816 | response["truncated_following"] = True |
| 12817 | |
| 12818 | if not following_ids: |
| 12819 | response.update({"items": [], "count": 0}) |
| 12820 | await _send_json(send, response) |
| 12821 | return |
| 12822 | |
| 12823 | items: list[dict[str, Any]] = [] |
| 12824 | for source in _feed_sources(): |
| 12825 | pairs = [(f"{source['owner_field']}.in", ",".join(following_ids))] |
| 12826 | if source["visibility_field"] and source["visibility_true_value"] is not None: |
| 12827 | pairs.append( |
| 12828 | (f"{source['visibility_field']}.eq", str(source["visibility_true_value"])) |
| 12829 | ) |
| 12830 | pairs.append(("limit", "200")) |
| 12831 | source_status, source_payload = await _internal_request( |
| 12832 | "GET", |
| 12833 | f"/collections/{source['collection']}/records", |
| 12834 | urllib.parse.urlencode(pairs), |
| 12835 | b"", |
| 12836 | authorization=authorization, |
| 12837 | ) |
| 12838 | if await _send_if_unavailable(send, source_status, source_payload): |
| 12839 | return |
| 12840 | if source_status != 200 or not isinstance(source_payload, dict): |
| 12841 | # One bad/missing/disallowed source degrades to fewer sources, |
| 12842 | # never an error -- same isolation 14's rollup definitions use |
| 12843 | # for "one bad definition is logged and skipped", applied here |
| 12844 | # to feed sources (spec's Degradation section). |
| 12845 | continue |
| 12846 | for record in source_payload.get("records") or []: |
| 12847 | if not isinstance(record, dict): |
| 12848 | continue |
| 12849 | items.append( |
| 12850 | { |
| 12851 | "source_collection": source["collection"], |
| 12852 | "source_id": record.get(source["link_field"]) or record.get("id"), |
| 12853 | "author_id": record.get(source["owner_field"]), |
| 12854 | "time": record.get(source["time_field"]) or "", |
| 12855 | "summary": _feed_item_summary(record, source["summary_fields"]), |
| 12856 | "record": record, |
| 12857 | } |
| 12858 | ) |
| 12859 | |
| 12860 | # Step 3 of the spec's read shape: merge every source's already-small, |
| 12861 | # already-filtered rows by time_field, newest first -- no server sort |
| 12862 | # param exists for /collections/{c}/records (58's own Open Questions), |
| 12863 | # so this handler does the k-way merge itself. |
| 12864 | items.sort(key=lambda item: item["time"], reverse=True) |
| 12865 | total = len(items) |
| 12866 | window = items[offset : offset + limit] |
| 12867 | response.update({"items": window, "count": len(window), "total": total}) |
| 12868 | await _send_json(send, response) |
| 12869 | |
| 12870 | |
| 12871 | async def _send_if_unavailable(send, status: int, payload: Any) -> bool: |
| 12872 | """Pass a sub-read's 503 through (policy or identity store unavailable). |
| 12873 | |
| 12874 | The feed degrades a refused or missing source to "fewer items", but a 503 |
| 12875 | is not a refusal: it means the box cannot decide right now, and an empty |
| 12876 | 200 would tell the caller there is nothing new. Its body carries no parse |
| 12877 | error for a non-admin caller (the sub-read already decided that). |
| 12878 | """ |
| 12879 | if status != 503: |
| 12880 | return False |
| 12881 | body = payload if isinstance(payload, dict) else {"status": "error", "error": str(payload)} |
| 12882 | headers = None |
| 12883 | retry_after = body.get("retry_after") |
| 12884 | if retry_after is not None: |
| 12885 | headers = [("retry-after", str(retry_after))] |
| 12886 | await _send_json(send, body, status=503, headers=headers) |
| 12887 | return True |
| 12888 | |
| 12889 | |
| 12890 | def _feed_enabled() -> bool: |
| 12891 | value = os.environ.get(FEED_ENABLED_ENV) |
| 12892 | if value is None: |
| 12893 | return True |
| 12894 | return value.strip().lower() in TRUE_VALUES |
| 12895 | |
| 12896 | |
| 12897 | def _feed_sources() -> list[dict[str, Any]]: |
| 12898 | """Discover feed-source collections via schema metadata (64's `blocks.feed`). |
| 12899 | |
| 12900 | A collection opts into the feed by declaring `blocks.feed` in its |
| 12901 | schema (plan/vocabulary/64-feed-spec.md's Parameterization section) -- |
| 12902 | additive-opt-in, same posture as every other block key in this |
| 12903 | vocabulary; nothing is swept in by default. |
| 12904 | |
| 12905 | `blocks` is a first-class schema metadata key (whitelisted in |
| 12906 | object_schemas._normalize_schema alongside `flow`/`views`), so it |
| 12907 | survives normalization and install and is read through the ordinary, |
| 12908 | cached get_schema path -- never a raw side-channel file read. |
| 12909 | """ |
| 12910 | sources: list[dict[str, Any]] = [] |
| 12911 | try: |
| 12912 | summaries = object_schemas.list_schemas(base_dir=_data_dir()) |
| 12913 | except (OSError, ValueError): |
| 12914 | return sources |
| 12915 | |
| 12916 | for summary in summaries: |
| 12917 | if summary.get("source") != "manual": |
| 12918 | continue # blocks.feed can only be declared in a manual schema |
| 12919 | name = summary.get("name") |
| 12920 | if not name or not object_schemas.validate_schema_name(name): |
| 12921 | continue |
| 12922 | try: |
| 12923 | raw = object_schemas.get_schema(name, base_dir=_data_dir()) |
| 12924 | except (object_schemas.SchemaNotFoundError, OSError, ValueError): |
| 12925 | continue |
| 12926 | if not isinstance(raw, dict): |
| 12927 | continue |
| 12928 | |
| 12929 | blocks = raw.get("blocks") |
| 12930 | feed_block = blocks.get("feed") if isinstance(blocks, dict) else None |
| 12931 | if not isinstance(feed_block, dict): |
| 12932 | continue |
| 12933 | |
| 12934 | owner_field = feed_block.get("owner_field") |
| 12935 | time_field = feed_block.get("time_field") |
| 12936 | if not isinstance(owner_field, str) or not owner_field: |
| 12937 | continue |
| 12938 | if not isinstance(time_field, str) or not time_field: |
| 12939 | continue |
| 12940 | |
| 12941 | summary_fields = feed_block.get("summary_fields") |
| 12942 | if not isinstance(summary_fields, list) or not summary_fields: |
| 12943 | views = raw.get("views") |
| 12944 | summary_fields = views.get("list_fields") if isinstance(views, dict) else None |
| 12945 | if not isinstance(summary_fields, list): |
| 12946 | summary_fields = [] |
| 12947 | summary_fields = [field for field in summary_fields if isinstance(field, str)] |
| 12948 | |
| 12949 | link_field = feed_block.get("link_field") |
| 12950 | if not isinstance(link_field, str) or not link_field: |
| 12951 | link_field = "id" |
| 12952 | |
| 12953 | visibility_field = feed_block.get("visibility_field") |
| 12954 | if not isinstance(visibility_field, str) or not visibility_field: |
| 12955 | visibility_field = None |
| 12956 | |
| 12957 | sources.append( |
| 12958 | { |
| 12959 | "collection": name, |
| 12960 | "owner_field": owner_field, |
| 12961 | "visibility_field": visibility_field, |
| 12962 | "visibility_true_value": feed_block.get("visibility_true_value"), |
| 12963 | "time_field": time_field, |
| 12964 | "summary_fields": summary_fields, |
| 12965 | "link_field": link_field, |
| 12966 | } |
| 12967 | ) |
| 12968 | return sources |
| 12969 | |
| 12970 | |
| 12971 | def _feed_item_summary(record: dict[str, Any], summary_fields: list[str]) -> str: |
| 12972 | parts = [str(record[field]).strip() for field in summary_fields if record.get(field)] |
| 12973 | return " — ".join(part for part in parts if part) |
| 12974 | |
| 12975 | |
| 12976 | async def _handle_schema( |
| 12977 | send, |
| 12978 | method: str, |
| 12979 | schema: str, |
| 12980 | query: dict[str, str], |
| 12981 | body: bytes, |
| 12982 | headers: dict[str, str], |
| 12983 | ) -> None: |
| 12984 | if method != "GET": |
| 12985 | if method == "PUT": |
| 12986 | await _handle_schema_put(send, schema, body, headers) |
| 12987 | return |
| 12988 | if method == "POST": |
| 12989 | await _handle_schema_post(send, schema, body, headers) |
| 12990 | return |
| 12991 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 12992 | return |
| 12993 | |
| 12994 | if query.get("versions") == "true": |
| 12995 | await _handle_schema_versions_get(send, schema, query, headers) |
| 12996 | return |
| 12997 | |
| 12998 | if "version" in query: |
| 12999 | await _handle_schema_version_get(send, schema, query, headers) |
| 13000 | return |
| 13001 | |
| 13002 | gate_error = _admin_token_gate_error( |
| 13003 | headers, |
| 13004 | f"Schema detail requires {ADMIN_TOKEN_ENV}.", |
| 13005 | ) |
| 13006 | if gate_error is not None: |
| 13007 | status, message = gate_error |
| 13008 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13009 | return |
| 13010 | |
| 13011 | try: |
| 13012 | schema_payload = object_schemas.get_schema(schema, base_dir=_data_dir()) |
| 13013 | except object_schemas.InvalidSchemaNameError as exc: |
| 13014 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13015 | return |
| 13016 | except object_schemas.SchemaNotFoundError as exc: |
| 13017 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 13018 | return |
| 13019 | except ValueError as exc: |
| 13020 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13021 | return |
| 13022 | |
| 13023 | await _send_json( |
| 13024 | send, |
| 13025 | { |
| 13026 | "status": "ok", |
| 13027 | "schema": schema_payload, |
| 13028 | }, |
| 13029 | ) |
| 13030 | |
| 13031 | |
| 13032 | async def _handle_schema_put( |
| 13033 | send, |
| 13034 | schema: str, |
| 13035 | body: bytes, |
| 13036 | headers: dict[str, str], |
| 13037 | ) -> None: |
| 13038 | gate_error = _admin_token_gate_error( |
| 13039 | headers, |
| 13040 | f"Schema writes require {ADMIN_TOKEN_ENV}.", |
| 13041 | ) |
| 13042 | if gate_error is not None: |
| 13043 | status, message = gate_error |
| 13044 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13045 | return |
| 13046 | |
| 13047 | try: |
| 13048 | payload = _parse_json_body(body) |
| 13049 | schema_payload = _schema_payload_from_request(payload) |
| 13050 | normalized_schema = object_schemas.normalize_schema(schema, schema_payload, source="manual") |
| 13051 | author = _payload_text(payload, "author", "api") |
| 13052 | message = _payload_text(payload, "message", "Updated schema via API") |
| 13053 | version_id = _schema_version_manager().save_version( |
| 13054 | schema=schema, |
| 13055 | content=object_schema_versions.schema_version_content(normalized_schema), |
| 13056 | author=author, |
| 13057 | message=message, |
| 13058 | ) |
| 13059 | saved_schema = object_schemas.replace_schema( |
| 13060 | schema, |
| 13061 | normalized_schema, |
| 13062 | base_dir=_data_dir(), |
| 13063 | ) |
| 13064 | except object_schemas.InvalidSchemaNameError as exc: |
| 13065 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13066 | return |
| 13067 | except object_schema_versions.InvalidSchemaNameError as exc: |
| 13068 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13069 | return |
| 13070 | except ValueError as exc: |
| 13071 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13072 | return |
| 13073 | except OSError as exc: |
| 13074 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13075 | return |
| 13076 | |
| 13077 | await _send_json( |
| 13078 | send, |
| 13079 | { |
| 13080 | "status": "ok", |
| 13081 | "message": f"Schema updated to version {version_id}", |
| 13082 | "version_id": version_id, |
| 13083 | "collection": schema, |
| 13084 | "schema": saved_schema, |
| 13085 | }, |
| 13086 | ) |
| 13087 | |
| 13088 | |
| 13089 | async def _handle_schema_post( |
| 13090 | send, |
| 13091 | schema: str, |
| 13092 | body: bytes, |
| 13093 | headers: dict[str, str], |
| 13094 | ) -> None: |
| 13095 | try: |
| 13096 | payload = _parse_json_body(body) |
| 13097 | except ValueError as exc: |
| 13098 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13099 | return |
| 13100 | |
| 13101 | if payload.get("action") != "rollback": |
| 13102 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13103 | return |
| 13104 | |
| 13105 | await _handle_schema_rollback_post(send, schema, payload, headers) |
| 13106 | |
| 13107 | |
| 13108 | async def _handle_schema_versions_get( |
| 13109 | send, |
| 13110 | schema: str, |
| 13111 | query: dict[str, str], |
| 13112 | headers: dict[str, str], |
| 13113 | ) -> None: |
| 13114 | gate_error = _admin_token_gate_error( |
| 13115 | headers, |
| 13116 | f"Schema versions require {ADMIN_TOKEN_ENV}.", |
| 13117 | ) |
| 13118 | if gate_error is not None: |
| 13119 | status, message = gate_error |
| 13120 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13121 | return |
| 13122 | |
| 13123 | try: |
| 13124 | object_schemas.get_schema(schema, base_dir=_data_dir()) |
| 13125 | limit = _query_int(query, "limit", default=10, minimum=1, maximum=100) |
| 13126 | versions = _schema_version_manager().get_history(schema, limit=limit) |
| 13127 | except object_schemas.InvalidSchemaNameError as exc: |
| 13128 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13129 | return |
| 13130 | except object_schemas.SchemaNotFoundError as exc: |
| 13131 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 13132 | return |
| 13133 | except object_schema_versions.InvalidSchemaNameError as exc: |
| 13134 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13135 | return |
| 13136 | except ValueError as exc: |
| 13137 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13138 | return |
| 13139 | |
| 13140 | await _send_json( |
| 13141 | send, |
| 13142 | { |
| 13143 | "status": "ok", |
| 13144 | "collection": schema, |
| 13145 | "versions": versions, |
| 13146 | "count": len(versions), |
| 13147 | }, |
| 13148 | ) |
| 13149 | |
| 13150 | |
| 13151 | async def _handle_schema_version_get( |
| 13152 | send, |
| 13153 | schema: str, |
| 13154 | query: dict[str, str], |
| 13155 | headers: dict[str, str], |
| 13156 | ) -> None: |
| 13157 | gate_error = _admin_token_gate_error( |
| 13158 | headers, |
| 13159 | f"Schema version detail requires {ADMIN_TOKEN_ENV}.", |
| 13160 | ) |
| 13161 | if gate_error is not None: |
| 13162 | status, message = gate_error |
| 13163 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13164 | return |
| 13165 | |
| 13166 | try: |
| 13167 | version_id = _query_int(query, "version", minimum=1) |
| 13168 | version = _schema_version_manager().get_version(schema, version_id) |
| 13169 | except object_schema_versions.InvalidSchemaNameError as exc: |
| 13170 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13171 | return |
| 13172 | except ValueError as exc: |
| 13173 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13174 | return |
| 13175 | |
| 13176 | if version is None: |
| 13177 | await _send_json( |
| 13178 | send, |
| 13179 | {"status": "error", "error": f"Version {version_id} not found for schema {schema}"}, |
| 13180 | status=404, |
| 13181 | ) |
| 13182 | return |
| 13183 | |
| 13184 | await _send_json( |
| 13185 | send, |
| 13186 | { |
| 13187 | "status": "ok", |
| 13188 | "collection": schema, |
| 13189 | "version": _schema_version_payload(version), |
| 13190 | }, |
| 13191 | ) |
| 13192 | |
| 13193 | |
| 13194 | async def _handle_schema_rollback_post( |
| 13195 | send, |
| 13196 | schema: str, |
| 13197 | payload: dict[str, Any], |
| 13198 | headers: dict[str, str], |
| 13199 | ) -> None: |
| 13200 | gate_error = _admin_token_gate_error( |
| 13201 | headers, |
| 13202 | f"Schema rollback requires {ADMIN_TOKEN_ENV}.", |
| 13203 | ) |
| 13204 | if gate_error is not None: |
| 13205 | status, message = gate_error |
| 13206 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13207 | return |
| 13208 | |
| 13209 | try: |
| 13210 | version_id = _payload_int(payload, "version_id", minimum=1) |
| 13211 | author = _payload_text(payload, "author", "api") |
| 13212 | message = _payload_text(payload, "message", f"Rollback schema to version {version_id}") |
| 13213 | new_version_id = _schema_version_manager().rollback( |
| 13214 | schema=schema, |
| 13215 | to_version=version_id, |
| 13216 | author=author, |
| 13217 | message=message, |
| 13218 | ) |
| 13219 | new_version = _schema_version_manager().get_version(schema, new_version_id) |
| 13220 | if new_version is None: |
| 13221 | raise object_schema_versions.SchemaVersionNotFoundError( |
| 13222 | f"Version {new_version_id} not found for schema {schema}" |
| 13223 | ) |
| 13224 | schema_payload = json.loads(new_version["content"]) |
| 13225 | saved_schema = object_schemas.replace_schema(schema, schema_payload, base_dir=_data_dir()) |
| 13226 | except object_schemas.InvalidSchemaNameError as exc: |
| 13227 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13228 | return |
| 13229 | except object_schema_versions.InvalidSchemaNameError as exc: |
| 13230 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13231 | return |
| 13232 | except object_schema_versions.SchemaVersionNotFoundError as exc: |
| 13233 | await _send_json(send, {"status": "error", "error": str(exc)}, status=404) |
| 13234 | return |
| 13235 | except (json.JSONDecodeError, ValueError) as exc: |
| 13236 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13237 | return |
| 13238 | except OSError as exc: |
| 13239 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13240 | return |
| 13241 | |
| 13242 | await _send_json( |
| 13243 | send, |
| 13244 | { |
| 13245 | "status": "ok", |
| 13246 | "message": f"Rolled back schema to version {version_id}", |
| 13247 | "version_id": version_id, |
| 13248 | "new_version_id": new_version_id, |
| 13249 | "collection": schema, |
| 13250 | "schema": saved_schema, |
| 13251 | }, |
| 13252 | ) |
| 13253 | |
| 13254 | |
| 13255 | def _object_source_payload(source) -> dict[str, str]: |
| 13256 | return { |
| 13257 | "object_id": source.object_id, |
| 13258 | "path": source.relative_path.as_posix(), |
| 13259 | "owner": _object_owner(source.object_id), |
| 13260 | } |
| 13261 | |
| 13262 | |
| 13263 | def _schema_version_payload(version: dict[str, Any]) -> dict[str, Any]: |
| 13264 | payload = dict(version) |
| 13265 | content = payload.get("content") |
| 13266 | if isinstance(content, str): |
| 13267 | try: |
| 13268 | payload["schema"] = json.loads(content) |
| 13269 | except json.JSONDecodeError: |
| 13270 | pass |
| 13271 | return payload |
| 13272 | |
| 13273 | |
| 13274 | def _object_owner(object_id: str) -> str: |
| 13275 | parsed = parse_user_object_id(object_id) |
| 13276 | if parsed is None: |
| 13277 | return "system" |
| 13278 | user_id, _ = parsed |
| 13279 | return str(user_id) |
| 13280 | |
| 13281 | |
| 13282 | def _object_collection(object_id: str) -> str | None: |
| 13283 | parsed = parse_user_object_id(object_id) |
| 13284 | if parsed is not None: |
| 13285 | _, name = parsed |
| 13286 | return name.split("_", 1)[0] if name else None |
| 13287 | |
| 13288 | return object_id.split("_", 1)[0] if object_id else None |
| 13289 | |
| 13290 | |
| 13291 | def _append_execution_log(result: object_execution.ObjectExecutionResult) -> None: |
| 13292 | if result.path is None: |
| 13293 | return |
| 13294 | |
| 13295 | try: |
| 13296 | if result.ok: |
| 13297 | object_logs.append_object_log( |
| 13298 | result.object_id, |
| 13299 | "DEBUG", |
| 13300 | f"{result.method} completed successfully", |
| 13301 | base_dir=_data_dir(), |
| 13302 | correlation_id=result.correlation_id, |
| 13303 | method=result.method, |
| 13304 | status="success", |
| 13305 | duration_ms=result.duration_ms, |
| 13306 | ) |
| 13307 | return |
| 13308 | |
| 13309 | error_type = result.error.type if result.error is not None else None |
| 13310 | error = result.error.message if result.error is not None else None |
| 13311 | object_logs.append_object_log( |
| 13312 | result.object_id, |
| 13313 | "ERROR", |
| 13314 | f"{result.method} failed: {error}", |
| 13315 | base_dir=_data_dir(), |
| 13316 | correlation_id=result.correlation_id, |
| 13317 | method=result.method, |
| 13318 | status="error", |
| 13319 | duration_ms=result.duration_ms, |
| 13320 | error_type=error_type, |
| 13321 | error=error, |
| 13322 | ) |
| 13323 | except Exception: |
| 13324 | # Logging is feedback for the dev loop; it should not change the object response. |
| 13325 | pass |
| 13326 | |
| 13327 | |
| 13328 | def _append_file_log( |
| 13329 | object_id: str, |
| 13330 | *, |
| 13331 | operation: str, |
| 13332 | metadata: Mapping[str, Any], |
| 13333 | method: str, |
| 13334 | ) -> None: |
| 13335 | try: |
| 13336 | object_logs.append_object_log( |
| 13337 | object_id, |
| 13338 | "INFO", |
| 13339 | f"File {operation}: {metadata['name']}", |
| 13340 | base_dir=_data_dir(), |
| 13341 | method=method, |
| 13342 | status="success", |
| 13343 | file_name=metadata.get("name"), |
| 13344 | file_size=metadata.get("size"), |
| 13345 | file_operation=operation, |
| 13346 | ) |
| 13347 | except Exception: |
| 13348 | # File logs are operator feedback; file writes should not fail because logging failed. |
| 13349 | pass |
| 13350 | |
| 13351 | |
| 13352 | def _append_file_change_log( |
| 13353 | object_id: str, |
| 13354 | *, |
| 13355 | operation: str, |
| 13356 | metadata: Mapping[str, Any], |
| 13357 | method: str, |
| 13358 | actor: str, |
| 13359 | correlation_id: str | None, |
| 13360 | ) -> dict[str, Any] | None: |
| 13361 | action = { |
| 13362 | "created": "file_create", |
| 13363 | "updated": "file_update", |
| 13364 | "deleted": "file_delete", |
| 13365 | }.get(operation) |
| 13366 | if action is None: |
| 13367 | return None |
| 13368 | |
| 13369 | try: |
| 13370 | return object_file_changes.append_file_change( |
| 13371 | object_id=object_id, |
| 13372 | action=action, |
| 13373 | file_name=str(metadata.get("name") or ""), |
| 13374 | file_size=int(metadata["size"]) if "size" in metadata else None, |
| 13375 | actor=actor, |
| 13376 | message=f"File {operation}: {metadata.get('name')}", |
| 13377 | correlation_id=correlation_id, |
| 13378 | details={ |
| 13379 | "method": method, |
| 13380 | "modified": metadata.get("modified"), |
| 13381 | }, |
| 13382 | base_dir=_data_dir(), |
| 13383 | ) |
| 13384 | except Exception: |
| 13385 | # File-change entries are operator feedback; file writes already succeeded. |
| 13386 | return None |
| 13387 | |
| 13388 | |
| 13389 | def _append_source_change_log( |
| 13390 | object_id: str, |
| 13391 | *, |
| 13392 | action: str, |
| 13393 | version_id: int, |
| 13394 | from_version_id: int | None = None, |
| 13395 | actor: str = "api", |
| 13396 | message: str = "", |
| 13397 | correlation_id: str | None = None, |
| 13398 | details: Mapping[str, Any] | None = None, |
| 13399 | ) -> None: |
| 13400 | fields: dict[str, Any] = { |
| 13401 | "action": action, |
| 13402 | "version_id": version_id, |
| 13403 | } |
| 13404 | if from_version_id is not None: |
| 13405 | fields["from_version_id"] = from_version_id |
| 13406 | |
| 13407 | try: |
| 13408 | object_source_changes.append_source_change( |
| 13409 | object_id=object_id, |
| 13410 | action=action, |
| 13411 | version_id=version_id, |
| 13412 | from_version_id=from_version_id, |
| 13413 | actor=actor, |
| 13414 | message=message, |
| 13415 | correlation_id=correlation_id, |
| 13416 | details=details, |
| 13417 | base_dir=_data_dir(), |
| 13418 | ) |
| 13419 | object_logs.append_object_log( |
| 13420 | object_id, |
| 13421 | "INFO", |
| 13422 | f"{action} version {version_id}", |
| 13423 | base_dir=_data_dir(), |
| 13424 | correlation_id=correlation_id or object_correlation.current_correlation_id(), |
| 13425 | **fields, |
| 13426 | ) |
| 13427 | except Exception: |
| 13428 | # Source-change entries are operator feedback; source writes already succeeded. |
| 13429 | pass |
| 13430 | |
| 13431 | |
| 13432 | def _object_count() -> int: |
| 13433 | return sum(1 for _ in iter_object_sources()) |
| 13434 | |
| 13435 | |
| 13436 | def _pyproject_version(path: Path | None = None) -> str | None: |
| 13437 | """The `version = "..."` line of the [project] table of the pyproject.toml |
| 13438 | beside this file, or None. A small parse so Python 3.10 (no tomllib) works.""" |
| 13439 | path = path or Path(__file__).resolve().parent / "pyproject.toml" |
| 13440 | try: |
| 13441 | lines = path.read_text(encoding="utf-8").splitlines() |
| 13442 | except OSError: |
| 13443 | return None |
| 13444 | in_project = False |
| 13445 | for line in lines: |
| 13446 | text = line.strip() |
| 13447 | if text.startswith("["): |
| 13448 | in_project = text == "[project]" |
| 13449 | elif in_project: |
| 13450 | key, sep, value = text.partition("=") |
| 13451 | if sep and key.strip() == "version": |
| 13452 | value = value.split("#", 1)[0].strip() |
| 13453 | if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": |
| 13454 | return value[1:-1] or None |
| 13455 | return None |
| 13456 | return None |
| 13457 | |
| 13458 | |
| 13459 | def _package_version() -> str: |
| 13460 | # Installed metadata wins. The Docker image runs from the source tree |
| 13461 | # without installing it, so then the pyproject.toml beside this file says. |
| 13462 | try: |
| 13463 | return importlib_metadata.version("dbbasic-object-server") |
| 13464 | except importlib_metadata.PackageNotFoundError: |
| 13465 | return _pyproject_version() or "0.0.1" |
| 13466 | |
| 13467 | |
| 13468 | BUILD_COMMIT_ENV = "DBBASIC_BUILD_COMMIT" |
| 13469 | BUILD_COMMIT_FILE = Path(__file__).resolve().parent / "BUILD_COMMIT" |
| 13470 | _BUILD_COMMIT_RE = re.compile(r"[0-9a-fA-F]{7,40}") |
| 13471 | |
| 13472 | |
| 13473 | def _build_commit() -> str | None: |
| 13474 | """The git commit this build came from (lowercase hex), or None when unknown. |
| 13475 | |
| 13476 | DBBASIC_BUILD_COMMIT wins; else the BUILD_COMMIT file the Docker build |
| 13477 | writes beside this module; else None. Never runs git: a `git archive` |
| 13478 | tree has no .git. Only 7 to 40 hex characters count, so a bad value can |
| 13479 | never put other text in the startup line or in JSON. |
| 13480 | """ |
| 13481 | raw = os.environ.get(BUILD_COMMIT_ENV) |
| 13482 | if raw is None or not raw.strip(): |
| 13483 | try: |
| 13484 | raw = BUILD_COMMIT_FILE.read_text(encoding="utf-8", errors="replace")[:200] |
| 13485 | except OSError: |
| 13486 | return None |
| 13487 | raw = raw.strip() |
| 13488 | if _BUILD_COMMIT_RE.fullmatch(raw): |
| 13489 | return raw.lower() |
| 13490 | return None |
| 13491 | |
| 13492 | |
| 13493 | def _station_id() -> str: |
| 13494 | return os.environ.get("DBBASIC_STATION_ID") or os.environ.get("STATION_ID") or "standalone" |
| 13495 | |
| 13496 | |
| 13497 | def _rate_limit_identity(scope: dict[str, Any], headers: dict[str, str]) -> str: |
| 13498 | token = _authorization_token(headers) |
| 13499 | admin_token = os.environ.get(ADMIN_TOKEN_ENV, "") |
| 13500 | if token and admin_token and _secret_equals(token, admin_token): |
| 13501 | return f"token:{_hash_identity(token)}" |
| 13502 | |
| 13503 | return f"ip:{_client_ip(scope, headers)}" |
| 13504 | |
| 13505 | |
| 13506 | def _hash_identity(value: str) -> str: |
| 13507 | return hashlib.sha256(value.encode("utf-8")).hexdigest()[:32] |
| 13508 | |
| 13509 | |
| 13510 | def _client_ip(scope: dict[str, Any], headers: dict[str, str]) -> str: |
| 13511 | if _env_enabled(RATE_LIMIT_TRUST_PROXY_HEADERS_ENV): |
| 13512 | forwarded = headers.get("x-forwarded-for", "") |
| 13513 | if forwarded: |
| 13514 | return forwarded.split(",", 1)[0].strip() |
| 13515 | |
| 13516 | real_ip = headers.get("x-real-ip", "") |
| 13517 | if real_ip: |
| 13518 | return real_ip.strip() |
| 13519 | |
| 13520 | client = scope.get("client") |
| 13521 | if isinstance(client, (list, tuple)) and client: |
| 13522 | return str(client[0]) |
| 13523 | |
| 13524 | return "127.0.0.1" |
| 13525 | |
| 13526 | |
| 13527 | def _storage_check() -> dict[str, str]: |
| 13528 | check_path = os.path.join(_data_dir(), ".health_check") |
| 13529 | try: |
| 13530 | os.makedirs(_data_dir(), exist_ok=True) |
| 13531 | with open(check_path, "w", encoding="utf-8") as handle: |
| 13532 | handle.write("ok") |
| 13533 | with open(check_path, encoding="utf-8") as handle: |
| 13534 | handle.read() |
| 13535 | os.unlink(check_path) |
| 13536 | except OSError as exc: |
| 13537 | return { |
| 13538 | "status": "error", |
| 13539 | "message": str(exc), |
| 13540 | } |
| 13541 | |
| 13542 | return {"status": "ok"} |
| 13543 | |
| 13544 | |
| 13545 | async def _handle_admin_ops( |
| 13546 | send, |
| 13547 | method: str, |
| 13548 | query: dict[str, str], |
| 13549 | headers: dict[str, str], |
| 13550 | ) -> None: |
| 13551 | if method != "GET": |
| 13552 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13553 | return |
| 13554 | |
| 13555 | gate_error = _admin_token_gate_error( |
| 13556 | headers, |
| 13557 | f"Ops events require {ADMIN_TOKEN_ENV}.", |
| 13558 | ) |
| 13559 | if gate_error is not None: |
| 13560 | status, message = gate_error |
| 13561 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13562 | return |
| 13563 | |
| 13564 | try: |
| 13565 | events = object_ops_log.read_events( |
| 13566 | base_dir=_data_dir(), |
| 13567 | limit=_query_int(query, "limit", default=100, minimum=1, maximum=1000), |
| 13568 | kind=_optional_query_text(query, "kind"), |
| 13569 | event=_optional_query_text(query, "event"), |
| 13570 | identifier=_optional_query_text(query, "identifier"), |
| 13571 | ) |
| 13572 | except ValueError as exc: |
| 13573 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13574 | return |
| 13575 | except OSError as exc: |
| 13576 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13577 | return |
| 13578 | |
| 13579 | await _send_json( |
| 13580 | send, |
| 13581 | { |
| 13582 | "status": "ok", |
| 13583 | "events": events, |
| 13584 | "count": len(events), |
| 13585 | }, |
| 13586 | ) |
| 13587 | |
| 13588 | |
| 13589 | BACKUP_SCHEDULE_ENV = "DBBASIC_BACKUP_SCHEDULE" |
| 13590 | |
| 13591 | |
| 13592 | def _backup_schedule_payload() -> dict[str, Any]: |
| 13593 | """Automatic backups are a config option; report whether one is set. |
| 13594 | |
| 13595 | Scheduled runs are driven by an external timer (systemd/cron) calling |
| 13596 | `object_backup.py create`; DBBASIC_BACKUP_SCHEDULE records the operator's |
| 13597 | intent so clients can show it. On-demand create/download always work. |
| 13598 | """ |
| 13599 | schedule = os.environ.get(BACKUP_SCHEDULE_ENV, "").strip() |
| 13600 | return {"scheduled": bool(schedule), "schedule": schedule or None, "env": BACKUP_SCHEDULE_ENV, |
| 13601 | # The daemon's own scheduled backups (object_backup_schedule), |
| 13602 | # reported in full under /admin/status "scheduled_backups". |
| 13603 | "destination_configured": object_backup_schedule.config()["enabled"], |
| 13604 | "destination_env": object_backup_schedule.DESTINATION_ENV} |
| 13605 | |
| 13606 | |
| 13607 | def _scheduled_backups_payload() -> dict[str, Any]: |
| 13608 | """object_backup_schedule.status for this box, never raising: a status |
| 13609 | page that fails because the backup status could not be read would hide |
| 13610 | exactly the thing it exists to show, so an unreadable status is itself |
| 13611 | reported as a problem.""" |
| 13612 | try: |
| 13613 | return object_backup_schedule.status(_data_dir()) |
| 13614 | except Exception as exc: # noqa: BLE001 |
| 13615 | return {"enabled": object_backup_schedule.config()["enabled"], "healthy": False, |
| 13616 | "problems": [{"id": "status_unreadable", |
| 13617 | "message": f"backup status could not be read: {exc}"}], |
| 13618 | "warnings": []} |
| 13619 | |
| 13620 | |
| 13621 | def _scheduled_backup_alert(payload: Mapping[str, Any]) -> str | None: |
| 13622 | problems = payload.get("problems") or [] |
| 13623 | if not problems: |
| 13624 | return None |
| 13625 | return "BACKUPS NEED ATTENTION: " + "; ".join(str(p.get("message")) for p in problems) |
| 13626 | |
| 13627 | |
| 13628 | async def _handle_admin_scheduled_backups( |
| 13629 | send, |
| 13630 | method: str, |
| 13631 | path: str, |
| 13632 | headers: dict[str, str], |
| 13633 | ) -> None: |
| 13634 | """Scheduled backups: GET the status; POST .../run to back up now, POST |
| 13635 | .../test to restore-test the newest snapshot now. Admin only. |
| 13636 | |
| 13637 | A POST starts the work on a thread and answers 202 at once: a large box |
| 13638 | takes minutes, longer than a proxy waits, and the result belongs in the |
| 13639 | status (GET this route, /admin/status) where every other surface reads |
| 13640 | it, not in one HTTP response somebody may never see. 409 when backups |
| 13641 | are off or a run is already going. |
| 13642 | """ |
| 13643 | gate_error = _admin_token_gate_error(headers, f"Backups require {ADMIN_TOKEN_ENV}.") |
| 13644 | if gate_error is not None: |
| 13645 | status, message = gate_error |
| 13646 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13647 | return |
| 13648 | |
| 13649 | if path == http_api_contract.ADMIN_SCHEDULED_BACKUPS_PATH: |
| 13650 | if method != "GET": |
| 13651 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13652 | return |
| 13653 | await _send_json(send, {"status": "ok", "scheduled_backups": _scheduled_backups_payload()}) |
| 13654 | return |
| 13655 | |
| 13656 | if method != "POST": |
| 13657 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13658 | return |
| 13659 | if not object_backup_schedule.config()["enabled"]: |
| 13660 | await _send_json(send, { |
| 13661 | "status": "error", |
| 13662 | "error": f"Scheduled backups are off; set {object_backup_schedule.DESTINATION_ENV} " |
| 13663 | "to a directory outside the data directory (a mounted disk, NFS, or a " |
| 13664 | "folder another tool syncs away)."}, status=409) |
| 13665 | return |
| 13666 | kind = "backup" if path == http_api_contract.ADMIN_SCHEDULED_BACKUPS_RUN_PATH else "restore_test" |
| 13667 | if kind == "restore_test" and not object_backup_schedule.list_snapshots( |
| 13668 | object_backup_schedule.config()["destination"]): |
| 13669 | await _send_json(send, {"status": "error", |
| 13670 | "error": "There is no snapshot at the destination to test."}, |
| 13671 | status=409) |
| 13672 | return |
| 13673 | thread = object_backup_schedule.start_in_background(kind, _data_dir()) |
| 13674 | if thread is None: |
| 13675 | await _send_json(send, {"status": "error", |
| 13676 | "error": "A backup or restore test is already running."}, |
| 13677 | status=409) |
| 13678 | return |
| 13679 | _append_ops_auth_event(event=f"scheduled_{kind}_started", |
| 13680 | identifier=_record_change_actor(headers)) |
| 13681 | await _send_json(send, {"status": "ok", "started": kind, |
| 13682 | "scheduled_backups": _scheduled_backups_payload()}, status=202) |
| 13683 | |
| 13684 | |
| 13685 | async def _handle_admin_backups( |
| 13686 | send, |
| 13687 | method: str, |
| 13688 | headers: dict[str, str], |
| 13689 | ) -> None: |
| 13690 | """List runtime backups (GET) or create one on demand (POST). Admin only.""" |
| 13691 | gate_error = _admin_token_gate_error(headers, f"Backups require {ADMIN_TOKEN_ENV}.") |
| 13692 | if gate_error is not None: |
| 13693 | status, message = gate_error |
| 13694 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13695 | return |
| 13696 | |
| 13697 | if method == "GET": |
| 13698 | try: |
| 13699 | backups = object_backup_index.list_backups(data_dir=_data_dir()) |
| 13700 | except (OSError, ValueError) as exc: |
| 13701 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13702 | return |
| 13703 | await _send_json( |
| 13704 | send, |
| 13705 | { |
| 13706 | "status": "ok", |
| 13707 | "backups": backups, |
| 13708 | "count": len(backups), |
| 13709 | "schedule": _backup_schedule_payload(), |
| 13710 | }, |
| 13711 | ) |
| 13712 | return |
| 13713 | |
| 13714 | if method == "POST": |
| 13715 | try: |
| 13716 | backup = object_backup_index.create_backup(data_dir=_data_dir()) |
| 13717 | except object_backup.BackupError as exc: |
| 13718 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13719 | return |
| 13720 | except OSError as exc: |
| 13721 | await _send_json( |
| 13722 | send, {"status": "error", "error": f"Could not create backup: {exc}"}, status=500 |
| 13723 | ) |
| 13724 | return |
| 13725 | _append_ops_auth_event(event="backup_created", identifier=_record_change_actor(headers), |
| 13726 | label=str(backup.get("id"))) |
| 13727 | await _send_json(send, {"status": "ok", "backup": backup}, status=201) |
| 13728 | return |
| 13729 | |
| 13730 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13731 | |
| 13732 | |
| 13733 | async def _handle_admin_backup_download( |
| 13734 | send, |
| 13735 | method: str, |
| 13736 | backup_id: str, |
| 13737 | headers: dict[str, str], |
| 13738 | ) -> None: |
| 13739 | """Stream one backup archive. Admin only — it contains all runtime data.""" |
| 13740 | if method != "GET": |
| 13741 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13742 | return |
| 13743 | |
| 13744 | gate_error = _admin_token_gate_error(headers, f"Backups require {ADMIN_TOKEN_ENV}.") |
| 13745 | if gate_error is not None: |
| 13746 | status, message = gate_error |
| 13747 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13748 | return |
| 13749 | |
| 13750 | try: |
| 13751 | path = object_backup_index.backup_path(backup_id, data_dir=_data_dir()) |
| 13752 | except ValueError as exc: |
| 13753 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13754 | return |
| 13755 | if not path.is_file(): |
| 13756 | await _send_json(send, {"status": "error", "error": "Backup not found"}, status=404) |
| 13757 | return |
| 13758 | |
| 13759 | try: |
| 13760 | content = path.read_bytes() |
| 13761 | except OSError as exc: |
| 13762 | await _send_json(send, {"status": "error", "error": str(exc)}, status=500) |
| 13763 | return |
| 13764 | |
| 13765 | _append_ops_auth_event(event="backup_downloaded", identifier=_record_change_actor(headers), |
| 13766 | label=backup_id) |
| 13767 | await _send_bytes( |
| 13768 | send, |
| 13769 | content, |
| 13770 | content_type="application/gzip", |
| 13771 | extra_headers=[ |
| 13772 | (b"content-disposition", f'attachment; filename="{backup_id}"'.encode("latin-1", "replace")), |
| 13773 | (b"x-content-type-options", b"nosniff"), |
| 13774 | ], |
| 13775 | ) |
| 13776 | |
| 13777 | |
| 13778 | async def _handle_admin_backup_preview( |
| 13779 | send, |
| 13780 | method: str, |
| 13781 | backup_id: str, |
| 13782 | query: dict[str, str], |
| 13783 | headers: dict[str, str], |
| 13784 | ) -> None: |
| 13785 | """Preview what restoring part of a backup would change. Read-only, admin only.""" |
| 13786 | if method != "GET": |
| 13787 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13788 | return |
| 13789 | |
| 13790 | gate_error = _admin_token_gate_error(headers, f"Backups require {ADMIN_TOKEN_ENV}.") |
| 13791 | if gate_error is not None: |
| 13792 | status, message = gate_error |
| 13793 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13794 | return |
| 13795 | |
| 13796 | try: |
| 13797 | path = object_backup_index.backup_path(backup_id, data_dir=_data_dir()) |
| 13798 | except ValueError as exc: |
| 13799 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13800 | return |
| 13801 | if not path.is_file(): |
| 13802 | await _send_json(send, {"status": "error", "error": "Backup not found"}, status=404) |
| 13803 | return |
| 13804 | |
| 13805 | kind = _optional_query_text(query, "kind") |
| 13806 | if kind != "collection": |
| 13807 | await _send_json( |
| 13808 | send, {"status": "error", "error": "unsupported preview kind"}, status=400 |
| 13809 | ) |
| 13810 | return |
| 13811 | |
| 13812 | name = _optional_query_text(query, "name") |
| 13813 | if not name: |
| 13814 | await _send_json( |
| 13815 | send, {"status": "error", "error": "Query parameter 'name' is required"}, status=400 |
| 13816 | ) |
| 13817 | return |
| 13818 | |
| 13819 | try: |
| 13820 | preview = object_backup_index.preview_collection(backup_id, name, data_dir=_data_dir()) |
| 13821 | except ValueError as exc: |
| 13822 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13823 | return |
| 13824 | |
| 13825 | await _send_json(send, {"status": "ok", "preview": preview}) |
| 13826 | |
| 13827 | |
| 13828 | async def _handle_admin_backup_record( |
| 13829 | send, |
| 13830 | method: str, |
| 13831 | backup_id: str, |
| 13832 | query: dict[str, str], |
| 13833 | headers: dict[str, str], |
| 13834 | ) -> None: |
| 13835 | """Pull one record's backup-vs-live status, without restoring. Admin only.""" |
| 13836 | if method != "GET": |
| 13837 | await _send_json(send, {"status": "error", "error": "Method not allowed"}, status=405) |
| 13838 | return |
| 13839 | |
| 13840 | gate_error = _admin_token_gate_error(headers, f"Backups require {ADMIN_TOKEN_ENV}.") |
| 13841 | if gate_error is not None: |
| 13842 | status, message = gate_error |
| 13843 | await _send_json(send, {"status": "error", "error": message}, status=status) |
| 13844 | return |
| 13845 | |
| 13846 | try: |
| 13847 | path = object_backup_index.backup_path(backup_id, data_dir=_data_dir()) |
| 13848 | except ValueError as exc: |
| 13849 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13850 | return |
| 13851 | if not path.is_file(): |
| 13852 | await _send_json(send, {"status": "error", "error": "Backup not found"}, status=404) |
| 13853 | return |
| 13854 | |
| 13855 | collection = _optional_query_text(query, "collection") |
| 13856 | if not collection: |
| 13857 | await _send_json( |
| 13858 | send, |
| 13859 | {"status": "error", "error": "Query parameter 'collection' is required"}, |
| 13860 | status=400, |
| 13861 | ) |
| 13862 | return |
| 13863 | |
| 13864 | record_id = _optional_query_text(query, "id") |
| 13865 | if not record_id: |
| 13866 | await _send_json( |
| 13867 | send, {"status": "error", "error": "Query parameter 'id' is required"}, status=400 |
| 13868 | ) |
| 13869 | return |
| 13870 | |
| 13871 | try: |
| 13872 | record = object_backup_index.preview_record( |
| 13873 | backup_id, collection, record_id, data_dir=_data_dir() |
| 13874 | ) |
| 13875 | except ValueError as exc: |
| 13876 | await _send_json(send, {"status": "error", "error": str(exc)}, status=400) |
| 13877 | return |
| 13878 | |
| 13879 | await _send_json(send, {"status": "ok", "record": record}) |
| 13880 | |
| 13881 | |
| 13882 | def _append_ops_execution_error( |
| 13883 | object_id: str, |
| 13884 | method: str, |
| 13885 | result: object_execution.ObjectExecutionResult, |
| 13886 | headers: dict[str, str], |
| 13887 | ) -> None: |
| 13888 | try: |
| 13889 | subject = _permission_subject(headers) |
| 13890 | object_ops_log.append_event( |
| 13891 | object_ops_log.EXECUTION_ERROR, |
| 13892 | { |
| 13893 | "object_id": object_id, |
| 13894 | "method": method, |
| 13895 | "error_type": result.error.type if result.error is not None else None, |
| 13896 | "message": (result.error.message if result.error is not |
Only the first 512 KB is shown. Download the zip for the whole file.