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_identity_sources.py · 32.1 KB · 798 lines
| 1 | """Pluggable identity sources: who is this request, according to someone else? |
| 2 | |
| 3 | The server already knows four ways a request can say who it is: the admin |
| 4 | token, a durable API key, a local session, and (when an operator opts in) |
| 5 | trusted gateway headers. Each of those is resolved by object_server's |
| 6 | `_permission_identity`. This module is the start of a fifth kind: an |
| 7 | identity that another service vouches for. The first real caller is a |
| 8 | Django REST Framework app, whose clients send `Authorization: Token <DRF token>` |
| 9 | and expect this server to recognise them the way the old object server did. |
| 10 | |
| 11 | The shape is deliberately small, because the plan is a shared, pluggable |
| 12 | identity layer later (standard protocols at the edges, our own principal |
| 13 | model in the middle) and the least useful thing to do now is guess at its |
| 14 | final form: |
| 15 | |
| 16 | - An *identity source* takes the request headers and returns a `Principal` |
| 17 | or None. It does not know about permissions, objects or HTTP routing. |
| 18 | - A source confers only the roles its allowlist names |
| 19 | (DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES for http_verify). Unset means none |
| 20 | at all: the upstream says who somebody is, and this box's operator says |
| 21 | which of the upstream's role names mean anything here. Dropped roles are |
| 22 | reported on the principal (`dropped_roles`) so the server can record them. |
| 23 | - Sources are *configured* (from env today), *ordered* (first hit wins) and |
| 24 | *fail closed*: an exception, a timeout, a non-200, an oversized or |
| 25 | malformed answer all mean "not authenticated by this source". Nothing a |
| 26 | source returns can make a caller admin: `Principal` has no admin bit, and |
| 27 | `resolve_principal` strips the admin role names before handing it on. The |
| 28 | admin token stays the only way to be the operator. |
| 29 | - A principal's user id must be a positive decimal integer, because it |
| 30 | becomes the `u_<id>_` object namespace. A source that answers with |
| 31 | anything else has not authenticated anybody. |
| 32 | |
| 33 | What was rejected: |
| 34 | |
| 35 | - Letting the verify service's `is_staff`/`is_superuser` map to admin. The |
| 36 | service vouches for *who* somebody is, not for what they may do on this |
| 37 | box; a compromised or misconfigured upstream must not become root here. |
| 38 | - Caching by raw token. The cache key is a SHA-256 of the Authorization |
| 39 | header value, so a memory dump or a debug print of the cache does not hand |
| 40 | out credentials. Tokens are never logged. |
| 41 | - Following redirects and honouring HTTP(S)_PROXY. Both would send the |
| 42 | caller's credential somewhere the operator did not name. The fetch here |
| 43 | is plain http.client: it never follows a redirect (a 3xx is "could not |
| 44 | check") and never consults proxy settings. |
| 45 | - A per-read timeout alone. An upstream that drips a byte every couple of |
| 46 | seconds would hold one of the 8 verify slots for minutes and, eight at a |
| 47 | time, shut every new token out. The timeout is a deadline for the whole |
| 48 | exchange (connect, TLS, headers, body): past it the socket is shut down |
| 49 | and the slot is free again. |
| 50 | - Plain http to anything but loopback. Every caller's credential crosses |
| 51 | that wire, and so does the answer we believe: `https` is required unless |
| 52 | the host is 127.0.0.0/8, ::1 or `localhost` (checked when the source is |
| 53 | configured and again before every call). |
| 54 | - Trusting whoever answers. The two sides authenticate each other: this |
| 55 | server sends a shared secret (`X-DBBASIC-Verify-Secret`, from |
| 56 | DBBASIC_IDENTITY_VERIFY_SECRET; required for a non-loopback URL) so the |
| 57 | upstream knows the caller is a box it serves, and the upstream must name |
| 58 | this box in its answer (`"audience"`, equal to DBBASIC_IDENTITY_AUDIENCE) |
| 59 | so an answer minted for another service is not replayed here. A missing |
| 60 | or different audience authenticates nobody. |
| 61 | """ |
| 62 | from __future__ import annotations |
| 63 | |
| 64 | import hashlib |
| 65 | import http.client |
| 66 | import ipaddress |
| 67 | import json |
| 68 | import os |
| 69 | import re |
| 70 | import socket |
| 71 | import ssl |
| 72 | import threading |
| 73 | import time |
| 74 | import urllib.parse |
| 75 | from dataclasses import dataclass, field |
| 76 | from typing import Any, Callable, Iterable, Mapping, Protocol |
| 77 | |
| 78 | IDENTITY_VERIFY_URL_ENV = "DBBASIC_IDENTITY_VERIFY_URL" |
| 79 | # The server-to-server secret sent with each verify request. Never logged, |
| 80 | # never in an error message, never in a repr. |
| 81 | IDENTITY_VERIFY_SECRET_ENV = "DBBASIC_IDENTITY_VERIFY_SECRET" |
| 82 | # This server's name as the upstream must write it in "audience". |
| 83 | IDENTITY_AUDIENCE_ENV = "DBBASIC_IDENTITY_AUDIENCE" |
| 84 | # Comma-separated roles the verify source may confer. Unset or empty: none. |
| 85 | IDENTITY_ALLOWED_ROLES_ENV = "DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES" |
| 86 | VERIFY_SECRET_HEADER = "X-DBBASIC-Verify-Secret" |
| 87 | AUDIENCE_HEADER = "X-DBBASIC-Audience" |
| 88 | MIN_SECRET_LENGTH = 16 |
| 89 | |
| 90 | HTTP_VERIFY_TIMEOUT_SECONDS = 3.0 |
| 91 | HTTP_VERIFY_MAX_RESPONSE_BYTES = 64 * 1024 |
| 92 | POSITIVE_CACHE_ENV = "DBBASIC_IDENTITY_CACHE_TTL_SECONDS" |
| 93 | # How long a "yes, that token is user N" answer is trusted. Short on purpose: |
| 94 | # it is also how long a revoked token keeps working unless the upstream calls |
| 95 | # POST /admin/identity/sources/forget. |
| 96 | POSITIVE_CACHE_SECONDS = 30.0 |
| 97 | # The ceiling on any cached answer, whatever the setting says (a larger one |
| 98 | # is clamped, with a startup warning) and whatever the upstream's answer |
| 99 | # says (nothing in it is read as a lifetime). |
| 100 | MAX_CACHE_SECONDS = 60.0 |
| 101 | NEGATIVE_CACHE_SECONDS = 10.0 |
| 102 | # The cache is bounded: a stream of random tokens can only ever occupy this |
| 103 | # many entries (expired ones go first, then the oldest). |
| 104 | CACHE_MAX_ENTRIES = 4096 |
| 105 | # In-flight verify calls across the process. Past this a request is simply |
| 106 | # not authenticated by this source (fail closed) rather than queueing a |
| 107 | # thread per stranger with a made-up token. |
| 108 | MAX_CONCURRENT_VERIFICATIONS = 8 |
| 109 | |
| 110 | # Role names a source may never confer. The server additionally strips the |
| 111 | # active permission policy's admin_roles (see object_server). |
| 112 | NEVER_GRANTED_ROLES = frozenset({"admin", "superuser"}) |
| 113 | |
| 114 | _NUMERIC_USER_ID_RE = re.compile(r"^[0-9]{1,18}$") |
| 115 | _CANONICAL_USER_ID_RE = re.compile(r"^[1-9][0-9]{0,17}$") |
| 116 | # The same shape object_identity accepts for account ids. |
| 117 | _ACCOUNT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@-]{0,127}$") |
| 118 | _ROLE_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,64}$") |
| 119 | # Visible ASCII, no spaces: it goes in an HTTP header verbatim. |
| 120 | _SECRET_RE = re.compile(r"^[\x21-\x7e]{%d,512}$" % MIN_SECRET_LENGTH) |
| 121 | _AUDIENCE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$") |
| 122 | _MAX_ROLES = 32 |
| 123 | |
| 124 | |
| 125 | @dataclass(frozen=True) |
| 126 | class Principal: |
| 127 | """Who a source says the caller is. Never carries admin.""" |
| 128 | |
| 129 | user_id: str |
| 130 | source: str |
| 131 | account_id: str | None = None |
| 132 | roles: tuple[str, ...] = () |
| 133 | display_name: str | None = None |
| 134 | # Roles the upstream named that were not conferred (not allowlisted, or |
| 135 | # an admin name). Informational: for the server's ops log. |
| 136 | dropped_roles: tuple[str, ...] = () |
| 137 | |
| 138 | |
| 139 | class IdentityUnavailable(Exception): |
| 140 | """The source could not be asked (busy, down, timed out, 5xx). |
| 141 | |
| 142 | Different from "not authenticated": the caller carried a credential we |
| 143 | were unable to check, so the honest answer is 503, not anonymous. |
| 144 | """ |
| 145 | |
| 146 | |
| 147 | class IdentitySource(Protocol): |
| 148 | """Anything with a `name` and a `resolve(headers) -> Principal | None`. |
| 149 | |
| 150 | `headers` are lower-cased request headers. `resolve` may raise; the |
| 151 | caller treats that as "not authenticated" (fail closed). |
| 152 | """ |
| 153 | |
| 154 | name: str |
| 155 | |
| 156 | def resolve(self, headers: Mapping[str, str]) -> Principal | None: ... |
| 157 | |
| 158 | |
| 159 | def normalize_user_id(value: Any) -> str | None: |
| 160 | """A positive decimal user id as a canonical string, else None. |
| 161 | |
| 162 | `True` is an int in Python and JSON; it is not a user id. Leading zeros |
| 163 | are normalised away so `007` and `7` name one namespace, `u_7_`. |
| 164 | """ |
| 165 | if isinstance(value, bool): |
| 166 | return None |
| 167 | if isinstance(value, int): |
| 168 | text = str(value) |
| 169 | elif isinstance(value, str): |
| 170 | text = value.strip() |
| 171 | else: |
| 172 | return None |
| 173 | if not _NUMERIC_USER_ID_RE.fullmatch(text): |
| 174 | return None |
| 175 | number = int(text) |
| 176 | if number <= 0: |
| 177 | return None |
| 178 | return str(number) |
| 179 | |
| 180 | |
| 181 | def _clean_roles(value: Any, *, forbidden: Iterable[str] = ()) -> tuple[str, ...]: |
| 182 | if not isinstance(value, (list, tuple)): |
| 183 | return () |
| 184 | blocked = {role.lower() for role in NEVER_GRANTED_ROLES} | { |
| 185 | str(role).lower() for role in forbidden |
| 186 | } |
| 187 | roles: list[str] = [] |
| 188 | for item in value[:_MAX_ROLES]: |
| 189 | if not isinstance(item, str) or not _ROLE_RE.fullmatch(item): |
| 190 | continue |
| 191 | if item.lower() in blocked: |
| 192 | continue |
| 193 | if item not in roles: |
| 194 | roles.append(item) |
| 195 | return tuple(roles) |
| 196 | |
| 197 | |
| 198 | def _shaped_roles(value: Any) -> tuple[str, ...]: |
| 199 | """Every well-formed role name in an upstream list (deduplicated, capped).""" |
| 200 | if not isinstance(value, (list, tuple)): |
| 201 | return () |
| 202 | roles: list[str] = [] |
| 203 | for item in value[:_MAX_ROLES]: |
| 204 | if isinstance(item, str) and _ROLE_RE.fullmatch(item) and item not in roles: |
| 205 | roles.append(item) |
| 206 | return tuple(roles) |
| 207 | |
| 208 | |
| 209 | def parse_allowed_roles(raw: str | None) -> frozenset[str]: |
| 210 | """The roles a source may confer, from a comma-separated setting. |
| 211 | |
| 212 | Empty or unset is the empty set (no roles). A malformed name raises |
| 213 | ValueError, refusing the source rather than guessing what was meant. |
| 214 | """ |
| 215 | roles: set[str] = set() |
| 216 | for item in (raw or "").split(","): |
| 217 | name = item.strip() |
| 218 | if not name: |
| 219 | continue |
| 220 | if not _ROLE_RE.fullmatch(name): |
| 221 | raise ValueError( |
| 222 | f"{IDENTITY_ALLOWED_ROLES_ENV} has a malformed role name " |
| 223 | "(letters, digits and _ . : - only, at most 64 characters)" |
| 224 | ) |
| 225 | roles.add(name) |
| 226 | return frozenset(roles) |
| 227 | |
| 228 | |
| 229 | def _optional_text(value: Any, limit: int = 200) -> str | None: |
| 230 | if isinstance(value, bool) or value is None: |
| 231 | return None |
| 232 | if isinstance(value, (int, str)): |
| 233 | text = str(value).strip() |
| 234 | return text[:limit] or None |
| 235 | return None |
| 236 | |
| 237 | |
| 238 | AUDIENCE_MISSING = "audience_missing" |
| 239 | AUDIENCE_MISMATCH = "audience_mismatch" |
| 240 | # A 200 whose body is not a JSON object at all: an HTML page (an upstream |
| 241 | # that redirects to its login page), a list, something that does not parse. |
| 242 | NOT_JSON = "not_json" |
| 243 | # A 403 from the upstream: it refuses this server's request itself (a wrong |
| 244 | # or missing X-DBBASIC-Verify-Secret, or an X-DBBASIC-Audience it does not |
| 245 | # serve), whatever the token. A 401 is one token it does not know and is |
| 246 | # not recorded. |
| 247 | UPSTREAM_FORBIDDEN = "upstream_forbidden" |
| 248 | |
| 249 | |
| 250 | def audience_problem(payload: Any, audience: str) -> str | None: |
| 251 | """Why a 200 verify answer is not addressed to this server, or None. |
| 252 | |
| 253 | NOT_JSON: not a JSON object. AUDIENCE_MISSING: a JSON object with no "audience" key (an upstream that |
| 254 | has not been updated to echo it). AUDIENCE_MISMATCH: the key is there but |
| 255 | is not this server's name. This only names the reason for an operator; |
| 256 | principal_from_verify_payload does the refusing. |
| 257 | """ |
| 258 | if not isinstance(payload, Mapping): |
| 259 | return NOT_JSON |
| 260 | if "audience" not in payload: |
| 261 | return AUDIENCE_MISSING |
| 262 | claimed = payload.get("audience") |
| 263 | if not audience or not isinstance(claimed, str) or claimed != audience: |
| 264 | return AUDIENCE_MISMATCH |
| 265 | return None |
| 266 | |
| 267 | |
| 268 | def principal_from_verify_payload( |
| 269 | payload: Any, *, source: str, audience: str |
| 270 | ) -> Principal | None: |
| 271 | """Map a DRF-style /api/auth/verify/ answer to a principal. |
| 272 | |
| 273 | Shape: `{"audience": "<this box>", "user_id": <int|str>, "username": |
| 274 | "..."}`, optionally `account_id` and `roles`. `audience` must be a string |
| 275 | equal to this server's configured audience; anything else (missing, a |
| 276 | list, another name) is an answer meant for someone else. |
| 277 | `is_staff`/`is_superuser` are read by nobody: see the module docstring. |
| 278 | """ |
| 279 | if not isinstance(payload, Mapping): |
| 280 | return None |
| 281 | claimed = payload.get("audience") |
| 282 | if not audience or not isinstance(claimed, str) or claimed != audience: |
| 283 | return None |
| 284 | raw_id = payload.get("user_id") |
| 285 | if isinstance(raw_id, bool): |
| 286 | return None |
| 287 | if isinstance(raw_id, int): |
| 288 | raw_id = str(raw_id) |
| 289 | # Strict: a canonical positive integer. "007", " 7" and "7 " are not |
| 290 | # the same credential-to-namespace mapping the upstream means. |
| 291 | if not isinstance(raw_id, str) or not _CANONICAL_USER_ID_RE.fullmatch(raw_id): |
| 292 | return None |
| 293 | user_id = raw_id |
| 294 | account_id = None |
| 295 | if payload.get("account_id") is not None: |
| 296 | raw_account = payload.get("account_id") |
| 297 | if not isinstance(raw_account, str) or not _ACCOUNT_ID_RE.fullmatch(raw_account): |
| 298 | return None |
| 299 | account_id = raw_account |
| 300 | named = _shaped_roles(payload.get("roles")) |
| 301 | roles = _clean_roles(list(named)) |
| 302 | return Principal( |
| 303 | user_id=user_id, |
| 304 | source=source, |
| 305 | account_id=account_id, |
| 306 | roles=roles, |
| 307 | display_name=_optional_text(payload.get("username") or payload.get("display_name")), |
| 308 | dropped_roles=tuple(role for role in named if role not in roles), |
| 309 | ) |
| 310 | |
| 311 | |
| 312 | def is_loopback_host(host: str | None) -> bool: |
| 313 | """True for `localhost`, 127.0.0.0/8 and ::1 -- nothing that needs DNS |
| 314 | beyond the name `localhost` itself, and no spelling tricks (`0x7f.1`, |
| 315 | `127.0.0.1.example.com` are not loopback).""" |
| 316 | if not host: |
| 317 | return False |
| 318 | if host.lower() == "localhost": |
| 319 | return True |
| 320 | try: |
| 321 | return ipaddress.ip_address(host).is_loopback |
| 322 | except ValueError: |
| 323 | return False |
| 324 | |
| 325 | |
| 326 | def check_transport(url: str) -> bool: |
| 327 | """Raise ValueError unless `url` may carry a credential: https, or http to |
| 328 | a loopback host. Returns whether the host is loopback.""" |
| 329 | parsed = urllib.parse.urlsplit(url) |
| 330 | if parsed.scheme not in {"http", "https"} or not parsed.netloc: |
| 331 | raise ValueError( |
| 332 | f"{IDENTITY_VERIFY_URL_ENV} must be an https:// URL " |
| 333 | "(http:// only for a loopback host)" |
| 334 | ) |
| 335 | try: |
| 336 | host = parsed.hostname |
| 337 | parsed.port # noqa: B018 -- raises ValueError on a bad port |
| 338 | except ValueError: |
| 339 | raise ValueError(f"{IDENTITY_VERIFY_URL_ENV} has an invalid host or port") from None |
| 340 | if not host: |
| 341 | raise ValueError(f"{IDENTITY_VERIFY_URL_ENV} must name a host") |
| 342 | if parsed.username is not None or parsed.password is not None: |
| 343 | raise ValueError(f"{IDENTITY_VERIFY_URL_ENV} must not carry user:password@") |
| 344 | loopback = is_loopback_host(host) |
| 345 | if parsed.scheme != "https" and not loopback: |
| 346 | raise ValueError( |
| 347 | f"{IDENTITY_VERIFY_URL_ENV} must use https:// unless its host is loopback " |
| 348 | "(127.0.0.0/8, ::1, localhost)" |
| 349 | ) |
| 350 | return loopback |
| 351 | |
| 352 | |
| 353 | def _default_fetch( |
| 354 | url: str, |
| 355 | authorization: str, |
| 356 | timeout: float, |
| 357 | max_bytes: int, |
| 358 | extra_headers: Mapping[str, str] | None = None, |
| 359 | ) -> tuple[int, bytes, str]: |
| 360 | """GET `url` forwarding the caller's Authorization header verbatim, plus |
| 361 | `extra_headers` (the shared secret and audience). |
| 362 | |
| 363 | Returns (status, body, content_type); the body is read only for a 200. |
| 364 | Raises on transport errors, a URL that is not https/loopback, an |
| 365 | oversized body, and the deadline: `timeout` bounds the whole exchange, |
| 366 | not each socket read. No redirect is followed and no proxy is used. |
| 367 | """ |
| 368 | check_transport(url) |
| 369 | parsed = urllib.parse.urlsplit(url) |
| 370 | headers = dict(extra_headers or {}) |
| 371 | headers.update({"Authorization": authorization, "Accept": "application/json"}) |
| 372 | target = (parsed.path or "/") + (f"?{parsed.query}" if parsed.query else "") |
| 373 | if parsed.scheme == "https": |
| 374 | connection: http.client.HTTPConnection = http.client.HTTPSConnection( |
| 375 | parsed.hostname, parsed.port, timeout=timeout, |
| 376 | context=ssl.create_default_context(), |
| 377 | ) |
| 378 | else: |
| 379 | connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=timeout) |
| 380 | expired = threading.Event() |
| 381 | |
| 382 | def _expire() -> None: |
| 383 | expired.set() |
| 384 | sock = connection.sock |
| 385 | if sock is not None: |
| 386 | try: |
| 387 | sock.shutdown(socket.SHUT_RDWR) |
| 388 | except OSError: |
| 389 | pass |
| 390 | |
| 391 | watchdog = threading.Timer(timeout, _expire) |
| 392 | watchdog.daemon = True |
| 393 | watchdog.start() |
| 394 | try: |
| 395 | connection.request("GET", target, headers=headers) |
| 396 | response = connection.getresponse() |
| 397 | if response.status != 200: |
| 398 | return response.status, b"", "" |
| 399 | body = response.read(max_bytes + 1) |
| 400 | if expired.is_set(): |
| 401 | raise TimeoutError("identity verify deadline passed") |
| 402 | if len(body) > max_bytes: |
| 403 | raise ValueError("identity verify response too large") |
| 404 | return response.status, body, response.getheader("Content-Type", "") or "" |
| 405 | finally: |
| 406 | watchdog.cancel() |
| 407 | connection.close() |
| 408 | |
| 409 | |
| 410 | Fetch = Callable[..., "tuple[int, bytes, str]"] |
| 411 | |
| 412 | |
| 413 | def _is_json_content_type(value: str) -> bool: |
| 414 | media = value.split(";", 1)[0].strip().lower() |
| 415 | return media == "application/json" |
| 416 | |
| 417 | |
| 418 | @dataclass |
| 419 | class HttpVerifySource: |
| 420 | """Forward `Authorization: Token|Bearer ...` to a trusted verify URL. |
| 421 | |
| 422 | HTTP 200 with a JSON object naming a numeric `user_id` is a principal; |
| 423 | anything else is not. Positive answers are cached for 30 s by default |
| 424 | (DBBASIC_IDENTITY_CACHE_TTL_SECONDS), definite refusals for 10 s, keyed |
| 425 | by a hash of the header value. Transport failures are never cached. |
| 426 | |
| 427 | The URL must point at a service the operator trusts and controls (an |
| 428 | internal address of the app that issued the tokens): every caller's |
| 429 | credential is sent to it. It must be https unless the host is loopback, |
| 430 | a non-loopback source needs `secret`, and every source needs `audience`. |
| 431 | """ |
| 432 | |
| 433 | url: str |
| 434 | audience: str = "" |
| 435 | secret: str = field(default="", repr=False) |
| 436 | name: str = "http_verify" |
| 437 | # The roles this source may confer; the default confers none. |
| 438 | allowed_roles: frozenset[str] = frozenset() |
| 439 | timeout: float = HTTP_VERIFY_TIMEOUT_SECONDS |
| 440 | max_bytes: int = HTTP_VERIFY_MAX_RESPONSE_BYTES |
| 441 | positive_ttl: float = POSITIVE_CACHE_SECONDS |
| 442 | negative_ttl: float = NEGATIVE_CACHE_SECONDS |
| 443 | max_entries: int = CACHE_MAX_ENTRIES |
| 444 | fetch: Fetch = _default_fetch |
| 445 | clock: Callable[[], float] = time.monotonic |
| 446 | _cache: dict[str, tuple[float, Principal | None]] = field(default_factory=dict, repr=False) |
| 447 | _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) |
| 448 | _generation: int = field(default=0, repr=False) |
| 449 | _inflight: threading.BoundedSemaphore = field( |
| 450 | default_factory=lambda: threading.BoundedSemaphore(MAX_CONCURRENT_VERIFICATIONS), |
| 451 | repr=False, |
| 452 | ) |
| 453 | # reason -> (how many answers were refused for it, clock time of the |
| 454 | # last): a 403, or a 200 not addressed to this server. Emptied by a 200 |
| 455 | # that names this server. Reasons only: |
| 456 | # nothing from the token or the answer is kept. |
| 457 | _audience_refusals: dict[str, tuple[int, float]] = field(default_factory=dict, repr=False) |
| 458 | |
| 459 | def __post_init__(self) -> None: |
| 460 | self.positive_ttl = _clamped_ttl(self.positive_ttl, POSITIVE_CACHE_SECONDS) |
| 461 | self.negative_ttl = _clamped_ttl(self.negative_ttl, NEGATIVE_CACHE_SECONDS) |
| 462 | loopback = check_transport(self.url) |
| 463 | if self.secret and not _SECRET_RE.fullmatch(self.secret): |
| 464 | raise ValueError( |
| 465 | f"{IDENTITY_VERIFY_SECRET_ENV} must be {MIN_SECRET_LENGTH} to 512 visible " |
| 466 | "ASCII characters with no spaces" |
| 467 | ) |
| 468 | if not self.secret and not loopback: |
| 469 | raise ValueError( |
| 470 | f"{IDENTITY_VERIFY_SECRET_ENV} must be set for a {IDENTITY_VERIFY_URL_ENV} " |
| 471 | "whose host is not loopback" |
| 472 | ) |
| 473 | if not _AUDIENCE_RE.fullmatch(self.audience or ""): |
| 474 | raise ValueError( |
| 475 | f"{IDENTITY_AUDIENCE_ENV} must be set (this server's name as the verify " |
| 476 | "service writes it in \"audience\": letters, digits and _ . : @ / -)" |
| 477 | ) |
| 478 | |
| 479 | def _outbound_headers(self) -> dict[str, str]: |
| 480 | headers = {AUDIENCE_HEADER: self.audience} |
| 481 | if self.secret: |
| 482 | headers[VERIFY_SECRET_HEADER] = self.secret |
| 483 | return headers |
| 484 | |
| 485 | @staticmethod |
| 486 | def cache_key(authorization: str) -> str: |
| 487 | return hashlib.sha256(authorization.encode("utf-8", "surrogatepass")).hexdigest() |
| 488 | |
| 489 | def _credential(self, headers: Mapping[str, str]) -> str | None: |
| 490 | authorization = (headers.get("authorization") or "").strip() |
| 491 | scheme, _, token = authorization.partition(" ") |
| 492 | if scheme.lower() not in {"token", "bearer"} or not token.strip(): |
| 493 | return None |
| 494 | if len(authorization) > 4096 or any(c in authorization for c in "\r\n"): |
| 495 | return None |
| 496 | return authorization |
| 497 | |
| 498 | def cached(self, headers: Mapping[str, str]) -> tuple[bool, Principal | None]: |
| 499 | """(hit, principal) from the cache only; never calls out.""" |
| 500 | authorization = self._credential(headers) |
| 501 | if authorization is None: |
| 502 | return True, None |
| 503 | key = self.cache_key(authorization) |
| 504 | now = self.clock() |
| 505 | with self._lock: |
| 506 | entry = self._cache.get(key) |
| 507 | if entry is not None and entry[0] > now: |
| 508 | return True, entry[1] |
| 509 | return False, None |
| 510 | |
| 511 | def resolve(self, headers: Mapping[str, str]) -> Principal | None: |
| 512 | authorization = self._credential(headers) |
| 513 | if authorization is None: |
| 514 | return None |
| 515 | hit, principal = self.cached(headers) |
| 516 | if hit: |
| 517 | return principal |
| 518 | |
| 519 | if not self._inflight.acquire(blocking=False): |
| 520 | # Saturated: we cannot check this credential. Not cached. |
| 521 | raise IdentityUnavailable("identity verification is busy") |
| 522 | with self._lock: |
| 523 | generation = self._generation |
| 524 | try: |
| 525 | principal, definite = self._verify(authorization) |
| 526 | finally: |
| 527 | self._inflight.release() |
| 528 | if not definite: |
| 529 | raise IdentityUnavailable("identity verification is unavailable") |
| 530 | self._store(self.cache_key(authorization), principal, generation) |
| 531 | return principal |
| 532 | |
| 533 | def _verify(self, authorization: str) -> tuple[Principal | None, bool]: |
| 534 | """(principal, definite). Not definite = transport trouble: do not cache.""" |
| 535 | try: |
| 536 | # Again at call time: a source is a plain object and its url can |
| 537 | # be changed after construction. |
| 538 | check_transport(self.url) |
| 539 | if not self.secret and not is_loopback_host(urllib.parse.urlsplit(self.url).hostname): |
| 540 | return None, False |
| 541 | result = self.fetch( |
| 542 | self.url, authorization, self.timeout, self.max_bytes, self._outbound_headers() |
| 543 | ) |
| 544 | status, body = result[0], result[1] |
| 545 | content_type = result[2] if len(result) > 2 else "" |
| 546 | except Exception: # noqa: BLE001 -- any failure is "could not check" |
| 547 | return None, False |
| 548 | if status == 403: |
| 549 | self._note_audience(UPSTREAM_FORBIDDEN) |
| 550 | return None, True |
| 551 | if status == 401: |
| 552 | return None, True |
| 553 | if status != 200: |
| 554 | return None, False # 5xx, 429, redirects, 404: not an answer |
| 555 | if not _is_json_content_type(content_type): |
| 556 | self._note_audience(NOT_JSON) |
| 557 | return None, True |
| 558 | if len(body) > self.max_bytes: |
| 559 | return None, True |
| 560 | try: |
| 561 | payload = json.loads(body.decode("utf-8")) |
| 562 | except (UnicodeDecodeError, ValueError): |
| 563 | self._note_audience(NOT_JSON) |
| 564 | return None, True |
| 565 | self._note_audience(audience_problem(payload, self.audience)) |
| 566 | return ( |
| 567 | principal_from_verify_payload(payload, source=self.name, audience=self.audience), |
| 568 | True, |
| 569 | ) |
| 570 | |
| 571 | def _note_audience(self, problem: str | None) -> None: |
| 572 | """Remember that the upstream refused this server (403) or answered |
| 573 | 200 with something that is not a JSON object or lacks this server's |
| 574 | audience (or forget it all, once a 200 names this server). Changes |
| 575 | no answer.""" |
| 576 | now = self.clock() |
| 577 | with self._lock: |
| 578 | if problem is None: |
| 579 | self._audience_refusals.clear() |
| 580 | else: |
| 581 | count = self._audience_refusals.get(problem, (0, 0.0))[0] |
| 582 | self._audience_refusals[problem] = (count + 1, now) |
| 583 | |
| 584 | def audience_refusals(self) -> dict[str, tuple[int, float]]: |
| 585 | """reason -> (answers refused so far, seconds since the last one), |
| 586 | for UPSTREAM_FORBIDDEN / NOT_JSON / AUDIENCE_MISSING / AUDIENCE_MISMATCH. |
| 587 | Empty once the upstream has answered 200 with this server's audience.""" |
| 588 | now = self.clock() |
| 589 | with self._lock: |
| 590 | return { |
| 591 | reason: (count, max(0.0, now - at)) |
| 592 | for reason, (count, at) in self._audience_refusals.items() |
| 593 | } |
| 594 | |
| 595 | def _store(self, key: str, principal: Principal | None, generation: int | None = None) -> None: |
| 596 | now = self.clock() |
| 597 | ttl = self.positive_ttl if principal is not None else self.negative_ttl |
| 598 | # Again here: the fields are plain attributes and can be changed later. |
| 599 | ttl = _clamped_ttl(ttl, 0.0) |
| 600 | with self._lock: |
| 601 | if generation is not None and generation != self._generation: |
| 602 | return # a forget happened while this lookup was in flight |
| 603 | if key not in self._cache and len(self._cache) >= self.max_entries: |
| 604 | for stale in [k for k, (expires, _) in self._cache.items() if expires <= now]: |
| 605 | del self._cache[stale] |
| 606 | while len(self._cache) >= self.max_entries: |
| 607 | del self._cache[next(iter(self._cache))] |
| 608 | self._cache.pop(key, None) |
| 609 | self._cache[key] = (now + ttl, principal) |
| 610 | |
| 611 | def forget(self, token_hash: str | None = None) -> int: |
| 612 | """Drop one cached answer (by SHA-256 of the Authorization value) or all. |
| 613 | |
| 614 | Returns how many entries were dropped. Lookups already in flight will |
| 615 | not store their answer. |
| 616 | """ |
| 617 | with self._lock: |
| 618 | self._generation += 1 |
| 619 | if token_hash is None: |
| 620 | count = len(self._cache) |
| 621 | self._cache.clear() |
| 622 | return count |
| 623 | return 1 if self._cache.pop(token_hash, None) is not None else 0 |
| 624 | |
| 625 | def clear_cache(self) -> None: |
| 626 | with self._lock: |
| 627 | self._cache.clear() |
| 628 | |
| 629 | |
| 630 | # --- configuration -------------------------------------------------------- |
| 631 | |
| 632 | _CONFIGURED: tuple[tuple[str, ...], tuple[IdentitySource, ...]] | None = None |
| 633 | _CONFIGURED_LOCK = threading.Lock() |
| 634 | |
| 635 | |
| 636 | def _config_signature() -> tuple[str, ...]: |
| 637 | # The secret is held as a digest here, so changing it rebuilds the source |
| 638 | # without a second plain copy living in the signature. |
| 639 | secret = os.environ.get(IDENTITY_VERIFY_SECRET_ENV, "").strip() |
| 640 | return ( |
| 641 | os.environ.get(IDENTITY_VERIFY_URL_ENV, "").strip(), |
| 642 | os.environ.get(POSITIVE_CACHE_ENV, "").strip(), |
| 643 | hashlib.sha256(secret.encode("utf-8", "surrogatepass")).hexdigest() if secret else "", |
| 644 | os.environ.get(IDENTITY_AUDIENCE_ENV, "").strip(), |
| 645 | os.environ.get(IDENTITY_ALLOWED_ROLES_ENV, "").strip(), |
| 646 | ) |
| 647 | |
| 648 | |
| 649 | def _source_from_env(verify_url: str) -> HttpVerifySource: |
| 650 | """Raises ValueError (never naming the secret) for a refused configuration.""" |
| 651 | return HttpVerifySource( |
| 652 | url=verify_url, |
| 653 | audience=os.environ.get(IDENTITY_AUDIENCE_ENV, "").strip(), |
| 654 | secret=os.environ.get(IDENTITY_VERIFY_SECRET_ENV, "").strip(), |
| 655 | positive_ttl=positive_cache_seconds(), |
| 656 | allowed_roles=parse_allowed_roles(os.environ.get(IDENTITY_ALLOWED_ROLES_ENV)), |
| 657 | ) |
| 658 | |
| 659 | |
| 660 | def _clamped_ttl(value: Any, fallback: float) -> float: |
| 661 | """A cache lifetime in [0, MAX_CACHE_SECONDS]; `fallback` for nonsense.""" |
| 662 | if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value: |
| 663 | return fallback |
| 664 | return float(min(max(value, 0.0), MAX_CACHE_SECONDS)) |
| 665 | |
| 666 | |
| 667 | def _configured_cache_seconds() -> float | None: |
| 668 | """The setting as a number, or None when unset or not a usable number.""" |
| 669 | raw = os.environ.get(POSITIVE_CACHE_ENV, "").strip() |
| 670 | if not raw: |
| 671 | return None |
| 672 | try: |
| 673 | value = float(raw) |
| 674 | except ValueError: |
| 675 | return None |
| 676 | if value != value or value < 0: |
| 677 | return None |
| 678 | return value |
| 679 | |
| 680 | |
| 681 | def positive_cache_seconds() -> float: |
| 682 | """DBBASIC_IDENTITY_CACHE_TTL_SECONDS, default 30, clamped to 60.""" |
| 683 | value = _configured_cache_seconds() |
| 684 | if value is None: |
| 685 | return POSITIVE_CACHE_SECONDS |
| 686 | return min(value, MAX_CACHE_SECONDS) |
| 687 | |
| 688 | |
| 689 | def cache_ttl_warning() -> str | None: |
| 690 | """A sentence for startup when the configured lifetime was clamped.""" |
| 691 | value = _configured_cache_seconds() |
| 692 | if value is None or value <= MAX_CACHE_SECONDS: |
| 693 | return None |
| 694 | return ( |
| 695 | f"{POSITIVE_CACHE_ENV}={os.environ.get(POSITIVE_CACHE_ENV, '').strip()} is above the " |
| 696 | f"{int(MAX_CACHE_SECONDS)} s ceiling; verified identities are cached for " |
| 697 | f"{int(MAX_CACHE_SECONDS)} s." |
| 698 | ) |
| 699 | |
| 700 | |
| 701 | def forget(token_hash: str | None = None) -> int: |
| 702 | """Drop cached verify answers on every configured source.""" |
| 703 | return sum( |
| 704 | source.forget(token_hash) |
| 705 | for source in configured_sources() |
| 706 | if hasattr(source, "forget") |
| 707 | ) |
| 708 | |
| 709 | |
| 710 | def configured_sources() -> tuple[IdentitySource, ...]: |
| 711 | """The sources the environment turns on, in order. Empty when none. |
| 712 | |
| 713 | Rebuilt when the env changes (tests flip it); otherwise the same |
| 714 | instances are returned so their caches survive between requests. A |
| 715 | misconfigured source (a URL that is not https or loopback, a missing |
| 716 | secret for a remote host, no audience) yields no source at all -- nobody |
| 717 | is authenticated by a source the operator did not configure correctly. |
| 718 | configuration_error() says why. |
| 719 | """ |
| 720 | global _CONFIGURED |
| 721 | signature = _config_signature() |
| 722 | with _CONFIGURED_LOCK: |
| 723 | if _CONFIGURED is not None and _CONFIGURED[0] == signature: |
| 724 | return _CONFIGURED[1] |
| 725 | sources: list[IdentitySource] = [] |
| 726 | verify_url = signature[0] |
| 727 | if verify_url: |
| 728 | try: |
| 729 | sources.append(_source_from_env(verify_url)) |
| 730 | except ValueError: |
| 731 | pass |
| 732 | _CONFIGURED = (signature, tuple(sources)) |
| 733 | return _CONFIGURED[1] |
| 734 | |
| 735 | |
| 736 | def configuration_error() -> str | None: |
| 737 | """A sentence for status pages when the env names a source we refused.""" |
| 738 | verify_url = os.environ.get(IDENTITY_VERIFY_URL_ENV, "").strip() |
| 739 | if not verify_url: |
| 740 | return None |
| 741 | try: |
| 742 | _source_from_env(verify_url) |
| 743 | except ValueError as exc: |
| 744 | return str(exc) |
| 745 | return None |
| 746 | |
| 747 | |
| 748 | def resolve_principal( |
| 749 | headers: Mapping[str, str], |
| 750 | sources: Iterable[IdentitySource] | None = None, |
| 751 | *, |
| 752 | forbidden_roles: Iterable[str] = (), |
| 753 | raise_unavailable: bool = False, |
| 754 | ) -> Principal | None: |
| 755 | """First principal any source vouches for, admin roles stripped. |
| 756 | |
| 757 | Only roles in the source's `allowed_roles` survive; a source without |
| 758 | that attribute confers none. Every role named but not conferred is in |
| 759 | the result's `dropped_roles`. |
| 760 | |
| 761 | A source that raises is skipped: it authenticated nobody. A source that |
| 762 | says IdentityUnavailable is skipped too, but with `raise_unavailable` |
| 763 | the error is re-raised when no other source vouched for the caller. |
| 764 | """ |
| 765 | unavailable: IdentityUnavailable | None = None |
| 766 | for source in configured_sources() if sources is None else sources: |
| 767 | try: |
| 768 | principal = source.resolve(headers) |
| 769 | except IdentityUnavailable as exc: |
| 770 | unavailable = exc |
| 771 | continue |
| 772 | except Exception: # noqa: BLE001 -- fail closed per source |
| 773 | continue |
| 774 | if principal is None: |
| 775 | continue |
| 776 | user_id = normalize_user_id(principal.user_id) |
| 777 | if user_id is None: |
| 778 | continue |
| 779 | allowed = getattr(source, "allowed_roles", None) |
| 780 | if not isinstance(allowed, (set, frozenset)): |
| 781 | allowed = frozenset() |
| 782 | named = _shaped_roles(list(principal.roles) + list(principal.dropped_roles)) |
| 783 | roles = tuple( |
| 784 | role |
| 785 | for role in _clean_roles(list(principal.roles), forbidden=forbidden_roles) |
| 786 | if role in allowed |
| 787 | ) |
| 788 | return Principal( |
| 789 | user_id=user_id, |
| 790 | source=principal.source, |
| 791 | account_id=principal.account_id, |
| 792 | roles=roles, |
| 793 | display_name=principal.display_name, |
| 794 | dropped_roles=tuple(role for role in named if role not in roles), |
| 795 | ) |
| 796 | if unavailable is not None and raise_unavailable: |
| 797 | raise unavailable |
| 798 | return None |