albert-memory 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. albert/__init__.py +3 -0
  2. albert/admin.py +532 -0
  3. albert/api.py +698 -0
  4. albert/automatic_memory_release.json +14 -0
  5. albert/benchmark.py +272 -0
  6. albert/benchmark_cli.py +37 -0
  7. albert/capture.py +1051 -0
  8. albert/capture_installer.py +1000 -0
  9. albert/capture_promotion.py +298 -0
  10. albert/capture_retention.py +72 -0
  11. albert/capture_sdk.py +558 -0
  12. albert/capture_security.py +79 -0
  13. albert/chunking.py +79 -0
  14. albert/classifier.py +263 -0
  15. albert/claude_adapter.py +357 -0
  16. albert/claude_lifecycle.py +418 -0
  17. albert/claude_package.json +19 -0
  18. albert/claude_plugin/.claude-plugin/plugin.json +11 -0
  19. albert/claude_plugin/.mcp.json +13 -0
  20. albert/claude_plugin/hooks/hooks.json +70 -0
  21. albert/clusters.py +140 -0
  22. albert/codex_adapter.py +308 -0
  23. albert/codex_hooks/hooks.json +49 -0
  24. albert/codex_lifecycle.py +485 -0
  25. albert/codex_package.json +19 -0
  26. albert/compatibility.py +121 -0
  27. albert/config.py +144 -0
  28. albert/console.py +508 -0
  29. albert/console_backends.py +236 -0
  30. albert/console_map.py +518 -0
  31. albert/console_ops.py +919 -0
  32. albert/credentials.py +616 -0
  33. albert/cursor_adapter.py +320 -0
  34. albert/cursor_hooks/hooks.json +11 -0
  35. albert/cursor_rules/albert-memory.mdc +11 -0
  36. albert/db.py +68 -0
  37. albert/embeddings.py +91 -0
  38. albert/graph.py +623 -0
  39. albert/graph_builders.py +879 -0
  40. albert/graph_cypher.py +669 -0
  41. albert/graph_store.py +376 -0
  42. albert/host_targets/claude-code.json +45 -0
  43. albert/host_targets/codex.json +45 -0
  44. albert/host_targets/openclaw.json +45 -0
  45. albert/host_targets.py +271 -0
  46. albert/links.py +428 -0
  47. albert/mcp_server.py +457 -0
  48. albert/memory_safety.py +111 -0
  49. albert/models.py +611 -0
  50. albert/openclaw_adapter.py +326 -0
  51. albert/openclaw_adapter_trust.json +5 -0
  52. albert/openclaw_package.json +22 -0
  53. albert/openclaw_plugin/index.js +135 -0
  54. albert/openclaw_plugin/openclaw.plugin.json +25 -0
  55. albert/openclaw_plugin/package.json +12 -0
  56. albert/portability.py +291 -0
  57. albert/provenance.py +105 -0
  58. albert/recorder.py +166 -0
  59. albert/release_gate.py +83 -0
  60. albert/schemas.py +617 -0
  61. albert/scope.py +26 -0
  62. albert/search.py +447 -0
  63. albert/security.py +150 -0
  64. albert/services.py +1316 -0
  65. albert/session_context.py +162 -0
  66. albert/trace_feed.py +165 -0
  67. albert/trace_writer.py +131 -0
  68. albert/tracing.py +75 -0
  69. albert/worker.py +202 -0
  70. albert/workspaces.py +256 -0
  71. albert_memory-0.4.0.dist-info/METADATA +554 -0
  72. albert_memory-0.4.0.dist-info/RECORD +74 -0
  73. albert_memory-0.4.0.dist-info/WHEEL +4 -0
  74. albert_memory-0.4.0.dist-info/entry_points.txt +14 -0
albert/search.py ADDED
@@ -0,0 +1,447 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ import re
6
+ from collections import defaultdict
7
+ from datetime import UTC, datetime
8
+ from typing import Any
9
+ from uuid import UUID
10
+
11
+ from sqlalchemy import Float, cast, func, literal_column, or_, select, text
12
+ from sqlalchemy.orm import Session
13
+
14
+ from albert.config import get_settings
15
+ from albert.embeddings import get_embedder
16
+ from albert.graph_store import get_graph_store
17
+ from albert.models import Memory, MemoryChunk
18
+ from albert.recorder import cap_candidates, current_recorder, span
19
+ from albert.schemas import SearchHit, SearchRequest, SearchResponse
20
+ from albert.scope import in_workspace
21
+
22
+ RRF_K = 60
23
+ logger = logging.getLogger("albert.search")
24
+
25
+
26
+ def _scope_conditions(
27
+ *,
28
+ organization_id: UUID,
29
+ workspace_id: UUID | None,
30
+ request: SearchRequest,
31
+ ) -> list[Any]:
32
+ conditions: list[Any] = [
33
+ Memory.organization_id == organization_id,
34
+ Memory.status == "active",
35
+ ]
36
+ conditions.append(in_workspace(Memory.workspace_id, workspace_id))
37
+ if request.project_ref is not None:
38
+ conditions.append(Memory.project_ref == request.project_ref)
39
+ if request.task_ref is not None:
40
+ conditions.append(Memory.task_ref == request.task_ref)
41
+ if request.run_ref is not None:
42
+ conditions.append(Memory.run_ref == request.run_ref)
43
+ if request.memory_types:
44
+ conditions.append(Memory.memory_type.in_(request.memory_types))
45
+ if request.sensitivity:
46
+ conditions.append(Memory.sensitivity.in_(request.sensitivity))
47
+ when = request.temporal_as_of or datetime.now(UTC)
48
+ conditions.extend(
49
+ [Memory.valid_from <= when, or_(Memory.valid_until.is_(None), Memory.valid_until > when)]
50
+ )
51
+ return conditions
52
+
53
+
54
+ # A memory matches when it shares any query term; ts_rank_cd then ranks by how
55
+ # many terms it covers and how close together they are. plainto_tsquery ANDs
56
+ # every term, so a natural-language prompt (what recall hooks send) matched
57
+ # nothing. ts_rank_cd has no IDF and ranks every OR match, so a long query keeps
58
+ # only its rarest terms that occur in this tenant's memories (Hindsight caps
59
+ # terms the same way after long OR queries caused production timeouts). The cap
60
+ # is ALBERT_LEXICAL_MAX_TERMS.
61
+ # Document frequency is counted up to this cap: enough to rank rare terms
62
+ # exactly while a common term costs at most this many index hits.
63
+ TERM_FREQUENCY_CAP = 1000
64
+
65
+
66
+ def _rarest_lexemes(session: Session, lexemes: list[str], organization_id: UUID) -> list[str]:
67
+ """Keep the lexical_max_terms rarest lexemes that occur in this organization."""
68
+ limit = get_settings().lexical_max_terms
69
+ if len(lexemes) <= limit:
70
+ return lexemes
71
+ rows = session.execute(
72
+ text(
73
+ "SELECT term, (SELECT count(*) FROM (SELECT 1 FROM memories AS m "
74
+ "WHERE m.organization_id = :organization_id AND m.status = 'active' "
75
+ "AND m.search_vector @@ plainto_tsquery('simple', term) LIMIT :cap) AS hits) "
76
+ "FROM unnest(CAST(:terms AS text[])) AS term"
77
+ ),
78
+ {"organization_id": organization_id, "terms": lexemes, "cap": TERM_FREQUENCY_CAP},
79
+ ).all()
80
+ # A term no memory contains can only waste a slot; longer terms break ties.
81
+ present = [(int(count), term) for term, count in rows if int(count) > 0]
82
+ present.sort(key=lambda item: (item[0], -len(item[1]), item[1]))
83
+ return [term for _count, term in present[:limit]]
84
+
85
+
86
+ def _any_term_query(session: Session, query: str, organization_id: UUID): # type: ignore[no-untyped-def]
87
+ """OR of the query's English lexemes, or None when none can match."""
88
+ lexemes = session.scalar(
89
+ text("SELECT tsvector_to_array(to_tsvector('english', :query))"), {"query": query}
90
+ )
91
+ if not lexemes:
92
+ return None
93
+ terms = _rarest_lexemes(session, list(lexemes), organization_id)
94
+ if not terms:
95
+ return None
96
+ # Lexemes are already normalized; the 'simple' config keeps them unchanged.
97
+ combined = func.plainto_tsquery(literal_column("'simple'::regconfig"), terms[0])
98
+ for term in terms[1:]:
99
+ combined = combined.op("||")(
100
+ func.plainto_tsquery(literal_column("'simple'::regconfig"), term)
101
+ )
102
+ return combined
103
+
104
+
105
+ def _lexical_search(
106
+ session: Session,
107
+ *,
108
+ organization_id: UUID,
109
+ workspace_id: UUID | None,
110
+ request: SearchRequest,
111
+ ) -> list[tuple[Memory, float]]:
112
+ conditions = _scope_conditions(
113
+ organization_id=organization_id, workspace_id=workspace_id, request=request
114
+ )
115
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
116
+ # memories.search_vector is a stored generated tsvector (migration 0003)
117
+ # with a GIN index; matching on the column keeps the index usable and
118
+ # avoids recomputing to_tsvector for every ranked row.
119
+ document = literal_column("memories.search_vector")
120
+ query = _any_term_query(session, request.query, organization_id)
121
+ if query is None:
122
+ return []
123
+ rank = func.ts_rank_cd(document, query)
124
+ statement = (
125
+ select(Memory, rank.label("lexical_rank"))
126
+ .where(*conditions, document.op("@@")(query))
127
+ .order_by(rank.desc())
128
+ .limit(request.limit * 3)
129
+ )
130
+ return [(memory, float(score)) for memory, score in session.execute(statement)]
131
+
132
+ terms = [term for term in re.findall(r"[\w.-]+", request.query.casefold()) if term]
133
+ rows = list(session.scalars(select(Memory).where(*conditions)))
134
+
135
+ def score(memory: Memory) -> int:
136
+ text = f"{memory.subject} {memory.content}".casefold()
137
+ return sum(text.count(term) for term in terms)
138
+
139
+ ranked = [(row, float(score(row))) for row in rows if score(row) > 0]
140
+ return sorted(ranked, key=lambda item: item[1], reverse=True)[: request.limit * 3]
141
+
142
+
143
+ def _cosine(left: list[float], right: list[float]) -> float:
144
+ if not left or len(left) != len(right):
145
+ return -1.0
146
+ denominator = math.sqrt(sum(x * x for x in left)) * math.sqrt(sum(x * x for x in right))
147
+ return sum(x * y for x, y in zip(left, right, strict=True)) / denominator if denominator else -1
148
+
149
+
150
+ def _enable_iterative_scan(session: Session) -> None:
151
+ """Let pgvector keep scanning until the filtered result is full.
152
+
153
+ An HNSW scan returns ef_search candidates and only then applies the tenant,
154
+ workspace and sensitivity predicates; a small tenant inside a large table
155
+ can otherwise get zero vector hits. relaxed_order may return rows slightly
156
+ out of distance order, so callers re-sort.
157
+ """
158
+ try:
159
+ with session.begin_nested():
160
+ session.execute(text("SET LOCAL hnsw.iterative_scan = relaxed_order"))
161
+ except Exception: # pragma: no cover - older pgvector without the GUC
162
+ logger.warning("hnsw.iterative_scan unavailable; small tenants may lose vector hits")
163
+
164
+
165
+ def _vector_search(
166
+ session: Session,
167
+ *,
168
+ organization_id: UUID,
169
+ workspace_id: UUID | None,
170
+ request: SearchRequest,
171
+ ) -> list[tuple[Memory, float, int]]:
172
+ """Best-matching chunk per memory as (memory, similarity, chunk_index)."""
173
+ embedder = get_embedder()
174
+ query_vector = embedder.embed(request.query)
175
+ conditions = _scope_conditions(
176
+ organization_id=organization_id, workspace_id=workspace_id, request=request
177
+ )
178
+ # Vectors from another model live in a different space; comparing them to
179
+ # this query would rank noise. They are re-embedded by reindex-memories.
180
+ conditions.extend(
181
+ [
182
+ MemoryChunk.organization_id == organization_id,
183
+ MemoryChunk.embedding_model == embedder.name,
184
+ MemoryChunk.embedding.is_not(None),
185
+ ]
186
+ )
187
+ minimum = get_settings().min_vector_similarity
188
+ candidate_limit = request.limit * 6
189
+ best: dict[UUID, tuple[Memory, float, int]] = {}
190
+
191
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
192
+ _enable_iterative_scan(session)
193
+ distance = cast(MemoryChunk.embedding.op("<=>")(query_vector), Float)
194
+ rows = session.execute(
195
+ select(Memory, MemoryChunk.chunk_index, distance.label("vector_distance"))
196
+ .join(MemoryChunk, MemoryChunk.memory_id == Memory.id)
197
+ .where(*conditions)
198
+ .order_by(distance)
199
+ .limit(candidate_limit)
200
+ )
201
+ scored = [(memory, 1.0 - float(value), index) for memory, index, value in rows]
202
+ else:
203
+ rows = session.execute(
204
+ select(Memory, MemoryChunk.chunk_index, MemoryChunk.embedding)
205
+ .join(MemoryChunk, MemoryChunk.memory_id == Memory.id)
206
+ .where(*conditions)
207
+ )
208
+ scored = [
209
+ (memory, _cosine(embedding or [], query_vector), index)
210
+ for memory, index, embedding in rows
211
+ ]
212
+
213
+ for memory, similarity, index in scored:
214
+ if similarity < minimum:
215
+ continue
216
+ current = best.get(memory.id)
217
+ if current is None or similarity > current[1]:
218
+ best[memory.id] = (memory, similarity, index)
219
+ ordered = sorted(best.values(), key=lambda item: item[1], reverse=True)
220
+ return ordered[: request.limit * 3]
221
+
222
+
223
+ def _filters(request: SearchRequest, workspace_id: UUID | None) -> dict[str, Any]:
224
+ return {
225
+ "workspace_id": str(workspace_id) if workspace_id else None,
226
+ "project_ref": request.project_ref,
227
+ "task_ref": request.task_ref,
228
+ "run_ref": request.run_ref,
229
+ "branch_ref": request.branch_ref,
230
+ "memory_types": request.memory_types,
231
+ "sensitivity": request.sensitivity,
232
+ "temporal_as_of": request.temporal_as_of.isoformat() if request.temporal_as_of else None,
233
+ }
234
+
235
+
236
+ def _candidates(items: list[tuple[Any, float]], kind: str) -> list[dict[str, Any]]:
237
+ return cap_candidates(
238
+ [
239
+ {"id": str(ident), "kind": kind, "score": score, "rank": rank}
240
+ for rank, (ident, score) in enumerate(items, start=1)
241
+ ]
242
+ )
243
+
244
+
245
+ def _memory_hit(memory: Memory, request: SearchRequest, backend: str, score: float) -> SearchHit:
246
+ provenance = memory.metadata_.get("provenance", {})
247
+ if not isinstance(provenance, dict):
248
+ provenance = {}
249
+ return SearchHit(
250
+ memory_id=memory.id,
251
+ kind="memory",
252
+ subject=memory.subject,
253
+ content=memory.content if request.include_content else "",
254
+ score=0,
255
+ backends=[],
256
+ source_episode_id=memory.episode_id,
257
+ metadata={
258
+ "memory_type": memory.memory_type,
259
+ "sensitivity": memory.sensitivity,
260
+ "confidence": memory.confidence,
261
+ "project_ref": memory.project_ref,
262
+ "task_ref": memory.task_ref,
263
+ "run_ref": memory.run_ref,
264
+ "valid_from": memory.valid_from.isoformat(),
265
+ "updated_at": memory.updated_at.isoformat(),
266
+ "provenance": provenance,
267
+ "capture_source_trust": memory.metadata_.get("capture_source_trust", "verified"),
268
+ "quarantined": bool(memory.metadata_.get("quarantined", False)),
269
+ "backend_scores": {backend: score},
270
+ },
271
+ )
272
+
273
+
274
+ def _exclude_quarantined_relationships(session: Session, relationships: list[Any]) -> list[Any]:
275
+ source_ids = {item.source_memory_id for item in relationships if item.source_memory_id}
276
+ if not source_ids:
277
+ return relationships
278
+ memories = session.scalars(select(Memory).where(Memory.id.in_(source_ids)))
279
+ quarantined = {memory.id for memory in memories if (memory.metadata_ or {}).get("quarantined")}
280
+ return [item for item in relationships if item.source_memory_id not in quarantined]
281
+
282
+
283
+ def hybrid_search(
284
+ session: Session,
285
+ *,
286
+ organization_id: UUID,
287
+ workspace_id: UUID | None,
288
+ request: SearchRequest,
289
+ allowed_sensitivities: list[str],
290
+ ) -> SearchResponse:
291
+ ranked: list[tuple[str, list[tuple[str, SearchHit]]]] = []
292
+ degraded: list[str] = []
293
+ filters = _filters(request, workspace_id)
294
+
295
+ with span("lexical", filters=filters) as handle:
296
+ lexical = _lexical_search(
297
+ session, organization_id=organization_id, workspace_id=workspace_id, request=request
298
+ )
299
+ handle.set(
300
+ candidates_total=len(lexical),
301
+ candidates=_candidates([(m.id, s) for m, s in lexical], "memory"),
302
+ )
303
+ ranked.append(
304
+ (
305
+ "lexical",
306
+ [(f"memory:{m.id}", _memory_hit(m, request, "lexical", s)) for m, s in lexical],
307
+ )
308
+ )
309
+
310
+ try:
311
+ with span(
312
+ "vector",
313
+ filters=filters,
314
+ embedding_model=get_embedder().name,
315
+ min_similarity=get_settings().min_vector_similarity,
316
+ ) as handle:
317
+ vectors = _vector_search(
318
+ session,
319
+ organization_id=organization_id,
320
+ workspace_id=workspace_id,
321
+ request=request,
322
+ )
323
+ handle.set(
324
+ candidates_total=len(vectors),
325
+ candidates=_candidates([(m.id, s) for m, s, _i in vectors], "memory"),
326
+ )
327
+ vector_hits = []
328
+ for memory, similarity, chunk_index in vectors:
329
+ hit = _memory_hit(memory, request, "vector", similarity)
330
+ hit.metadata["chunk_index"] = chunk_index
331
+ vector_hits.append((f"memory:{memory.id}", hit))
332
+ ranked.append(("vector", vector_hits))
333
+ except Exception as exc:
334
+ logger.exception("Vector retrieval failed")
335
+ degraded.append(f"vector retrieval unavailable: {type(exc).__name__}")
336
+
337
+ if request.include_graph:
338
+ try:
339
+ with span("graph", filters=filters) as handle:
340
+ relationships = get_graph_store().query(
341
+ session,
342
+ organization_id=organization_id,
343
+ workspace_id=workspace_id,
344
+ query=request.query,
345
+ temporal_as_of=request.temporal_as_of,
346
+ limit=request.limit * 3,
347
+ sensitivities=allowed_sensitivities,
348
+ )
349
+ relationships = _exclude_quarantined_relationships(session, relationships)
350
+ handle.set(
351
+ candidates_total=len(relationships),
352
+ candidates=_candidates(
353
+ [(r.id, r.confidence) for r in relationships], "relationship"
354
+ ),
355
+ )
356
+ ranked.append(
357
+ (
358
+ "graph",
359
+ [
360
+ (
361
+ f"relationship:{relationship.id}",
362
+ SearchHit(
363
+ memory_id=relationship.source_memory_id,
364
+ kind="relationship",
365
+ subject=relationship.relation_type,
366
+ content=(
367
+ f"{relationship.source_name} "
368
+ f"{relationship.relation_type.replace('_', ' ')} "
369
+ f"{relationship.target_name}"
370
+ if request.include_content
371
+ else ""
372
+ ),
373
+ score=0,
374
+ backends=[],
375
+ metadata={
376
+ "relationship_id": str(relationship.id),
377
+ "source_entity_id": str(relationship.source_entity_id),
378
+ "target_entity_id": str(relationship.target_entity_id),
379
+ "confidence": relationship.confidence,
380
+ "backend_scores": {"graph": relationship.confidence},
381
+ },
382
+ ),
383
+ )
384
+ for relationship in relationships
385
+ ],
386
+ )
387
+ )
388
+ except Exception as exc:
389
+ logger.exception("Graph retrieval failed")
390
+ degraded.append(f"graph retrieval unavailable: {type(exc).__name__}")
391
+
392
+ with span("fuse", k=RRF_K) as handle:
393
+ scores: dict[str, float] = defaultdict(float)
394
+ contributions: dict[str, dict[str, float]] = defaultdict(dict)
395
+ hits: dict[str, SearchHit] = {}
396
+ backend_names: dict[str, list[str]] = defaultdict(list)
397
+ for backend, backend_hits in ranked:
398
+ for rank, (key, hit) in enumerate(backend_hits, start=1):
399
+ contribution = 1.0 / (RRF_K + rank)
400
+ scores[key] += contribution
401
+ contributions[key][backend] = round(contribution, 6)
402
+ if key in hits:
403
+ existing_scores = hits[key].metadata.setdefault("backend_scores", {})
404
+ existing_scores.update(hit.metadata.get("backend_scores", {}))
405
+ for name, value in hit.metadata.items():
406
+ hits[key].metadata.setdefault(name, value)
407
+ else:
408
+ hits[key] = hit
409
+ backend_names[key].append(backend)
410
+ if request.branch_ref:
411
+ for key, hit in hits.items():
412
+ provenance = hit.metadata.get("provenance", {})
413
+ if (
414
+ provenance.get("branch") == request.branch_ref
415
+ or provenance.get("ref") == request.branch_ref
416
+ ):
417
+ scores[key] += 1.0 / (RRF_K + 1)
418
+ contributions[key]["branch_preference"] = round(1.0 / (RRF_K + 1), 6)
419
+ ordered = sorted(hits, key=lambda key: scores[key], reverse=True)
420
+ ordered = [key for key in ordered if not hits[key].metadata.get("quarantined")][
421
+ : request.limit
422
+ ]
423
+ result = []
424
+ for key in ordered:
425
+ hit = hits[key]
426
+ hit.score = scores[key]
427
+ hit.backends = backend_names[key]
428
+ result.append(hit)
429
+ handle.set(
430
+ candidates_total=len(hits),
431
+ hits=[
432
+ {
433
+ "id": key.split(":", 1)[1],
434
+ "kind": key.split(":", 1)[0],
435
+ "rank": rank,
436
+ "rrf": contributions[key],
437
+ "backends": backend_names[key],
438
+ }
439
+ for rank, key in enumerate(ordered, start=1)
440
+ ],
441
+ degraded=degraded,
442
+ )
443
+ if degraded:
444
+ recorder = current_recorder()
445
+ if recorder is not None:
446
+ recorder.status = "degraded"
447
+ return SearchResponse(hits=result, degraded=degraded)
albert/security.py ADDED
@@ -0,0 +1,150 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import secrets
6
+ from dataclasses import dataclass
7
+ from datetime import UTC, datetime, timedelta
8
+ from uuid import UUID
9
+
10
+ from fastapi import Depends, HTTPException, status
11
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
12
+ from sqlalchemy import select
13
+ from sqlalchemy.orm import Session
14
+
15
+ from albert.config import get_settings
16
+ from albert.db import get_session
17
+ from albert.models import APIKey, Principal
18
+ from albert.recorder import current_recorder, span
19
+
20
+ bearer = HTTPBearer(auto_error=False)
21
+ # Writing last_used_at on every request turns a shared agent key into a hot row.
22
+ LAST_USED_WRITE_INTERVAL = timedelta(seconds=60)
23
+
24
+ ALL_CAPABILITIES = [
25
+ "memory.read",
26
+ "memory.write",
27
+ "memory.review",
28
+ # Lets a workspace-scoped key write and change the organization-wide memories
29
+ # every workspace shares. An organization-wide key always can.
30
+ "memory.write.organization",
31
+ "memory.delete",
32
+ "memory.export",
33
+ "memory.import",
34
+ "graph.query",
35
+ "graph.write",
36
+ "working_memory.read",
37
+ "working_memory.write",
38
+ "locks.acquire",
39
+ "capture.write",
40
+ "capture.system",
41
+ "console.read",
42
+ "keys.manage",
43
+ "admin",
44
+ ]
45
+ KNOWN_CAPABILITIES = frozenset({*ALL_CAPABILITIES, "memory.confidential", "memory.restricted"})
46
+ # What a keys.manage holder may hand out. Never the power to mint more keys or
47
+ # admin, so a leaked issued credential cannot escalate.
48
+ GRANTABLE_CAPABILITIES = sorted(KNOWN_CAPABILITIES - {"admin", "keys.manage"})
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class AuthContext:
53
+ principal_id: UUID
54
+ organization_id: UUID
55
+ workspace_id: UUID | None
56
+ capabilities: frozenset[str]
57
+
58
+ def require(self, capability: str) -> None:
59
+ if "admin" not in self.capabilities and capability not in self.capabilities:
60
+ raise HTTPException(
61
+ status_code=status.HTTP_403_FORBIDDEN,
62
+ detail=f"Missing capability: {capability}",
63
+ )
64
+
65
+ def allowed_sensitivities(self) -> list[str]:
66
+ allowed = ["public", "internal"]
67
+ if "admin" in self.capabilities or "memory.confidential" in self.capabilities:
68
+ allowed.append("confidential")
69
+ if "admin" in self.capabilities or "memory.restricted" in self.capabilities:
70
+ allowed.append("restricted")
71
+ return allowed
72
+
73
+
74
+ def _digest(value: str) -> bytes:
75
+ pepper = get_settings().api_key_pepper.get_secret_value().encode()
76
+ return hmac.new(pepper, value.encode(), hashlib.sha256).digest()
77
+
78
+
79
+ def _as_utc(value: datetime) -> datetime:
80
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
81
+
82
+
83
+ def issue_api_key() -> tuple[str, str, bytes]:
84
+ prefix = secrets.token_urlsafe(9).replace("-", "").replace("_", "")[:12]
85
+ secret = secrets.token_urlsafe(32)
86
+ value = f"alb_{prefix}_{secret}"
87
+ return value, prefix, _digest(value)
88
+
89
+
90
+ def hash_lock_token(value: str) -> bytes:
91
+ return _digest(f"lock:{value}")
92
+
93
+
94
+ def verify_lock_token(value: str, expected: bytes) -> bool:
95
+ return hmac.compare_digest(hash_lock_token(value), expected)
96
+
97
+
98
+ def parse_api_key(value: str) -> tuple[str, str] | None:
99
+ parts = value.split("_", 2)
100
+ if len(parts) != 3 or parts[0] != "alb" or not parts[1] or not parts[2]:
101
+ return None
102
+ return parts[1], value
103
+
104
+
105
+ def authenticate(
106
+ credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
107
+ session: Session = Depends(get_session),
108
+ ) -> AuthContext:
109
+ if credentials is None or credentials.scheme.lower() != "bearer":
110
+ raise HTTPException(status_code=401, detail="Bearer API key required")
111
+ with span("auth") as handle:
112
+ parsed = parse_api_key(credentials.credentials)
113
+ if parsed is None:
114
+ raise HTTPException(status_code=401, detail="Invalid API key")
115
+ prefix, raw = parsed
116
+ handle.set(prefix=prefix)
117
+ record = session.scalar(
118
+ select(APIKey).where(APIKey.prefix == prefix, APIKey.active.is_(True))
119
+ )
120
+ now = datetime.now(UTC)
121
+ if (
122
+ record is None
123
+ or not hmac.compare_digest(record.key_hash, _digest(raw))
124
+ or (record.expires_at is not None and _as_utc(record.expires_at) <= now)
125
+ or not record.principal.active
126
+ ):
127
+ raise HTTPException(status_code=401, detail="Invalid or expired API key")
128
+ last_used = record.last_used_at
129
+ if last_used is None or now - _as_utc(last_used) >= LAST_USED_WRITE_INTERVAL:
130
+ record.last_used_at = now
131
+ session.commit()
132
+ principal: Principal = record.principal
133
+ handle.set(capabilities=sorted(record.capabilities or []))
134
+ recorder = current_recorder()
135
+ if recorder is not None:
136
+ recorder.set_identity(principal.organization_id, principal.id, principal.workspace_id)
137
+ return AuthContext(
138
+ principal_id=principal.id,
139
+ organization_id=principal.organization_id,
140
+ workspace_id=principal.workspace_id,
141
+ capabilities=frozenset(record.capabilities or []),
142
+ )
143
+
144
+
145
+ def require_capability(capability: str): # type: ignore[no-untyped-def]
146
+ def dependency(auth: AuthContext = Depends(authenticate)) -> AuthContext:
147
+ auth.require(capability)
148
+ return auth
149
+
150
+ return dependency