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

0 downloads

dbbasic-object-server/object_service_keys.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_service_keys.py · 10.3 KB · 319 lines
1"""File-backed per-user service API keys (AI providers and similar).
2
3Keys live in their own owner-only TSV under the identity directory, next to
4credentials.tsv and with the same posture: never inside record collections,
5never in API read responses, never in portable backups or source control.
6The write-only contract is deliberate — a caller can set a key, list which
7services have one, and delete one, but no surface can read key material
8back. The server uses stored keys on the caller's behalf (for example to
9call an AI provider) so the key never travels to browsers or agents.
10
11Keys are stored as provided, not hashed — unlike passwords they must be
12recoverable to be used. The 0600 file is the trust boundary, the same one
13that already protects the deployment admin token in its env file.
14"""
15
16from __future__ import annotations
17
18import csv
19import os
20import re
21import threading
22from dataclasses import dataclass
23from datetime import datetime, timezone
24from pathlib import Path
25from typing import Iterable, Mapping
26
27from object_versions import DEFAULT_DATA_DIR
28
29IDENTITY_DIR = "identity"
30SERVICE_KEYS_FILE = "service_keys.tsv"
31SERVICE_KEY_FIELDS = (
32 "user_id",
33 "service",
34 "key",
35 "created_at",
36 "updated_at",
37)
38MAX_KEY_LENGTH = 4096
39_SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
40
41# Reserved service-name prefixes mark PLATFORM-OWNED secrets -- a credential the
42# platform provisions on a user's behalf (e.g. a generated mailbox password),
43# as opposed to a user's own BYO key (openai, anthropic, ...). Reserved names
44# are valid to store, but only in-process server code may write them: the
45# self-service HTTP endpoint refuses them, so a user can never overwrite a
46# secret the platform owns. See docs/secrets-and-credentials.md.
47RESERVED_SERVICE_PREFIXES = ("sys-",)
48
49_FILE_LOCKS: dict[Path, threading.Lock] = {}
50_FILE_LOCKS_LOCK = threading.Lock()
51
52
53class InvalidServiceKeyError(ValueError):
54 """Raised when a service key payload is not usable."""
55
56
57@dataclass(frozen=True)
58class StoredServiceKey:
59 """One user's stored key for one service."""
60
61 user_id: str
62 service: str
63 key: str
64 created_at: str
65 updated_at: str
66
67
68def service_keys_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
69 root = Path(base_dir) / IDENTITY_DIR
70 path = root / SERVICE_KEYS_FILE
71 resolved_root = root.resolve(strict=False)
72 resolved_path = path.resolve(strict=False)
73
74 try:
75 resolved_path.relative_to(resolved_root)
76 except ValueError as exc:
77 raise ValueError("Service keys path escapes identity directory") from exc
78
79 return path
80
81
82def validate_service_name(service: str) -> bool:
83 """Return True when a service name is safe for storage and routes."""
84 return isinstance(service, str) and bool(_SERVICE_RE.fullmatch(service))
85
86
87def is_reserved_service(service: str) -> bool:
88 """Return True when a service name is platform-owned (a reserved prefix).
89
90 Reserved names are writable only by in-process server code; the
91 self-service HTTP endpoint rejects them so a user cannot overwrite a
92 secret the platform provisions on their behalf. This is the single source
93 of truth for the rule -- callers gate on it, they never re-derive it.
94 """
95 return isinstance(service, str) and service.startswith(RESERVED_SERVICE_PREFIXES)
96
97
98def set_service_key(
99 user_id: str,
100 service: str,
101 key: str,
102 *,
103 base_dir: Path | str = DEFAULT_DATA_DIR,
104 now: datetime | None = None,
105) -> dict[str, str]:
106 """Create or replace one user's key for one service; return safe metadata."""
107 normalized_user_id = _required_text(user_id, "user_id")
108 normalized_service = _required_service(service)
109 normalized_key = _required_key(key)
110 timestamp = _format_timestamp(now or _now())
111
112 path = service_keys_path(base_dir)
113 with _file_lock(path):
114 entries = _read_entries(path)
115 existing = _pop_entry(entries, normalized_user_id, normalized_service)
116 entries.append(
117 StoredServiceKey(
118 user_id=normalized_user_id,
119 service=normalized_service,
120 key=normalized_key,
121 created_at=existing.created_at if existing is not None else timestamp,
122 updated_at=timestamp,
123 )
124 )
125 _write_entries(path, entries)
126
127 return {
128 "user_id": normalized_user_id,
129 "service": normalized_service,
130 "operation": "replaced" if existing is not None else "created",
131 "updated_at": timestamp,
132 }
133
134
135def get_service_key(
136 user_id: str,
137 service: str,
138 *,
139 base_dir: Path | str = DEFAULT_DATA_DIR,
140) -> str | None:
141 """Return one stored key for server-side use, or None.
142
143 This is the only way key material comes back out, and it stays inside
144 the server process — route handlers must never place it in responses.
145 """
146 if not isinstance(user_id, str) or not validate_service_name(service):
147 return None
148 for entry in _read_entries(service_keys_path(base_dir)):
149 if entry.user_id == user_id.strip() and entry.service == service:
150 return entry.key
151 return None
152
153
154def list_service_key_status(
155 user_id: str,
156 *,
157 base_dir: Path | str = DEFAULT_DATA_DIR,
158) -> list[dict[str, str]]:
159 """Return which services have keys for one user — metadata only."""
160 normalized_user_id = _required_text(user_id, "user_id")
161 statuses = []
162 for entry in _read_entries(service_keys_path(base_dir)):
163 if entry.user_id == normalized_user_id:
164 statuses.append(
165 {
166 "service": entry.service,
167 "created_at": entry.created_at,
168 "updated_at": entry.updated_at,
169 }
170 )
171 return sorted(statuses, key=lambda status: status["service"])
172
173
174def remove_service_key(
175 user_id: str,
176 service: str,
177 *,
178 base_dir: Path | str = DEFAULT_DATA_DIR,
179) -> bool:
180 """Delete one user's key for one service; return whether one existed."""
181 normalized_user_id = _required_text(user_id, "user_id")
182 normalized_service = _required_service(service)
183 path = service_keys_path(base_dir)
184 with _file_lock(path):
185 entries = _read_entries(path)
186 existing = _pop_entry(entries, normalized_user_id, normalized_service)
187 if existing is None:
188 return False
189 _write_entries(path, entries)
190 return True
191
192
193def remove_all_service_keys(
194 user_id: str,
195 *,
196 base_dir: Path | str = DEFAULT_DATA_DIR,
197) -> int:
198 """Delete every key for one user (user deletion cleanup); return count."""
199 normalized_user_id = _required_text(user_id, "user_id")
200 path = service_keys_path(base_dir)
201 with _file_lock(path):
202 entries = _read_entries(path)
203 kept = [entry for entry in entries if entry.user_id != normalized_user_id]
204 removed = len(entries) - len(kept)
205 if removed:
206 _write_entries(path, kept)
207 return removed
208
209
210def _required_text(value: str, name: str) -> str:
211 if not isinstance(value, str):
212 raise InvalidServiceKeyError(f"{name} must be a string")
213 text = value.strip()
214 if not text:
215 raise InvalidServiceKeyError(f"{name} is required")
216 return text
217
218
219def _required_service(service: str) -> str:
220 if not validate_service_name(service):
221 raise InvalidServiceKeyError(
222 "service must be lowercase letters, digits, hyphens, or underscores"
223 )
224 return service
225
226
227def _required_key(key: str) -> str:
228 if not isinstance(key, str):
229 raise InvalidServiceKeyError("key must be a string")
230 text = key.strip()
231 if not text:
232 raise InvalidServiceKeyError("key is required")
233 if len(text) > MAX_KEY_LENGTH:
234 raise InvalidServiceKeyError(f"key must be at most {MAX_KEY_LENGTH} characters")
235 if any(char in text for char in "\t\r\n"):
236 raise InvalidServiceKeyError("key must not contain tabs or newlines")
237 return text
238
239
240def _pop_entry(
241 entries: list[StoredServiceKey],
242 user_id: str,
243 service: str,
244) -> StoredServiceKey | None:
245 for index, entry in enumerate(entries):
246 if entry.user_id == user_id and entry.service == service:
247 return entries.pop(index)
248 return None
249
250
251def _read_entries(path: Path) -> list[StoredServiceKey]:
252 if not path.exists():
253 return []
254
255 entries: list[StoredServiceKey] = []
256 with path.open(newline="") as handle:
257 rows = csv.DictReader(handle, delimiter="\t")
258 for row in rows:
259 if not row:
260 continue
261 entry = _entry_from_row(row)
262 if entry is not None:
263 entries.append(entry)
264 return entries
265
266
267def _write_entries(path: Path, entries: Iterable[StoredServiceKey]) -> None:
268 path.parent.mkdir(parents=True, exist_ok=True)
269 temp_path = path.with_name(f".{path.name}.tmp")
270 with temp_path.open("w", newline="") as handle:
271 writer = csv.DictWriter(handle, fieldnames=SERVICE_KEY_FIELDS, delimiter="\t")
272 writer.writeheader()
273 for entry in entries:
274 writer.writerow(
275 {
276 "user_id": entry.user_id,
277 "service": entry.service,
278 "key": entry.key,
279 "created_at": entry.created_at,
280 "updated_at": entry.updated_at,
281 }
282 )
283 os.chmod(temp_path, 0o600)
284 temp_path.replace(path)
285
286
287def _entry_from_row(row: Mapping[str, str]) -> StoredServiceKey | None:
288 user_id = (row.get("user_id") or "").strip()
289 service = (row.get("service") or "").strip()
290 key = (row.get("key") or "").strip()
291 created_at = (row.get("created_at") or "").strip()
292 updated_at = (row.get("updated_at") or "").strip()
293 if not user_id or not service or not key or not created_at or not updated_at:
294 return None
295 return StoredServiceKey(
296 user_id=user_id,
297 service=service,
298 key=key,
299 created_at=created_at,
300 updated_at=updated_at,
301 )
302
303
304def _format_timestamp(value: datetime) -> str:
305 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
306
307
308def _now() -> datetime:
309 return datetime.now(timezone.utc)
310
311
312def _file_lock(path: Path) -> threading.Lock:
313 resolved = path.resolve(strict=False)
314 with _FILE_LOCKS_LOCK:
315 lock = _FILE_LOCKS.get(resolved)
316 if lock is None:
317 lock = threading.Lock()
318 _FILE_LOCKS[resolved] = lock
319 return lock