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_api_keys.py · 8.4 KB · 235 lines
| 1 | """Per-user API keys -- durable bearer tokens for programmatic / MCP / agent |
| 2 | access to the object server. |
| 3 | |
| 4 | This is the access path q9 has (`/userauth/apikeys/`, `Authorization: Token …`) |
| 5 | and the object server lacked: a user mints a long-lived token, points an agent |
| 6 | or script at it, and it authenticates as that user. Distinct from the three |
| 7 | existing token kinds: session tokens (short-lived, from a password login), the |
| 8 | operator admin token (one server-wide superuser, in the env), and BYO |
| 9 | service-keys (authenticate to *providers*, not to us). |
| 10 | |
| 11 | Posture -- stronger than q9's plaintext-token-in-DB: |
| 12 | |
| 13 | - Keys live in their own owner-only TSV under `identity/` (next to |
| 14 | credentials.tsv / sessions.tsv), `0600`, **excluded from portable backups** |
| 15 | like the rest of `identity/`. |
| 16 | - **Only the hash is stored** (`hash_token`, the exact session-token shape: |
| 17 | `sha256:<hex>`). An API key is verify-only -- like a password it never needs |
| 18 | to be recovered, so it is never kept in a recoverable form. The raw token |
| 19 | exists once, in the create response; after that the server can only *check* a |
| 20 | presented token, never reveal a stored one. |
| 21 | - Verification is constant-time (`hmac.compare_digest`). |
| 22 | - Tokens carry a `dbk_` prefix so the auth layer routes them without a wasted |
| 23 | session lookup, and so a leaked token is greppable/revocable by shape. |
| 24 | |
| 25 | The auth wiring (object_server `_permission_identity`) and the self-service |
| 26 | management routes live in object_server; this module is the pure store + |
| 27 | resolver. |
| 28 | """ |
| 29 | |
| 30 | from __future__ import annotations |
| 31 | |
| 32 | import csv |
| 33 | import hmac |
| 34 | import os |
| 35 | import re |
| 36 | import secrets |
| 37 | import threading |
| 38 | from dataclasses import dataclass |
| 39 | from datetime import datetime, timezone |
| 40 | from pathlib import Path |
| 41 | from typing import Iterable |
| 42 | |
| 43 | import object_identity |
| 44 | from object_versions import DEFAULT_DATA_DIR |
| 45 | |
| 46 | IDENTITY_DIR = "identity" |
| 47 | API_KEYS_FILE = "api_keys.tsv" |
| 48 | API_KEY_FIELDS = ("user_id", "key_id", "name", "token_hash", "created_at", "last_used_at") |
| 49 | |
| 50 | TOKEN_PREFIX = "dbk_" |
| 51 | _TOKEN_BYTES = 32 |
| 52 | MAX_NAME_LENGTH = 120 |
| 53 | _KEY_ID_RE = re.compile(r"^[a-z0-9]{8,64}$") |
| 54 | |
| 55 | _FILE_LOCKS: dict[Path, threading.Lock] = {} |
| 56 | _FILE_LOCKS_LOCK = threading.Lock() |
| 57 | |
| 58 | |
| 59 | class InvalidApiKeyError(ValueError): |
| 60 | """Raised when an API-key request is not usable.""" |
| 61 | |
| 62 | |
| 63 | @dataclass(frozen=True) |
| 64 | class ApiKeyMeta: |
| 65 | """Safe metadata for one API key -- never carries the token or its hash.""" |
| 66 | |
| 67 | user_id: str |
| 68 | key_id: str |
| 69 | name: str |
| 70 | created_at: str |
| 71 | last_used_at: str |
| 72 | |
| 73 | def public(self) -> dict[str, str]: |
| 74 | return { |
| 75 | "key_id": self.key_id, |
| 76 | "name": self.name, |
| 77 | "created_at": self.created_at, |
| 78 | "last_used_at": self.last_used_at, |
| 79 | } |
| 80 | |
| 81 | |
| 82 | def api_keys_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 83 | root = Path(base_dir) / IDENTITY_DIR |
| 84 | path = root / API_KEYS_FILE |
| 85 | resolved_root = root.resolve(strict=False) |
| 86 | resolved_path = path.resolve(strict=False) |
| 87 | try: |
| 88 | resolved_path.relative_to(resolved_root) |
| 89 | except ValueError as exc: |
| 90 | raise ValueError("API keys path escapes identity directory") from exc |
| 91 | return path |
| 92 | |
| 93 | |
| 94 | def _now() -> datetime: |
| 95 | return datetime.now(timezone.utc) |
| 96 | |
| 97 | |
| 98 | def _format_timestamp(value: datetime) -> str: |
| 99 | return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") |
| 100 | |
| 101 | |
| 102 | def _required_text(value: str, name: str) -> str: |
| 103 | if not isinstance(value, str) or not value.strip(): |
| 104 | raise InvalidApiKeyError(f"{name} is required") |
| 105 | return value.strip() |
| 106 | |
| 107 | |
| 108 | def _required_name(name: str) -> str: |
| 109 | text = _required_text(name, "name") |
| 110 | if len(text) > MAX_NAME_LENGTH: |
| 111 | raise InvalidApiKeyError(f"name must be at most {MAX_NAME_LENGTH} characters") |
| 112 | return text |
| 113 | |
| 114 | |
| 115 | def create_api_key( |
| 116 | user_id: str, |
| 117 | name: str, |
| 118 | *, |
| 119 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 120 | now: datetime | None = None, |
| 121 | ) -> tuple[dict[str, str], str]: |
| 122 | """Mint a key for a user. Returns (safe metadata, RAW TOKEN). The raw token |
| 123 | is the ONLY time it exists -- it is never stored or recoverable.""" |
| 124 | normalized_user_id = _required_text(user_id, "user_id") |
| 125 | normalized_name = _required_name(name) |
| 126 | raw_token = TOKEN_PREFIX + secrets.token_urlsafe(_TOKEN_BYTES) |
| 127 | key_id = secrets.token_hex(12) |
| 128 | stamp = _format_timestamp(now or _now()) |
| 129 | entry = ApiKeyMeta( |
| 130 | user_id=normalized_user_id, key_id=key_id, name=normalized_name, |
| 131 | created_at=stamp, last_used_at="", |
| 132 | ) |
| 133 | path = api_keys_path(base_dir) |
| 134 | with _file_lock(path): |
| 135 | entries = _read_entries(path) |
| 136 | entries.append((entry, object_identity.hash_token(raw_token))) |
| 137 | _write_entries(path, entries) |
| 138 | return entry.public(), raw_token |
| 139 | |
| 140 | |
| 141 | def list_api_keys(user_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> list[dict[str, str]]: |
| 142 | """A user's keys as safe metadata (never the token or hash).""" |
| 143 | normalized_user_id = _required_text(user_id, "user_id") |
| 144 | path = api_keys_path(base_dir) |
| 145 | with _file_lock(path): |
| 146 | entries = _read_entries(path) |
| 147 | return [meta.public() for meta, _hash in entries if meta.user_id == normalized_user_id] |
| 148 | |
| 149 | |
| 150 | def revoke_api_key(user_id: str, key_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> bool: |
| 151 | """Delete one of a user's keys. Returns True when a key was removed.""" |
| 152 | normalized_user_id = _required_text(user_id, "user_id") |
| 153 | if not _KEY_ID_RE.fullmatch(key_id or ""): |
| 154 | raise InvalidApiKeyError("invalid key_id") |
| 155 | path = api_keys_path(base_dir) |
| 156 | with _file_lock(path): |
| 157 | entries = _read_entries(path) |
| 158 | kept = [(m, h) for (m, h) in entries if not (m.user_id == normalized_user_id and m.key_id == key_id)] |
| 159 | if len(kept) == len(entries): |
| 160 | return False |
| 161 | _write_entries(path, kept) |
| 162 | return True |
| 163 | |
| 164 | |
| 165 | def resolve_api_key(token: str | None, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> str | None: |
| 166 | """Return the user_id a raw API-key token authenticates as, or None. Rejects |
| 167 | anything without the `dbk_` prefix immediately (so a session token never |
| 168 | reaches this path). Constant-time hash comparison, same as sessions. |
| 169 | |
| 170 | Deliberately does NOT update last_used_at -- that would be a file write on |
| 171 | every authenticated request. A future daemon/lazy update can add it.""" |
| 172 | if not token or not token.startswith(TOKEN_PREFIX): |
| 173 | return None |
| 174 | presented = object_identity.hash_token(token) |
| 175 | path = api_keys_path(base_dir) |
| 176 | try: |
| 177 | with _file_lock(path): |
| 178 | entries = _read_entries(path) |
| 179 | except OSError: |
| 180 | return None |
| 181 | for meta, stored_hash in entries: |
| 182 | if hmac.compare_digest(stored_hash, presented): |
| 183 | return meta.user_id |
| 184 | return None |
| 185 | |
| 186 | |
| 187 | # --- file IO (mirrors object_service_keys' owner-only 0600 posture) -------- |
| 188 | |
| 189 | def _file_lock(path: Path) -> threading.Lock: |
| 190 | resolved = path.resolve(strict=False) |
| 191 | with _FILE_LOCKS_LOCK: |
| 192 | lock = _FILE_LOCKS.get(resolved) |
| 193 | if lock is None: |
| 194 | lock = threading.Lock() |
| 195 | _FILE_LOCKS[resolved] = lock |
| 196 | return lock |
| 197 | |
| 198 | |
| 199 | def _read_entries(path: Path) -> list[tuple[ApiKeyMeta, str]]: |
| 200 | try: |
| 201 | text = path.read_text(encoding="utf-8") |
| 202 | except FileNotFoundError: |
| 203 | return [] |
| 204 | entries: list[tuple[ApiKeyMeta, str]] = [] |
| 205 | for row in csv.DictReader(text.splitlines(), delimiter="\t"): |
| 206 | token_hash = (row.get("token_hash") or "").strip() |
| 207 | user_id = (row.get("user_id") or "").strip() |
| 208 | key_id = (row.get("key_id") or "").strip() |
| 209 | if not (token_hash and user_id and key_id): |
| 210 | continue |
| 211 | entries.append(( |
| 212 | ApiKeyMeta( |
| 213 | user_id=user_id, key_id=key_id, name=(row.get("name") or "").strip(), |
| 214 | created_at=(row.get("created_at") or "").strip(), |
| 215 | last_used_at=(row.get("last_used_at") or "").strip(), |
| 216 | ), |
| 217 | token_hash, |
| 218 | )) |
| 219 | return entries |
| 220 | |
| 221 | |
| 222 | def _write_entries(path: Path, entries: Iterable[tuple[ApiKeyMeta, str]]) -> None: |
| 223 | path.parent.mkdir(parents=True, exist_ok=True) |
| 224 | temp_path = path.with_suffix(path.suffix + ".tmp") |
| 225 | with temp_path.open("w", encoding="utf-8", newline="") as handle: |
| 226 | writer = csv.DictWriter(handle, fieldnames=API_KEY_FIELDS, delimiter="\t") |
| 227 | writer.writeheader() |
| 228 | for meta, token_hash in entries: |
| 229 | writer.writerow({ |
| 230 | "user_id": meta.user_id, "key_id": meta.key_id, "name": meta.name, |
| 231 | "token_hash": token_hash, "created_at": meta.created_at, |
| 232 | "last_used_at": meta.last_used_at, |
| 233 | }) |
| 234 | os.chmod(temp_path, 0o600) |
| 235 | os.replace(temp_path, path) |