Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_api_keys.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_api_keys.py · 14.1 KB · 349 lines
1"""Per-user API keys -- durable bearer tokens for programmatic / MCP / agent
2access to the object server.
3
4This is the access path q9 has (`/userauth/apikeys/`, `Authorization: Token …`)
5and the object server lacked: a user mints a long-lived token, points an agent
6or script at it, and it authenticates as that user. Distinct from the three
7existing token kinds: session tokens (short-lived, from a password login), the
8operator admin token (one server-wide superuser, in the env), and BYO
9service-keys (authenticate to *providers*, not to us).
10
11Posture -- 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
25The auth wiring (object_server `_permission_identity`) and the self-service
26management routes live in object_server; this module is the pure store +
27resolver.
28"""
29
30from __future__ import annotations
31
32import csv
33import hmac
34import os
35import re
36import secrets
37import threading
38from dataclasses import dataclass
39from datetime import datetime, timezone
40from pathlib import Path
41from typing import Iterable
42
43import object_identity
44from object_versions import DEFAULT_DATA_DIR
45
46IDENTITY_DIR = "identity"
47API_KEYS_FILE = "api_keys.tsv"
48API_KEY_FIELDS = ("user_id", "key_id", "name", "token_hash", "created_at", "last_used_at", "user_bound")
49
50TOKEN_PREFIX = "dbk_"
51_TOKEN_BYTES = 32
52MAX_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
59class InvalidApiKeyError(ValueError):
60 """Raised when an API-key request is not usable."""
61
62
63@dataclass(frozen=True)
64class 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 # Minted for a user with a row in users.tsv. Such a key ends when that row
73 # goes away (the user was deleted); a key minted for an unregistered id
74 # (allowed unless DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS) cannot tell
75 # "deleted" from "never registered", so it keeps working, as before. Rows
76 # written before this column existed read as not bound.
77 user_bound: bool = False
78
79 def public(self) -> dict[str, str]:
80 return {
81 "key_id": self.key_id,
82 "name": self.name,
83 "created_at": self.created_at,
84 "last_used_at": self.last_used_at,
85 }
86
87
88def api_keys_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
89 root = Path(base_dir) / IDENTITY_DIR
90 path = root / API_KEYS_FILE
91 resolved_root = root.resolve(strict=False)
92 resolved_path = path.resolve(strict=False)
93 try:
94 resolved_path.relative_to(resolved_root)
95 except ValueError as exc:
96 raise ValueError("API keys path escapes identity directory") from exc
97 return path
98
99
100def _now() -> datetime:
101 return datetime.now(timezone.utc)
102
103
104def _format_timestamp(value: datetime) -> str:
105 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
106
107
108def _required_text(value: str, name: str) -> str:
109 if not isinstance(value, str) or not value.strip():
110 raise InvalidApiKeyError(f"{name} is required")
111 return value.strip()
112
113
114def _required_name(name: str) -> str:
115 text = _required_text(name, "name")
116 if len(text) > MAX_NAME_LENGTH:
117 raise InvalidApiKeyError(f"name must be at most {MAX_NAME_LENGTH} characters")
118 return text
119
120
121def create_api_key(
122 user_id: str,
123 name: str,
124 *,
125 base_dir: Path | str = DEFAULT_DATA_DIR,
126 now: datetime | None = None,
127 require_known_user: bool = False,
128) -> tuple[dict[str, str], str]:
129 """Mint a key for a user. Returns (safe metadata, RAW TOKEN). The raw token
130 is the ONLY time it exists -- it is never stored or recoverable.
131
132 Refused for a user who is not active (object_identity.user_standing): a
133 disabled user was once handed a fresh, working key by the admin route.
134 Refused as well for a user whose account is not active. With
135 require_known_user, refused for a user id with no row too."""
136 normalized_user_id = _required_text(user_id, "user_id")
137 normalized_name = _required_name(name)
138 standing = object_identity.user_standing(normalized_user_id, base_dir=base_dir)
139 if standing == object_identity.STANDING_INACTIVE:
140 raise InvalidApiKeyError(f"User is not active: {normalized_user_id}")
141 if standing == object_identity.STANDING_ABSENT and require_known_user:
142 raise object_identity.UserNotFoundError(f"User not found: {normalized_user_id}")
143 record = object_identity.user_record(normalized_user_id, base_dir=base_dir)
144 # AccountUnusableError (a ValueError) for an account with no row or a
145 # row that does not parse: no key for a user who could not use it.
146 account = (
147 object_identity.member_account(normalized_user_id, record.account_id, base_dir=base_dir)
148 if record is not None
149 else None
150 )
151 if account is not None and not account.active:
152 raise InvalidApiKeyError(f"Account is not active: {record.account_id}")
153 raw_token = TOKEN_PREFIX + secrets.token_urlsafe(_TOKEN_BYTES)
154 key_id = secrets.token_hex(12)
155 stamp = _format_timestamp(now or _now())
156 entry = ApiKeyMeta(
157 user_id=normalized_user_id, key_id=key_id, name=normalized_name,
158 created_at=stamp, last_used_at="",
159 user_bound=standing == object_identity.STANDING_ACTIVE,
160 )
161 path = api_keys_path(base_dir)
162 with _file_lock(path):
163 entries = _read_entries(path)
164 entries.append((entry, object_identity.hash_token(raw_token)))
165 _write_entries(path, entries)
166 return entry.public(), raw_token
167
168
169def list_api_keys(user_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> list[dict[str, str]]:
170 """A user's keys as safe metadata (never the token or hash)."""
171 normalized_user_id = _required_text(user_id, "user_id")
172 path = api_keys_path(base_dir)
173 with _file_lock(path):
174 entries = _read_entries(path)
175 return [meta.public() for meta, _hash in entries if meta.user_id == normalized_user_id]
176
177
178def revoke_api_key(user_id: str, key_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> bool:
179 """Delete one of a user's keys. Returns True when a key was removed."""
180 normalized_user_id = _required_text(user_id, "user_id")
181 if not _KEY_ID_RE.fullmatch(key_id or ""):
182 raise InvalidApiKeyError("invalid key_id")
183 path = api_keys_path(base_dir)
184 with _file_lock(path):
185 entries = _read_entries(path)
186 kept = [(m, h) for (m, h) in entries if not (m.user_id == normalized_user_id and m.key_id == key_id)]
187 if len(kept) == len(entries):
188 return False
189 _write_entries(path, kept)
190 return True
191
192
193def revoke_user_api_keys(user_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> int:
194 """Delete every key a user holds; return how many (offboarding, disable)."""
195 normalized_user_id = _required_text(user_id, "user_id")
196 path = api_keys_path(base_dir)
197 with _file_lock(path):
198 entries = _read_entries(path)
199 kept = [(m, h) for (m, h) in entries if m.user_id != normalized_user_id]
200 removed = len(entries) - len(kept)
201 if removed:
202 _write_entries(path, kept)
203 return removed
204
205
206def resolve_api_key(
207 token: str | None,
208 *,
209 base_dir: Path | str = DEFAULT_DATA_DIR,
210 require_known_user: bool = False,
211 raise_unavailable: bool = False,
212 raise_account_unusable: bool = False,
213) -> str | None:
214 """Return the user_id a raw API-key token authenticates as, or None. Rejects
215 anything without the `dbk_` prefix immediately (so a session token never
216 reaches this path). Constant-time hash comparison, same as sessions.
217
218 A key whose owner is not active resolves to nobody, checked on every call
219 against users.tsv (object_identity.user_record, stat-cached) -- so a
220 disable, here or in another process, stops the key on the next request
221 even before revocation deletes it. With require_known_user a key naming a
222 user id with no row resolves to nobody as well.
223
224 A key whose owner is disabled, or was registered when the key was minted
225 and has no row now (deleted), is also deleted here, best effort, so
226 re-enabling or re-creating the user does not bring it back -- the same
227 as object_identity.resolve_session_token does for sessions. A row that
228 does not parse refuses the key without deleting it. A key whose owner's
229 account is disabled (accounts.tsv, stat-cached) is refused too but never
230 deleted, so re-enabling the account restores it unchanged; an
231 accounts.tsv that cannot be read raises OSError like users.tsv. A key
232 whose owner's row names an account with no row, or a row that does not
233 parse, is refused and kept (object_identity.member_account); with
234 raise_account_unusable that is AccountUnusableError rather than None. A
235 key carries no roles: the caller reads them from the user's row on every
236 request.
237
238 Deliberately does NOT update last_used_at -- that would be a file write on
239 every authenticated request. A future daemon/lazy update can add it."""
240 if not token or not token.startswith(TOKEN_PREFIX):
241 return None
242 presented = object_identity.hash_token(token)
243 path = api_keys_path(base_dir)
244 try:
245 with _file_lock(path):
246 entries = _read_entries(path)
247 except OSError:
248 # raise_unavailable: the caller tells "this key is not known" from "the
249 # keys file cannot be read" (object_server answers the second with a
250 # 503 under enforcement rather than treating the key holder as anonymous).
251 if raise_unavailable:
252 raise
253 return None
254 for meta, stored_hash in entries:
255 if hmac.compare_digest(stored_hash, presented):
256 # users.tsv unreadable raises OSError, as it always has; a missing
257 # users.tsv is unreadable too for a key bound to a registered user
258 # (not a deletion of every user at once).
259 record = object_identity.user_record(meta.user_id, base_dir=base_dir)
260 if record is None:
261 if not meta.user_bound:
262 return None if require_known_user else meta.user_id
263 if not object_identity.users_file_present(base_dir):
264 raise FileNotFoundError("Identity users file is missing")
265 _end_key(meta, base_dir=base_dir)
266 return None
267 if not record.active:
268 if record.roles is not None:
269 _end_key(meta, base_dir=base_dir)
270 return None
271 try:
272 account = object_identity.member_account(
273 meta.user_id, record.account_id, base_dir=base_dir
274 )
275 except object_identity.AccountUnusableError:
276 if raise_account_unusable:
277 raise
278 return None
279 if account is not None and not account.active:
280 # Refused, never deleted: the key works again, unchanged,
281 # when the account is re-enabled (set_account_status).
282 return None
283 return meta.user_id
284 return None
285
286
287def _end_key(meta: ApiKeyMeta, *, base_dir: Path | str) -> None:
288 """Delete a key whose owner is gone or disabled, best effort (see resolve_api_key).
289
290 The refusal does not depend on it: the owner's row refuses the key on
291 every request anyway.
292 """
293 try:
294 revoke_api_key(meta.user_id, meta.key_id, base_dir=base_dir)
295 except (OSError, ValueError):
296 pass
297
298
299# --- file IO (mirrors object_service_keys' owner-only 0600 posture) --------
300
301def _file_lock(path: Path) -> threading.Lock:
302 resolved = path.resolve(strict=False)
303 with _FILE_LOCKS_LOCK:
304 lock = _FILE_LOCKS.get(resolved)
305 if lock is None:
306 lock = threading.Lock()
307 _FILE_LOCKS[resolved] = lock
308 return lock
309
310
311def _read_entries(path: Path) -> list[tuple[ApiKeyMeta, str]]:
312 try:
313 text = path.read_text(encoding="utf-8")
314 except FileNotFoundError:
315 return []
316 entries: list[tuple[ApiKeyMeta, str]] = []
317 for row in csv.DictReader(text.splitlines(), delimiter="\t"):
318 token_hash = (row.get("token_hash") or "").strip()
319 user_id = (row.get("user_id") or "").strip()
320 key_id = (row.get("key_id") or "").strip()
321 if not (token_hash and user_id and key_id):
322 continue
323 entries.append((
324 ApiKeyMeta(
325 user_id=user_id, key_id=key_id, name=(row.get("name") or "").strip(),
326 created_at=(row.get("created_at") or "").strip(),
327 last_used_at=(row.get("last_used_at") or "").strip(),
328 user_bound=(row.get("user_bound") or "").strip() == "1",
329 ),
330 token_hash,
331 ))
332 return entries
333
334
335def _write_entries(path: Path, entries: Iterable[tuple[ApiKeyMeta, str]]) -> None:
336 path.parent.mkdir(parents=True, exist_ok=True)
337 temp_path = path.with_suffix(path.suffix + ".tmp")
338 with temp_path.open("w", encoding="utf-8", newline="") as handle:
339 writer = csv.DictWriter(handle, fieldnames=API_KEY_FIELDS, delimiter="\t")
340 writer.writeheader()
341 for meta, token_hash in entries:
342 writer.writerow({
343 "user_id": meta.user_id, "key_id": meta.key_id, "name": meta.name,
344 "token_hash": token_hash, "created_at": meta.created_at,
345 "last_used_at": meta.last_used_at,
346 "user_bound": "1" if meta.user_bound else "",
347 })
348 os.chmod(temp_path, 0o600)
349 os.replace(temp_path, path)