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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_field_permissions.py · 7.0 KB · 212 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 | fields = _schema_field_map(collection, base_dir=base_dir, roots=roots) |
| 44 | if not fields: |
| 45 | return dict(record) |
| 46 | |
| 47 | visible = dict(record) |
| 48 | for name, field in fields.items(): |
| 49 | if field_access(field, subject=subject, policy=policy, record=record) == HIDDEN: |
| 50 | visible.pop(name, None) |
| 51 | return visible |
| 52 | |
| 53 | |
| 54 | def denied_write_fields( |
| 55 | collection: str, |
| 56 | submitted_fields: Iterable[str], |
| 57 | *, |
| 58 | subject: object_permissions.PermissionSubject, |
| 59 | policy: object_permissions.PermissionPolicy, |
| 60 | record: Mapping[str, Any] | None = None, |
| 61 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 62 | roots: Iterable[Path] | None = None, |
| 63 | allow_id: bool = True, |
| 64 | ) -> list[str]: |
| 65 | """Return submitted schema fields that are not editable by ``subject``.""" |
| 66 | fields = _schema_field_map(collection, base_dir=base_dir, roots=roots) |
| 67 | if not fields: |
| 68 | return [] |
| 69 | |
| 70 | denied: list[str] = [] |
| 71 | for name in submitted_fields: |
| 72 | if allow_id and name == "id": |
| 73 | continue |
| 74 | field = fields.get(name) |
| 75 | if field is None: |
| 76 | continue |
| 77 | access = field_access(field, subject=subject, policy=policy, record=record) |
| 78 | if access is not None and access != EDIT: |
| 79 | denied.append(name) |
| 80 | return sorted(denied) |
| 81 | |
| 82 | |
| 83 | def field_access( |
| 84 | field: Mapping[str, Any], |
| 85 | *, |
| 86 | subject: object_permissions.PermissionSubject, |
| 87 | policy: object_permissions.PermissionPolicy, |
| 88 | record: Mapping[str, Any] | None = None, |
| 89 | ) -> str | None: |
| 90 | """Resolve one schema field's access for a subject. |
| 91 | |
| 92 | Missing permissions mean the field is not constrained by schema metadata. |
| 93 | When multiple principals match, the most restrictive access wins. |
| 94 | """ |
| 95 | permissions = field.get("permissions") |
| 96 | entries, default = _permission_entries(permissions, field_name=str(field.get("name", ""))) |
| 97 | if not entries and default is None: |
| 98 | return None |
| 99 | |
| 100 | matches = [ |
| 101 | access |
| 102 | for principal, access in entries |
| 103 | if object_permissions.principal_matches(principal, subject, policy, record=record) |
| 104 | ] |
| 105 | if matches: |
| 106 | return min(matches, key=lambda access: _ACCESS_RANK[access]) |
| 107 | return default |
| 108 | |
| 109 | |
| 110 | def _schema_field_map( |
| 111 | collection: str, |
| 112 | *, |
| 113 | base_dir: Path | str, |
| 114 | roots: Iterable[Path] | None, |
| 115 | ) -> dict[str, Mapping[str, Any]]: |
| 116 | try: |
| 117 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 118 | except object_schemas.SchemaNotFoundError: |
| 119 | return {} |
| 120 | |
| 121 | fields = schema.get("fields", []) |
| 122 | if not isinstance(fields, list): |
| 123 | return {} |
| 124 | return { |
| 125 | field["name"]: field |
| 126 | for field in fields |
| 127 | if isinstance(field, Mapping) and isinstance(field.get("name"), str) |
| 128 | } |
| 129 | |
| 130 | |
| 131 | def _permission_entries( |
| 132 | permissions: Any, |
| 133 | *, |
| 134 | field_name: str, |
| 135 | ) -> tuple[list[tuple[str, str]], str | None]: |
| 136 | if permissions is None: |
| 137 | return [], None |
| 138 | if isinstance(permissions, str): |
| 139 | return [], _normalize_access(permissions, field_name=field_name) |
| 140 | if not isinstance(permissions, Mapping): |
| 141 | raise ValueError(f"Schema field '{field_name}' permissions must be an object") |
| 142 | |
| 143 | entries: list[tuple[str, str]] = [] |
| 144 | default: str | None = None |
| 145 | |
| 146 | roles = permissions.get("roles") |
| 147 | if isinstance(roles, Mapping): |
| 148 | for role, access in roles.items(): |
| 149 | entries.append((_principal_from_key(str(role)), _access_from_value(access, field_name=field_name))) |
| 150 | |
| 151 | for key, value in permissions.items(): |
| 152 | if key == "roles": |
| 153 | continue |
| 154 | if not isinstance(key, str) or not key.strip(): |
| 155 | raise ValueError(f"Schema field '{field_name}' has an invalid permission principal") |
| 156 | normalized_key = key.strip() |
| 157 | if normalized_key == "default": |
| 158 | default = _access_from_value(value, field_name=field_name) |
| 159 | continue |
| 160 | if _access_key(normalized_key) is not None and isinstance(value, (list, tuple, set)): |
| 161 | access = _access_key(normalized_key) |
| 162 | assert access is not None |
| 163 | for principal in value: |
| 164 | if not isinstance(principal, str) or not principal.strip(): |
| 165 | raise ValueError( |
| 166 | f"Schema field '{field_name}' has an invalid permission principal" |
| 167 | ) |
| 168 | entries.append((_principal_from_key(principal), access)) |
| 169 | continue |
| 170 | entries.append((_principal_from_key(normalized_key), _access_from_value(value, field_name=field_name))) |
| 171 | |
| 172 | return entries, default |
| 173 | |
| 174 | |
| 175 | def _access_from_value(value: Any, *, field_name: str) -> str: |
| 176 | if isinstance(value, str): |
| 177 | return _normalize_access(value, field_name=field_name) |
| 178 | if isinstance(value, Mapping): |
| 179 | access = value.get("access", value.get("mode")) |
| 180 | if isinstance(access, str): |
| 181 | return _normalize_access(access, field_name=field_name) |
| 182 | raise ValueError(f"Schema field '{field_name}' permission access must be edit, read, or hidden") |
| 183 | |
| 184 | |
| 185 | def _normalize_access(value: str, *, field_name: str) -> str: |
| 186 | text = value.strip().lower().replace("-", "_") |
| 187 | if text in _EDIT_ALIASES: |
| 188 | return EDIT |
| 189 | if text in _READ_ALIASES: |
| 190 | return READ |
| 191 | if text in _HIDDEN_ALIASES: |
| 192 | return HIDDEN |
| 193 | raise ValueError(f"Schema field '{field_name}' permission access must be edit, read, or hidden") |
| 194 | |
| 195 | |
| 196 | def _access_key(value: str) -> str | None: |
| 197 | try: |
| 198 | return _normalize_access(value, field_name="") |
| 199 | except ValueError: |
| 200 | return None |
| 201 | |
| 202 | |
| 203 | def _principal_from_key(value: str) -> str: |
| 204 | principal = value.strip() |
| 205 | lowered = principal.lower() |
| 206 | if lowered in {"anonymous", "anon"}: |
| 207 | return "public" |
| 208 | if lowered in {"authenticated", "signed_in", "signed-in"}: |
| 209 | return "registered" |
| 210 | if lowered in _SPECIAL_PRINCIPALS or any(lowered.startswith(prefix) for prefix in _PRINCIPAL_PREFIXES): |
| 211 | return principal |
| 212 | return f"role:{principal}" |