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_field_permissions.py · 12.0 KB · 337 lines
| 1 | """Schema-level field permissions for collection records. |
| 2 | |
| 3 | Collection policy decides whether a subject can reach a row. Field permissions |
| 4 | refine that decision so generated forms and APIs can share the same |
| 5 | ``edit/read/hidden`` contract. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | from pathlib import Path |
| 11 | from typing import Any, Iterable, Mapping |
| 12 | |
| 13 | import object_permissions |
| 14 | import object_schemas |
| 15 | from object_versions import DEFAULT_DATA_DIR |
| 16 | |
| 17 | EDIT = "edit" |
| 18 | READ = "read" |
| 19 | HIDDEN = "hidden" |
| 20 | |
| 21 | _ACCESS_RANK = { |
| 22 | HIDDEN: 0, |
| 23 | READ: 1, |
| 24 | EDIT: 2, |
| 25 | } |
| 26 | _EDIT_ALIASES = {"edit", "editable", "write", "writable", "update"} |
| 27 | _READ_ALIASES = {"read", "readonly", "read_only", "view", "visible"} |
| 28 | _HIDDEN_ALIASES = {"hidden", "hide", "deny", "denied", "none", "forbidden"} |
| 29 | _PRINCIPAL_PREFIXES = ("role:", "user:", "account:", "subscription:") |
| 30 | _SPECIAL_PRINCIPALS = {"public", "registered", "owner"} |
| 31 | |
| 32 | |
| 33 | def redact_record( |
| 34 | collection: str, |
| 35 | record: Mapping[str, Any], |
| 36 | *, |
| 37 | subject: object_permissions.PermissionSubject, |
| 38 | policy: object_permissions.PermissionPolicy, |
| 39 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 40 | roots: Iterable[Path] | None = None, |
| 41 | ) -> dict[str, Any]: |
| 42 | """Return ``record`` with schema-hidden fields removed.""" |
| 43 | constrained = _redaction_plan(collection, base_dir=base_dir, roots=roots) |
| 44 | visible = dict(record) |
| 45 | for name, entries, default in constrained: |
| 46 | if _resolve_access(entries, default, subject=subject, policy=policy, |
| 47 | record=record) == HIDDEN: |
| 48 | visible.pop(name, None) |
| 49 | return visible |
| 50 | |
| 51 | |
| 52 | # (str(base_dir), collection) -> (the schema object the plan was parsed from, |
| 53 | # the plan or the ValueError parsing raised). There is no invalidation here: |
| 54 | # object_schemas.get_schema returns the SAME object for as long as the schema |
| 55 | # file has the stat it was read under and a new one after any change, so an |
| 56 | # entry is used only while `get_schema` still hands back the object it was |
| 57 | # built from. A schema that object_schemas does not cache (derived, or read |
| 58 | # inside its racy window) is a new object on every call and is parsed every |
| 59 | # time, as before. |
| 60 | _REDACTION_PLANS: dict[tuple[str, str], tuple[Any, Any]] = {} |
| 61 | _REDACTION_PLANS_MAX = 512 |
| 62 | |
| 63 | |
| 64 | def _redaction_plan( |
| 65 | collection: str, |
| 66 | *, |
| 67 | base_dir: Path | str, |
| 68 | roots: Iterable[Path] | None, |
| 69 | ) -> list[tuple[str, list[tuple[str, str]], str | None]]: |
| 70 | """(name, principal entries, default) for every schema field that |
| 71 | declares permissions, in schema order: what ``redact_record`` asks about |
| 72 | per row, parsed once per schema instead of once per row (a 1,000-row |
| 73 | attention count parsed every field's permissions 1,000 times). |
| 74 | |
| 75 | Raises what parsing raised, every time, exactly as the per-row parse |
| 76 | did: a schema with a malformed ``permissions`` redacts nothing and |
| 77 | refuses (callers fail closed on ValueError).""" |
| 78 | try: |
| 79 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 80 | except object_schemas.SchemaNotFoundError: |
| 81 | return [] |
| 82 | try: |
| 83 | key = (str(base_dir), collection) |
| 84 | entry = _REDACTION_PLANS.get(key) |
| 85 | except TypeError: |
| 86 | key, entry = None, None |
| 87 | if entry is not None and entry[0] is schema: |
| 88 | plan = entry[1] |
| 89 | else: |
| 90 | try: |
| 91 | plan = _parse_redaction_plan(schema) |
| 92 | except ValueError as exc: |
| 93 | plan = exc |
| 94 | if key is not None: |
| 95 | if len(_REDACTION_PLANS) >= _REDACTION_PLANS_MAX: |
| 96 | _REDACTION_PLANS.clear() |
| 97 | _REDACTION_PLANS[key] = (schema, plan) |
| 98 | if isinstance(plan, ValueError): |
| 99 | raise ValueError(*plan.args) |
| 100 | return plan |
| 101 | |
| 102 | |
| 103 | def _parse_redaction_plan(schema: Mapping[str, Any]) -> list[tuple[str, list[tuple[str, str]], str | None]]: |
| 104 | fields = schema.get("fields", []) |
| 105 | if not isinstance(fields, list): |
| 106 | return [] |
| 107 | by_name = { |
| 108 | field["name"]: field |
| 109 | for field in fields |
| 110 | if isinstance(field, Mapping) and isinstance(field.get("name"), str) |
| 111 | } |
| 112 | plan = [] |
| 113 | for name, field in by_name.items(): |
| 114 | entries, default = _permission_entries( |
| 115 | field.get("permissions"), field_name=str(field.get("name", ""))) |
| 116 | if entries or default is not None: |
| 117 | plan.append((name, entries, default)) |
| 118 | return plan |
| 119 | |
| 120 | |
| 121 | def _resolve_access( |
| 122 | entries: list[tuple[str, str]], |
| 123 | default: str | None, |
| 124 | *, |
| 125 | subject: object_permissions.PermissionSubject, |
| 126 | policy: object_permissions.PermissionPolicy, |
| 127 | record: Mapping[str, Any] | None, |
| 128 | ) -> str | None: |
| 129 | if not entries and default is None: |
| 130 | return None |
| 131 | matches = [ |
| 132 | access |
| 133 | for principal, access in entries |
| 134 | if object_permissions.principal_matches(principal, subject, policy, record=record) |
| 135 | ] |
| 136 | if matches: |
| 137 | return min(matches, key=lambda access: _ACCESS_RANK[access]) |
| 138 | return default |
| 139 | |
| 140 | |
| 141 | def may_hide_a_field( |
| 142 | collection: str, |
| 143 | *, |
| 144 | subject: object_permissions.PermissionSubject, |
| 145 | policy: object_permissions.PermissionPolicy, |
| 146 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 147 | roots: Iterable[Path] | None = None, |
| 148 | ) -> bool: |
| 149 | """Could the schema hide ANY field of ``collection`` from ``subject`` in |
| 150 | some row? The question for a number computed over whole rows with no |
| 151 | viewer (object_attention.provider_shown_to): it may only reach someone |
| 152 | ``redact_record`` would never take a field from. |
| 153 | |
| 154 | Fail closed, so True whenever it cannot be ruled out: a field hidden |
| 155 | from a principal the subject matches; hidden from ``owner`` (anyone can |
| 156 | be a row's owner); hidden by ``default`` unless a principal the subject |
| 157 | matches whatever the row (not ``owner``) grants read or edit; or a schema |
| 158 | whose permissions cannot be read or parsed. No schema, or a schema with |
| 159 | no field permissions, hides nothing. |
| 160 | """ |
| 161 | try: |
| 162 | constrained = _redaction_plan(collection, base_dir=base_dir, roots=roots) |
| 163 | for _name, entries, default in constrained: |
| 164 | granted = False |
| 165 | for principal, access in entries: |
| 166 | if principal == "owner": |
| 167 | if access == HIDDEN: |
| 168 | return True |
| 169 | continue |
| 170 | if object_permissions.principal_matches(principal, subject, policy, record=None): |
| 171 | if access == HIDDEN: |
| 172 | return True |
| 173 | granted = True |
| 174 | if default == HIDDEN and not granted: |
| 175 | return True |
| 176 | except Exception: # noqa: BLE001 - unreadable or malformed: assume it hides |
| 177 | return True |
| 178 | return False |
| 179 | |
| 180 | |
| 181 | def denied_write_fields( |
| 182 | collection: str, |
| 183 | submitted_fields: Iterable[str], |
| 184 | *, |
| 185 | subject: object_permissions.PermissionSubject, |
| 186 | policy: object_permissions.PermissionPolicy, |
| 187 | record: Mapping[str, Any] | None = None, |
| 188 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 189 | roots: Iterable[Path] | None = None, |
| 190 | allow_id: bool = True, |
| 191 | ) -> list[str]: |
| 192 | """Return submitted schema fields that are not editable by ``subject``.""" |
| 193 | fields = _schema_field_map(collection, base_dir=base_dir, roots=roots) |
| 194 | if not fields: |
| 195 | return [] |
| 196 | |
| 197 | denied: list[str] = [] |
| 198 | for name in submitted_fields: |
| 199 | if allow_id and name == "id": |
| 200 | continue |
| 201 | field = fields.get(name) |
| 202 | if field is None: |
| 203 | continue |
| 204 | access = field_access(field, subject=subject, policy=policy, record=record) |
| 205 | if access is not None and access != EDIT: |
| 206 | denied.append(name) |
| 207 | return sorted(denied) |
| 208 | |
| 209 | |
| 210 | def field_access( |
| 211 | field: Mapping[str, Any], |
| 212 | *, |
| 213 | subject: object_permissions.PermissionSubject, |
| 214 | policy: object_permissions.PermissionPolicy, |
| 215 | record: Mapping[str, Any] | None = None, |
| 216 | ) -> str | None: |
| 217 | """Resolve one schema field's access for a subject. |
| 218 | |
| 219 | Missing permissions mean the field is not constrained by schema metadata. |
| 220 | When multiple principals match, the most restrictive access wins. |
| 221 | """ |
| 222 | permissions = field.get("permissions") |
| 223 | entries, default = _permission_entries(permissions, field_name=str(field.get("name", ""))) |
| 224 | return _resolve_access(entries, default, subject=subject, policy=policy, record=record) |
| 225 | |
| 226 | |
| 227 | def _schema_field_map( |
| 228 | collection: str, |
| 229 | *, |
| 230 | base_dir: Path | str, |
| 231 | roots: Iterable[Path] | None, |
| 232 | ) -> dict[str, Mapping[str, Any]]: |
| 233 | try: |
| 234 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 235 | except object_schemas.SchemaNotFoundError: |
| 236 | return {} |
| 237 | |
| 238 | fields = schema.get("fields", []) |
| 239 | if not isinstance(fields, list): |
| 240 | return {} |
| 241 | return { |
| 242 | field["name"]: field |
| 243 | for field in fields |
| 244 | if isinstance(field, Mapping) and isinstance(field.get("name"), str) |
| 245 | } |
| 246 | |
| 247 | |
| 248 | def _permission_entries( |
| 249 | permissions: Any, |
| 250 | *, |
| 251 | field_name: str, |
| 252 | ) -> tuple[list[tuple[str, str]], str | None]: |
| 253 | if permissions is None: |
| 254 | return [], None |
| 255 | if isinstance(permissions, str): |
| 256 | return [], _normalize_access(permissions, field_name=field_name) |
| 257 | if not isinstance(permissions, Mapping): |
| 258 | raise ValueError(f"Schema field '{field_name}' permissions must be an object") |
| 259 | |
| 260 | entries: list[tuple[str, str]] = [] |
| 261 | default: str | None = None |
| 262 | |
| 263 | roles = permissions.get("roles") |
| 264 | if isinstance(roles, Mapping): |
| 265 | for role, access in roles.items(): |
| 266 | entries.append((_principal_from_key(str(role)), _access_from_value(access, field_name=field_name))) |
| 267 | |
| 268 | for key, value in permissions.items(): |
| 269 | if key == "roles": |
| 270 | continue |
| 271 | if not isinstance(key, str) or not key.strip(): |
| 272 | raise ValueError(f"Schema field '{field_name}' has an invalid permission principal") |
| 273 | normalized_key = key.strip() |
| 274 | if normalized_key == "default": |
| 275 | default = _access_from_value(value, field_name=field_name) |
| 276 | continue |
| 277 | if _access_key(normalized_key) is not None and isinstance(value, (list, tuple, set)): |
| 278 | access = _access_key(normalized_key) |
| 279 | assert access is not None |
| 280 | for principal in value: |
| 281 | if not isinstance(principal, str) or not principal.strip(): |
| 282 | raise ValueError( |
| 283 | f"Schema field '{field_name}' has an invalid permission principal" |
| 284 | ) |
| 285 | entries.append((_principal_from_key(principal), access)) |
| 286 | continue |
| 287 | entries.append((_principal_from_key(normalized_key), _access_from_value(value, field_name=field_name))) |
| 288 | |
| 289 | return entries, default |
| 290 | |
| 291 | |
| 292 | def _access_from_value(value: Any, *, field_name: str) -> str: |
| 293 | if isinstance(value, str): |
| 294 | return _normalize_access(value, field_name=field_name) |
| 295 | if isinstance(value, Mapping): |
| 296 | access = value.get("access", value.get("mode")) |
| 297 | if isinstance(access, str): |
| 298 | return _normalize_access(access, field_name=field_name) |
| 299 | raise ValueError(f"Schema field '{field_name}' permission access must be edit, read, or hidden") |
| 300 | |
| 301 | |
| 302 | def _normalize_access(value: str, *, field_name: str) -> str: |
| 303 | text = value.strip().lower().replace("-", "_") |
| 304 | if text in _EDIT_ALIASES: |
| 305 | return EDIT |
| 306 | if text in _READ_ALIASES: |
| 307 | return READ |
| 308 | if text in _HIDDEN_ALIASES: |
| 309 | return HIDDEN |
| 310 | raise ValueError(f"Schema field '{field_name}' permission access must be edit, read, or hidden") |
| 311 | |
| 312 | |
| 313 | def access_level(value: str) -> str | None: |
| 314 | """The level (edit, read or hidden) the engine reads a spelling as, or None. |
| 315 | |
| 316 | The engine accepts synonyms ("write", "readonly", "none"); DRON defines |
| 317 | the three levels only, and a package install says which one to write.""" |
| 318 | return _access_key(value) |
| 319 | |
| 320 | |
| 321 | def _access_key(value: str) -> str | None: |
| 322 | try: |
| 323 | return _normalize_access(value, field_name="") |
| 324 | except ValueError: |
| 325 | return None |
| 326 | |
| 327 | |
| 328 | def _principal_from_key(value: str) -> str: |
| 329 | principal = value.strip() |
| 330 | lowered = principal.lower() |
| 331 | if lowered in {"anonymous", "anon"}: |
| 332 | return "public" |
| 333 | if lowered in {"authenticated", "signed_in", "signed-in"}: |
| 334 | return "registered" |
| 335 | if lowered in _SPECIAL_PRINCIPALS or any(lowered.startswith(prefix) for prefix in _PRINCIPAL_PREFIXES): |
| 336 | return principal |
| 337 | return f"role:{principal}" |