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_access.py · 23.9 KB · 523 lines
| 1 | """The permission engine, asked from inside an object. |
| 2 | |
| 3 | A page or action that reads a record with ``object_records`` gets the raw |
| 4 | row: no rule, no row filter, no owner check. The generic collection API |
| 5 | asks ``object_permissions.check_permission`` about every row it returns; |
| 6 | an object that reads storage directly is the ONLY gate in front of what it |
| 7 | shows or changes, and on 2026-11-28 sixteen of them were found showing or |
| 8 | changing other users' records (bug-reports/2026-11-28-*-no-owner-check, |
| 9 | *-exposes-any-order, ...). Every one of them already had the answer one |
| 10 | call away -- the same policy file the API enforces -- and had instead |
| 11 | either no check or a hand-written ``owner_id == user_id`` that disagreed |
| 12 | with the API about admins, roles assigned in the policy, and unowned rows. |
| 13 | |
| 14 | So this is that call, and nothing else:: |
| 15 | |
| 16 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 17 | order = access.get("orders", order_id) # None: missing OR refused |
| 18 | if order is None: |
| 19 | return not_found() |
| 20 | lines = access.visible("order_lines", rows) # the rows the API would list |
| 21 | if not access.can("update", "scans", scan): # before a write |
| 22 | return {"status": 404, ...} |
| 23 | |
| 24 | It answers exactly what ``GET /collections/{c}/records/{id}`` (or the PUT) |
| 25 | would answer for the same subject under the active policy, with two |
| 26 | deliberate differences, both towards refusing: |
| 27 | |
| 28 | - **No identity is anonymous.** ``request["_identity"]`` is set by the |
| 29 | server on every HTTP execution and cannot be supplied by the client (the |
| 30 | server overwrites it). A request without one is an in-process call, and |
| 31 | an in-process caller that wants authority says so with an explicit |
| 32 | identity (``{"user_id": "system", "roles": ["admin"]}``) rather than |
| 33 | getting it by omission. Objects that forward a request to another object |
| 34 | forward ``_identity`` with it (site_return_form does). |
| 35 | - **An unreadable or invalid policy refuses everything**, admins included: |
| 36 | without the policy there is no way to know who the admin roles are. |
| 37 | |
| 38 | Project and record-share grants ARE resolved, by the same function the |
| 39 | server uses (``with_grants`` below): ``_identity`` carries only the four |
| 40 | fields, so Access reads the subject's ``project_access``, ``projects`` and |
| 41 | ``record_shares`` rows itself, and a rule that matches through |
| 42 | ``$accessible_projects`` or ``$shared_records`` matches here exactly as it |
| 43 | does for the record API. Until 2026-12-02 they were not, so a project |
| 44 | member or a sharee the API allowed was refused here, and an object that |
| 45 | writes a request's pointer could not ask ``relation_refusal`` without |
| 46 | refusing them too. |
| 47 | |
| 48 | And one difference that goes the OTHER way, for ``update`` and ``delete``. |
| 49 | The record API asks twice: once at the collection level with no record |
| 50 | (so a missing id cannot be told from a forbidden one), then with the |
| 51 | record. ``can(action, collection, record)`` asks only the second. Where a |
| 52 | collection has NO rule for the action, the API's first question is a 403, |
| 53 | while the engine, shown the record, falls through to the owner fallback |
| 54 | and says yes to whoever ``owner_id`` / ``user_id`` / ``created_by`` names. |
| 55 | So "this package grants no update" did not mean ``can("update", ...)`` was |
| 56 | false for the owner (measured on template_runs, wallet_entries and 27 |
| 57 | others, 2026-11-28). A collection that must be read-only to its owners |
| 58 | ships an ``owner_fallback`` rule that says so |
| 59 | (object_permissions._owner_fallback_opt_out, docs/permissions-model.md |
| 60 | "Ownership"); a gate must not infer it from the absence of a grant. |
| 61 | |
| 62 | ``get`` answers None for a missing record and for a refused one alike, so |
| 63 | an object using it cannot become an existence oracle by accident: a 404 |
| 64 | for "no such scan" and a 403 for "someone else's scan" tells a prober |
| 65 | which ids are real. |
| 66 | |
| 67 | ``can`` and ``get`` do not redact fields (rule ``fields`` / ``denied_fields``, |
| 68 | schema field permissions): an object renders the fields it chooses. An |
| 69 | object that renders or forwards a field a rule hides must ask ``readable``, |
| 70 | which answers with the row cut down to what the subject may read, or None. |
| 71 | |
| 72 | What was rejected: sixteen hand-written owner checks (the existing ones |
| 73 | already disagreed with each other about admins and about unowned rows -- |
| 74 | site_kitchen shows an order with a blank owner to everybody, the orders |
| 75 | API shows it to nobody); and routing objects through the HTTP API in |
| 76 | process (an object would need a credential to present, and the policy |
| 77 | answer is the same function either way). |
| 78 | """ |
| 79 | |
| 80 | from __future__ import annotations |
| 81 | |
| 82 | import os |
| 83 | from pathlib import Path |
| 84 | from typing import Any, Iterable, Mapping |
| 85 | |
| 86 | import object_collections |
| 87 | import object_field_permissions |
| 88 | import object_permission_store |
| 89 | import object_permissions |
| 90 | import object_records |
| 91 | import object_schemas |
| 92 | |
| 93 | READ = object_permissions.READ |
| 94 | UPDATE = object_permissions.UPDATE |
| 95 | CREATE = object_permissions.CREATE |
| 96 | DELETE = object_permissions.DELETE |
| 97 | |
| 98 | |
| 99 | PERMISSION_ENFORCEMENT_ENV = "DBBASIC_ENABLE_PERMISSION_ENFORCEMENT" |
| 100 | TRUE_VALUES = frozenset({"1", "true", "yes", "on"}) |
| 101 | |
| 102 | |
| 103 | def enforcement_enabled() -> bool: |
| 104 | """Is the permission policy enforced? THE answer the server gives |
| 105 | (`/permissions/status` mode "enforced"): object_server's |
| 106 | `_permission_enforcement_enabled` is this function. A process that is not |
| 107 | the server (the daemon) reads the same setting through here. Audit-only |
| 108 | and off are both False: the record API then serves every row and field, |
| 109 | so a derived view (notification, feed, history) is not narrower.""" |
| 110 | return os.environ.get(PERMISSION_ENFORCEMENT_ENV, "").strip().lower() in TRUE_VALUES |
| 111 | |
| 112 | |
| 113 | def apply_read_decision( |
| 114 | record: Mapping[str, Any], |
| 115 | decision: object_permissions.PermissionDecision, |
| 116 | *, |
| 117 | collection: str, |
| 118 | subject: object_permissions.PermissionSubject, |
| 119 | policy: object_permissions.PermissionPolicy, |
| 120 | base_dir: Path | str, |
| 121 | ) -> dict[str, Any]: |
| 122 | """``record`` cut down to the fields ``decision`` (an allowed READ) lets |
| 123 | ``subject`` see: the matched rule's ``fields`` allow-list and |
| 124 | ``denied_fields``, then the schema's per-field permissions. The record |
| 125 | API's redaction (object_server._apply_record_field_policy) is this |
| 126 | function, so there is one implementation of field visibility.""" |
| 127 | filtered = dict(record) |
| 128 | if decision.fields is not None: |
| 129 | filtered = {key: value for key, value in filtered.items() if key in decision.fields} |
| 130 | for field in decision.denied_fields: |
| 131 | filtered.pop(field, None) |
| 132 | return object_field_permissions.redact_record( |
| 133 | collection, filtered, subject=subject, policy=policy, base_dir=base_dir) |
| 134 | |
| 135 | |
| 136 | def access_for_user(user_id: str, *, base_dir: Path | str) -> "Access | None": |
| 137 | """An Access for a stored user, as the server would see them when they |
| 138 | sign in; None when the user is unknown, not active, or the identity |
| 139 | store cannot be read (a caller that cannot say who someone is must not |
| 140 | show them anything).""" |
| 141 | import object_identity |
| 142 | try: |
| 143 | user = object_identity.get_user(str(user_id), base_dir=base_dir) |
| 144 | except (LookupError, OSError, ValueError, TypeError): |
| 145 | return None |
| 146 | if user.get("status") != "active": |
| 147 | return None |
| 148 | return Access({"user_id": user.get("user_id"), "account_id": user.get("account_id"), |
| 149 | "roles": user.get("roles"), "subscriptions": user.get("subscriptions")}, |
| 150 | base_dir=base_dir) |
| 151 | |
| 152 | |
| 153 | def subject_from_identity(identity: Mapping[str, Any] | None) -> object_permissions.PermissionSubject: |
| 154 | """The subject the server described in ``request["_identity"]``. |
| 155 | |
| 156 | Only the four fields the server sets are read; anything else in the |
| 157 | mapping (a test's ``is_admin``, a client's guess) is ignored. A malformed |
| 158 | identity is anonymous. |
| 159 | """ |
| 160 | if not isinstance(identity, Mapping): |
| 161 | return object_permissions.PermissionSubject.anonymous() |
| 162 | |
| 163 | def _names(value): |
| 164 | # A list, as the server sends it. A bare string is not split into |
| 165 | # characters, and anything else is no roles at all. |
| 166 | return [str(item) for item in value] if isinstance(value, (list, tuple)) else [] |
| 167 | |
| 168 | try: |
| 169 | return object_permissions.subject_from_dict({ |
| 170 | "user_id": identity.get("user_id") or None, |
| 171 | "account_id": identity.get("account_id") or None, |
| 172 | "roles": _names(identity.get("roles")), |
| 173 | "subscriptions": _names(identity.get("subscriptions")), |
| 174 | }) |
| 175 | except (TypeError, ValueError): |
| 176 | return object_permissions.PermissionSubject.anonymous() |
| 177 | |
| 178 | |
| 179 | PROJECT_ACCESS_COLLECTION = "project_access" |
| 180 | PROJECTS_COLLECTION = "projects" |
| 181 | RECORD_SHARES_COLLECTION = "record_shares" |
| 182 | |
| 183 | |
| 184 | def _rows_where_or_empty(collection: str, field: str, value: Any, *, |
| 185 | base_dir: Path | str) -> list[dict[str, str]]: |
| 186 | """The rows of ``collection`` whose ``field`` equals ``value``, read |
| 187 | fresh (object_records.read_collection_records_where: the current |
| 188 | stat-checked snapshot, never a cache of its own). A collection that is |
| 189 | not installed or cannot be read grants nothing.""" |
| 190 | try: |
| 191 | return object_records.read_collection_records_where( |
| 192 | collection, field, value, base_dir=base_dir) |
| 193 | except ( |
| 194 | object_collections.CollectionNotFoundError, |
| 195 | object_collections.InvalidCollectionNameError, |
| 196 | OSError, |
| 197 | ValueError, |
| 198 | ): |
| 199 | return [] |
| 200 | |
| 201 | |
| 202 | def with_accessible_projects( |
| 203 | subject: object_permissions.PermissionSubject, *, base_dir: Path | str, |
| 204 | ) -> object_permissions.PermissionSubject: |
| 205 | """Resolve the subject's project grants and ownership before checks run. |
| 206 | |
| 207 | Grants live in the plain ``project_access`` records collection |
| 208 | (project_id, user_id, permission), so sharing is data: browseable, |
| 209 | audited, and versioned like every other record. Rules opt in with the |
| 210 | ``$accessible_projects`` row-filter value; ``$owned_projects`` |
| 211 | resolves from the projects collection's owner_id, which is what lets |
| 212 | "owners may share their own projects" stay a plain row filter. |
| 213 | ``$writable_projects`` narrows accessible grants to rows whose |
| 214 | ``permission`` is ``"write"``, for rules and transition guards that |
| 215 | need more than read-only membership. |
| 216 | |
| 217 | The one implementation: the server resolves every request's subject |
| 218 | with it (object_server._with_accessible_projects) and so does Access. |
| 219 | """ |
| 220 | if subject.user_id is None: |
| 221 | return subject |
| 222 | |
| 223 | access_rows = [ |
| 224 | record |
| 225 | for record in _rows_where_or_empty(PROJECT_ACCESS_COLLECTION, "user_id", subject.user_id, |
| 226 | base_dir=base_dir) |
| 227 | if record.get("project_id") |
| 228 | ] |
| 229 | project_ids = [record["project_id"] for record in access_rows] |
| 230 | writable_project_ids = [ |
| 231 | record["project_id"] for record in access_rows if record.get("permission") == "write" |
| 232 | ] |
| 233 | owned_project_ids = [ |
| 234 | record["id"] |
| 235 | for record in _rows_where_or_empty(PROJECTS_COLLECTION, "owner_id", subject.user_id, |
| 236 | base_dir=base_dir) |
| 237 | if record.get("id") |
| 238 | ] |
| 239 | if not project_ids and not owned_project_ids: |
| 240 | return subject |
| 241 | return subject.with_projects( |
| 242 | dict.fromkeys(project_ids), |
| 243 | dict.fromkeys(owned_project_ids), |
| 244 | dict.fromkeys(writable_project_ids), |
| 245 | ) |
| 246 | |
| 247 | |
| 248 | def with_shared_records( |
| 249 | subject: object_permissions.PermissionSubject, *, base_dir: Path | str, |
| 250 | ) -> object_permissions.PermissionSubject: |
| 251 | """Resolve the subject's per-collection record shares before checks run. |
| 252 | |
| 253 | The generic sibling of ``with_accessible_projects``: grants live in the |
| 254 | plain ``record_shares`` collection (collection, record_id, user_id, |
| 255 | permission), written only by the owner-checked /api/share endpoint. A rule |
| 256 | opts a collection into sharing with a ``{"id": "$shared_records"}`` row |
| 257 | filter (or ``$writable_shared_records`` for write). Keyed by collection so |
| 258 | the collection-aware resolver returns only this collection's shared ids. |
| 259 | """ |
| 260 | if subject.user_id is None: |
| 261 | return subject |
| 262 | shared: dict[str, list[str]] = {} |
| 263 | writable: dict[str, list[str]] = {} |
| 264 | for row in _rows_where_or_empty(RECORD_SHARES_COLLECTION, "user_id", subject.user_id, |
| 265 | base_dir=base_dir): |
| 266 | coll, rid = row.get("collection"), row.get("record_id") |
| 267 | if not coll or not rid: |
| 268 | continue |
| 269 | shared.setdefault(coll, []).append(rid) |
| 270 | if row.get("permission") == "write": |
| 271 | writable.setdefault(coll, []).append(rid) |
| 272 | if not shared: |
| 273 | return subject |
| 274 | return subject.with_shares( |
| 275 | {k: list(dict.fromkeys(v)) for k, v in shared.items()}, |
| 276 | {k: list(dict.fromkeys(v)) for k, v in writable.items()}, |
| 277 | ) |
| 278 | |
| 279 | |
| 280 | def with_grants( |
| 281 | subject: object_permissions.PermissionSubject, *, base_dir: Path | str, |
| 282 | ) -> object_permissions.PermissionSubject: |
| 283 | """The subject with its project grants and record shares resolved: what |
| 284 | the server checks every request with, and what Access checks with.""" |
| 285 | return with_shared_records(with_accessible_projects(subject, base_dir=base_dir), |
| 286 | base_dir=base_dir) |
| 287 | |
| 288 | |
| 289 | class Access: |
| 290 | """One subject and the active policy, loaded once per request.""" |
| 291 | |
| 292 | def __init__(self, identity: Mapping[str, Any] | None, *, base_dir: Path | str): |
| 293 | self.base_dir = base_dir |
| 294 | self.subject = with_grants(subject_from_identity(identity), base_dir=base_dir) |
| 295 | try: |
| 296 | self.policy: object_permissions.PermissionPolicy | None = ( |
| 297 | object_permission_store.load_policy(base_dir)) |
| 298 | except (OSError, ValueError, TypeError): |
| 299 | self.policy = None |
| 300 | |
| 301 | @property |
| 302 | def user_id(self) -> str: |
| 303 | return self.subject.user_id or "" |
| 304 | |
| 305 | @property |
| 306 | def signed_in(self) -> bool: |
| 307 | return self.subject.is_authenticated |
| 308 | |
| 309 | @property |
| 310 | def is_admin(self) -> bool: |
| 311 | return self.policy is not None and object_permissions.subject_has_admin_role( |
| 312 | self.subject, self.policy) |
| 313 | |
| 314 | def can(self, action: str, collection: str, record: Mapping[str, Any] | None) -> bool: |
| 315 | """May this subject do ``action`` to this record of ``collection``? |
| 316 | |
| 317 | ``record=None`` is the collection-level question; with a row filter |
| 318 | in play the engine answers "allowed, subject to the filter", so a |
| 319 | caller that has the record must pass it. |
| 320 | """ |
| 321 | if self.policy is None: |
| 322 | return False |
| 323 | try: |
| 324 | decision = object_permissions.check_permission( |
| 325 | self.subject, action, policy=self.policy, |
| 326 | collection=collection, record=record) |
| 327 | except (TypeError, ValueError): |
| 328 | return False |
| 329 | return decision.allowed |
| 330 | |
| 331 | def readable(self, collection: str, record: Mapping[str, Any] | None) -> dict[str, Any] | None: |
| 332 | """``record`` as this subject may read it: None when the row itself |
| 333 | is refused (or the policy or schema cannot be read), else a copy |
| 334 | with every field a rule or the schema hides from them removed. What |
| 335 | a notification, feed entry or history line may be built from.""" |
| 336 | if self.policy is None or not isinstance(record, Mapping): |
| 337 | return None |
| 338 | try: |
| 339 | decision = object_permissions.check_permission( |
| 340 | self.subject, READ, policy=self.policy, |
| 341 | collection=collection, record=record) |
| 342 | if not decision.allowed: |
| 343 | return None |
| 344 | return apply_read_decision( |
| 345 | record, decision, collection=collection, subject=self.subject, |
| 346 | policy=self.policy, base_dir=self.base_dir) |
| 347 | except (TypeError, ValueError, OSError): |
| 348 | return None |
| 349 | |
| 350 | def reads_every_row(self, collection: str) -> bool: |
| 351 | """May this subject read every row of ``collection``, whole? |
| 352 | |
| 353 | The question for a number computed over all of them (a code |
| 354 | attention provider's count). False whenever it cannot be proved: |
| 355 | see object_permissions.subject_reads_every_row. |
| 356 | """ |
| 357 | try: |
| 358 | return object_permissions.subject_reads_every_row( |
| 359 | self.subject, collection, policy=self.policy) |
| 360 | except (TypeError, ValueError): |
| 361 | return False |
| 362 | |
| 363 | def get(self, collection: str, record_id: str, action: str = READ) -> dict[str, Any] | None: |
| 364 | """The record, or None when it is missing OR this subject may not |
| 365 | ``action`` it -- the same answer for both on purpose. |
| 366 | |
| 367 | Storage errors other than "no such record" propagate: an unreadable |
| 368 | collection is not the same fact as an empty one, and the caller |
| 369 | decides how to refuse. |
| 370 | """ |
| 371 | if not record_id: |
| 372 | return None |
| 373 | try: |
| 374 | record = object_records.get_collection_record( |
| 375 | collection, record_id, base_dir=self.base_dir) |
| 376 | except (object_records.RecordNotFoundError, |
| 377 | object_records.InvalidRecordIdError, |
| 378 | object_collections.CollectionNotFoundError): |
| 379 | return None |
| 380 | if not record or not self.can(action, collection, record): |
| 381 | return None |
| 382 | return record |
| 383 | |
| 384 | def visible(self, collection: str, rows: Iterable[Mapping[str, Any]], |
| 385 | action: str = READ) -> list: |
| 386 | """The rows this subject may ``action``, in their original order. |
| 387 | |
| 388 | An admin is decided before any rule is read, so for one the answer |
| 389 | is every row without asking the engine row by row (a 20,000-row |
| 390 | page_views fold should not cost 20,000 calls to learn that). |
| 391 | """ |
| 392 | if self.is_admin: |
| 393 | return list(rows) |
| 394 | return [row for row in rows if self.can(action, collection, row)] |
| 395 | |
| 396 | def relation_refusal(self, collection: str, record: Mapping[str, Any], |
| 397 | existing: Mapping[str, Any] | None = None): |
| 398 | """The record API's answer to a write of ``record`` that points a |
| 399 | relation at a record this subject may not act on: ``(status, |
| 400 | body)``, or None when every declared pointer is allowed. |
| 401 | |
| 402 | Asked by an object about to write a row through ``object_records`` |
| 403 | with pointers it took from the request, so the row points only |
| 404 | where ``POST /collections/{collection}/records`` would have let the |
| 405 | same subject point it. See ``relation_refusal`` below. |
| 406 | |
| 407 | Unlike the record API, a missing target is refused here too, with |
| 408 | the same answer as one the subject may not read: the object has not |
| 409 | yet written anything (bytes, a file) that relation validation would |
| 410 | leave behind, and a missing id and a hidden one stay one answer. |
| 411 | """ |
| 412 | return relation_refusal(collection, record, subject=self.subject, |
| 413 | policy=self.policy, base_dir=self.base_dir, |
| 414 | existing=existing, refuse_missing=True) |
| 415 | |
| 416 | |
| 417 | def relation_requirements(collection: str, *, base_dir: Path | str) -> list[tuple[str, str, str]]: |
| 418 | """(field, target collection, action) for every relation the schema says |
| 419 | the writer must be allowed to act on: ``"relation": {"collection": ..., |
| 420 | "requires": "read" | "update"}`` (docs/permissions-model.md, "Pointing at |
| 421 | a record you may not act on"). Empty for a collection with no schema.""" |
| 422 | try: |
| 423 | schema = object_schemas.get_schema(collection, base_dir=base_dir) |
| 424 | except (object_schemas.InvalidSchemaNameError, object_schemas.SchemaNotFoundError): |
| 425 | return [] |
| 426 | fields = schema.get("fields") if isinstance(schema, dict) else None |
| 427 | required = [] |
| 428 | for field in fields if isinstance(fields, list) else []: |
| 429 | if not isinstance(field, dict) or not isinstance(field.get("name"), str): |
| 430 | continue |
| 431 | relation = field.get("relation") |
| 432 | if not isinstance(relation, dict): |
| 433 | continue |
| 434 | action = relation.get("requires") |
| 435 | target = relation.get("collection") |
| 436 | if isinstance(action, str) and action and isinstance(target, str) and target: |
| 437 | required.append((field["name"], target, action)) |
| 438 | return required |
| 439 | |
| 440 | |
| 441 | def relation_refusal( |
| 442 | collection: str, |
| 443 | record: Mapping[str, Any], |
| 444 | *, |
| 445 | subject: object_permissions.PermissionSubject, |
| 446 | policy: object_permissions.PermissionPolicy | None, |
| 447 | base_dir: Path | str, |
| 448 | existing: Mapping[str, Any] | None = None, |
| 449 | refuse_missing: bool = False, |
| 450 | ): |
| 451 | """Refuse a write that points a relation at a record ``subject`` may not |
| 452 | act on: ``(status, body)``, or None to let it through. |
| 453 | |
| 454 | The one implementation of ``relation.requires``, for the record API |
| 455 | (object_server, which sends what this returns) and for every object |
| 456 | that writes such a row itself (``Access.relation_refusal``). The rules |
| 457 | decide who may write THIS row; this decides whether the writer may touch |
| 458 | the row it points at. Each relation that declares ``requires`` and has a |
| 459 | value is checked on create, and on update only when the value changes |
| 460 | (a row may keep pointing where it was allowed to point). The target is |
| 461 | read under the same policy for the same subject: the write goes ahead |
| 462 | only if the engine lets the subject ``read`` it and, for ``update``, |
| 463 | ``update`` it. |
| 464 | |
| 465 | Fails closed: a target that cannot be read is 503, a policy that cannot |
| 466 | be evaluated 500 (and one that could not be loaded, None, 503). A target the subject may not even read is answered |
| 467 | exactly like a missing one (the 400 relation validation gives), so this |
| 468 | is no oracle for which ids exist. A missing target is left to that |
| 469 | validation, unless ``refuse_missing``, when it gets that same 400 here. |
| 470 | """ |
| 471 | for name, target, action in relation_requirements(collection, base_dir=base_dir): |
| 472 | raw = record.get(name) |
| 473 | value = "" if raw is None else str(raw) |
| 474 | if not value.strip(): |
| 475 | continue |
| 476 | if existing is not None and value == ("" if existing.get(name) is None else str(existing.get(name))): |
| 477 | continue |
| 478 | if policy is None: |
| 479 | return 503, {"status": "error", |
| 480 | "error": (f"The permission policy is unreadable, so whether you may " |
| 481 | f"point '{name}' at {target}/{value} cannot be checked. " |
| 482 | "Nothing was written.")} |
| 483 | missing = (400, {"status": "error", |
| 484 | "error": f"Record field '{name}' references a missing record: {target}/{value}"}) |
| 485 | try: |
| 486 | parent = object_records.get_collection_record(target, value, base_dir=base_dir) |
| 487 | except ( |
| 488 | object_collections.CollectionNotFoundError, |
| 489 | object_collections.InvalidCollectionNameError, |
| 490 | object_records.RecordNotFoundError, |
| 491 | object_records.InvalidRecordIdError, |
| 492 | ): |
| 493 | if refuse_missing: |
| 494 | return missing |
| 495 | continue # relation validation in object_records answers a missing target |
| 496 | except Exception: |
| 497 | return 503, {"status": "error", |
| 498 | "error": (f"{target} could not be read, so whether you may point " |
| 499 | f"'{name}' at {target}/{value} cannot be checked. Nothing " |
| 500 | "was written.")} |
| 501 | try: |
| 502 | readable = object_permissions.check_permission( |
| 503 | subject, object_permissions.READ, policy=policy, collection=target, record=parent |
| 504 | ).allowed |
| 505 | allowed = readable and ( |
| 506 | action == object_permissions.READ |
| 507 | or object_permissions.check_permission( |
| 508 | subject, action, policy=policy, collection=target, record=parent |
| 509 | ).allowed |
| 510 | ) |
| 511 | except ValueError as exc: |
| 512 | return 500, {"status": "error", "error": f"Permission policy is invalid: {exc}"} |
| 513 | if not readable: |
| 514 | return missing |
| 515 | if not allowed: |
| 516 | return 403, {"status": "error", |
| 517 | "error": (f"Record field '{name}' points at {target}/{value}, which you " |
| 518 | f"may not {action}. A {collection} row acts on the record it " |
| 519 | f"points at, so only someone allowed to {action} that record " |
| 520 | "may write one."), |
| 521 | "code": "forbidden", |
| 522 | "field": name} |
| 523 | return None |