-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth_proxy.py
More file actions
4736 lines (4285 loc) · 330 KB
/
Copy pathauth_proxy.py
File metadata and controls
4736 lines (4285 loc) · 330 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import contextlib
import hashlib
import hmac
import json
import logging
import os
import re
import secrets
import settings
import time
from collections import defaultdict, deque
from datetime import datetime, timezone
from pathlib import Path
from threading import RLock
from typing import Any, Dict
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
import host_store
from env_secrets import load_env_secrets
from shim import _CACHE_READ_FACTOR # the billing cache-read discount — one source
# Operator-managed keys/consumer-hashes live on the PVC (.env.secrets) and are
# the source of truth — load them over the container env BEFORE reading any of
# the values below, so dashboard edits survive pod restarts.
load_env_secrets()
UPSTREAM = os.getenv("ROUTER_UPSTREAM", "http://router:18080").rstrip("/")
CALLER_KEYS_JSON = os.getenv("CALLER_KEYS_JSON", "{}")
CALLER_KEYS_SHA256_JSON = os.getenv("CALLER_KEYS_SHA256_JSON", "{}")
RATE_PER_MIN = int(os.getenv("RATE_PER_MIN", "600"))
BURST = int(os.getenv("BURST", "200"))
RECENT_LIMIT = int(os.getenv("DASHBOARD_RECENT_LIMIT", "200"))
DASHBOARD_TRUSTED_USER_HEADER = os.getenv("DASHBOARD_TRUSTED_USER_HEADER", "").strip()
DASHBOARD_TRUSTED_USER_SECRET = os.getenv("DASHBOARD_TRUSTED_USER_SECRET", "")
DASHBOARD_PASSWORD_SHA256 = os.getenv("DASHBOARD_PASSWORD_SHA256", "")
DASHBOARD_SESSION_SECRET = os.getenv("DASHBOARD_SESSION_SECRET", "")
# Local-dev escape hatch: when truthy, the dashboard skips auth entirely and every
# request is treated as a local admin. OFF by default — never enable in a
# deployment reachable by anyone but you.
DASHBOARD_NO_AUTH = os.getenv("DASHBOARD_NO_AUTH", "").strip().lower() in ("1", "true", "yes", "on")
DASHBOARD_COOKIE_NAME = os.getenv("DASHBOARD_COOKIE_NAME", "router_dashboard_session")
DASHBOARD_COOKIE_MAX_AGE = int(os.getenv("DASHBOARD_COOKIE_MAX_AGE", "2592000"))
DASHBOARD_COOKIE_PATH = os.getenv("DASHBOARD_COOKIE_PATH", "/dashboard")
DASHBOARD_KEY_ENV_PATH = os.getenv("DASHBOARD_KEY_ENV_PATH", "/run/llm-router/.env.secrets")
CODEX_ACCOUNTS_DIR = os.getenv("CODEX_ACCOUNTS_DIR", "/codex/accounts")
CODEX_AUTH_PATH = os.getenv("CODEX_AUTH_PATH") or None
DASHBOARD_KEY_PREFIX = os.getenv("DASHBOARD_KEY_PREFIX", "llmr")
DEFAULT_ROTATION_GRACE_S = int(os.getenv("DASHBOARD_KEY_ROTATION_GRACE_S", "86400"))
DASHBOARD_POLICY_CONFIG_PATH = os.getenv("DASHBOARD_POLICY_CONFIG_PATH", "config.live.lua")
DASHBOARD_POLICY_METRICS_PATH = os.getenv("DASHBOARD_POLICY_METRICS_PATH", "metrics.live.lua")
DASHBOARD_POLICY_DIR = os.getenv("DASHBOARD_POLICY_DIR", "policies")
ROUTER_CONTEXT_LENGTH = int(os.getenv("ROUTER_CONTEXT_LENGTH", "200000"))
ROUTE_HEALTH_ROUTES = [r.strip() for r in os.getenv("DASHBOARD_ROUTE_HEALTH_ROUTES", "profile:default").split(",") if r.strip()]
SYNTHETIC_PROBES_ENABLED = os.getenv("DASHBOARD_SYNTHETIC_PROBES_ENABLED", "1").lower() not in {"0", "false", "no", "off"}
SYNTHETIC_PROBE_INTERVAL_S = float(os.getenv("DASHBOARD_SYNTHETIC_PROBE_INTERVAL_S", "300"))
SYNTHETIC_PROBE_INITIAL_DELAY_S = float(os.getenv("DASHBOARD_SYNTHETIC_PROBE_INITIAL_DELAY_S", "45"))
SYNTHETIC_PROBE_TIMEOUT_S = float(os.getenv("DASHBOARD_SYNTHETIC_PROBE_TIMEOUT_S", "45"))
SYNTHETIC_PROBE_CALLER = os.getenv("DASHBOARD_SYNTHETIC_PROBE_CALLER", "dashboard-probe")
def _load_caller_map(raw: str, name: str) -> Dict[str, str]:
try:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError(f"{name} must be a JSON object")
if not all(isinstance(k, str) and isinstance(v, str) for k, v in data.items()):
raise ValueError(f"{name} keys and values must be strings")
return data
except Exception as exc:
raise RuntimeError(f"invalid {name}: {exc}") from exc
CALLER_KEYS: Dict[str, str] = _load_caller_map(CALLER_KEYS_JSON, "CALLER_KEYS_JSON")
CALLER_KEY_HASHES: Dict[str, str] = _load_caller_map(CALLER_KEYS_SHA256_JSON, "CALLER_KEYS_SHA256_JSON")
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(message)s")
log = logging.getLogger("llm-router-auth-proxy")
app = FastAPI(title="llm-router auth proxy", docs_url=None, redoc_url=None)
_client: httpx.AsyncClient | None = None
_probe_task: asyncio.Task[None] | None = None
_windows: dict[str, deque[float]] = defaultdict(deque)
_started_wall = time.time()
_stats_lock = RLock()
def _counter() -> dict[str, Any]:
return {
"requests": 0,
"errors": 0,
"tokens_in": 0,
"tokens_out": 0,
"tokens_total": 0,
"latency_ms_total": 0.0,
"latency_ms_max": 0.0,
"last_seen": None,
}
def _new_stats() -> dict[str, Any]:
return {
"total_requests": 0,
"total_rejects": 0,
"total_errors": 0,
"total_tokens_in": 0,
"total_tokens_out": 0,
"total_tokens": 0,
"by_caller": defaultdict(_counter),
"by_provider": defaultdict(_counter),
"by_model_family": defaultdict(_counter),
"by_route": defaultdict(_counter),
"by_served_model": defaultdict(_counter),
"by_status": defaultdict(int),
"by_caller_provider": defaultdict(lambda: defaultdict(_counter)),
"by_caller_model_family": defaultdict(lambda: defaultdict(_counter)),
"by_caller_route": defaultdict(lambda: defaultdict(_counter)),
"by_caller_served_model": defaultdict(lambda: defaultdict(_counter)),
"by_caller_status": defaultdict(lambda: defaultdict(int)),
"by_key_sha256": defaultdict(_counter),
"by_key_provider": defaultdict(lambda: defaultdict(_counter)),
"by_key_model_family": defaultdict(lambda: defaultdict(_counter)),
"by_key_route": defaultdict(lambda: defaultdict(_counter)),
"by_key_served_model": defaultdict(lambda: defaultdict(_counter)),
"by_key_status": defaultdict(lambda: defaultdict(int)),
"key_owner": {},
"recent": deque(maxlen=RECENT_LIMIT),
"synthetic_route_health": {},
}
_stats: dict[str, Any] = _new_stats()
# Short TTL cache over the SQL-derived dashboard snapshots (stats bundle, the
# logins/provider-keys rollups) so the dashboard's 15s auto-refresh and multiple
# concurrent viewers don't re-run the window aggregation per request. Keyed by
# the full query tuple; invalidated by TTL only (freshness lag <= the TTL, less
# than the frontend's own refresh period). Never used for timeframe="runtime"
# (that path is in-memory and already O(1)).
_SNAPSHOT_TTL_S = float(os.getenv("DASHBOARD_STATS_TTL_S", "12"))
_snapshot_cache: dict[tuple, tuple[float, Any]] = {}
_snapshot_cache_lock = RLock()
def _snapshot_cache_get(key: tuple) -> Any:
if _SNAPSHOT_TTL_S <= 0:
return None
with _snapshot_cache_lock:
hit = _snapshot_cache.get(key)
if hit and (time.monotonic() - hit[0]) < _SNAPSHOT_TTL_S:
return hit[1]
return None
def _snapshot_cache_put(key: tuple, value: Any) -> None:
if _SNAPSHOT_TTL_S <= 0:
return
with _snapshot_cache_lock:
if len(_snapshot_cache) > 256: # bound the key space (bad params etc.)
_snapshot_cache.clear()
_snapshot_cache[key] = (time.monotonic(), value)
def _snapshot_cache_clear() -> None:
with _snapshot_cache_lock:
_snapshot_cache.clear()
def _reset_stats_for_tests() -> None:
"""Reset in-memory counters. Drains the host-store write queue first so a
just-recorded call has landed in the `calls` ledger before the test reads the
derived stats back (the persistent store now backs them, #5). Also drops the
snapshot TTL cache so the next read reflects the reset."""
host_store._write_q.join()
_snapshot_cache_clear()
with _stats_lock:
_stats.clear()
_stats.update(_new_stats())
def _consumers() -> list[str]:
return sorted(set(CALLER_KEYS.values()) | set(CALLER_KEY_HASHES.values()) | set(_load_issued_keys().keys()))
def _safe_consumer_name(raw: str) -> str:
name = re.sub(r"[^A-Za-z0-9_.:-]+", "-", (raw or "").strip()).strip("-._:")
if not name or len(name) > 80:
raise ValueError("consumer must be 1-80 chars: letters, numbers, dot, underscore, colon, or dash")
return name
def _write_json_file(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n")
tmp.chmod(0o600)
tmp.replace(path)
path.chmod(0o600)
def _upsert_env_line(path: Path, key: str, value: str) -> None:
"""Set KEY=value in an env file (used for provider API keys). Same
semantics as _upsert_env_json but for plain string values."""
path.parent.mkdir(parents=True, exist_ok=True)
lines = path.read_text().splitlines() if path.exists() else []
rendered = f"{key}={value}"
out: list[str] = []
replaced = False
for line in lines:
if line.startswith(key + "="):
out.append(rendered)
replaced = True
else:
out.append(line)
if not replaced:
out.append(rendered)
path.write_text("\n".join(out) + "\n")
path.chmod(0o600)
def _upsert_env_json(path: Path, key: str, value: dict[str, str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
lines = path.read_text().splitlines() if path.exists() else []
rendered = key + "=" + json.dumps(value, sort_keys=True, separators=(",", ":"))
out: list[str] = []
replaced = False
for line in lines:
if line.startswith(key + "="):
out.append(rendered)
replaced = True
else:
out.append(line)
if not replaced:
out.append(rendered)
path.write_text("\n".join(out) + "\n")
path.chmod(0o600)
_issued_keys_load_failed = False
def _load_issued_keys() -> dict[str, Any]:
global _issued_keys_load_failed
records, ok = host_store.get_consumer_keys()
_issued_keys_load_failed = not ok
return records
def _clean_route_list(value: Any) -> list[str]:
if value is None or value == "":
return []
if isinstance(value, str):
items = re.split(r"[\s,]+", value)
elif isinstance(value, list):
items = [str(v) for v in value]
else:
return []
out = []
for item in items:
route = item.strip()
if route and len(route) <= 160 and route not in out:
out.append(route)
return out
def _optional_int(value: Any, *, min_value: int = 0, max_value: int | None = 1_000_000) -> int | None:
if value is None or value == "":
return None
try:
ivalue = int(value)
except (TypeError, ValueError):
return None
if max_value is not None:
ivalue = min(max_value, ivalue)
return max(min_value, ivalue)
def _normalize_key_record(record: Any) -> dict[str, Any] | None:
if not isinstance(record, dict):
return None
prefix = str(record.get("sha256_prefix") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{8,64}", prefix):
return None
status = str(record.get("status") or "active").strip().lower()
if status not in {"active", "revoked"}:
status = "revoked"
out = {
"sha256_prefix": prefix,
"status": status,
"created_at": _optional_int(record.get("created_at"), max_value=None),
"viewer": str(record.get("viewer") or "")[:80] or None,
"expires_at": _optional_int(record.get("expires_at"), max_value=None),
"revoked_at": _optional_int(record.get("revoked_at"), max_value=None),
"replaced_at": _optional_int(record.get("replaced_at"), max_value=None),
}
return {k: v for k, v in out.items() if v is not None}
def _normalize_consumer_record(consumer: str, record: Any) -> dict[str, Any]:
now = int(time.time())
if record is None:
record = {}
elif not isinstance(record, dict):
return {"status": "inactive", "allowed_routes": [], "rate_per_min": None, "burst": None, "keys": [], "updated_at": now}
status = str(record.get("status") or "active").strip().lower()
if status not in {"active", "inactive"}:
status = "inactive"
keys = []
if "keys" in record and not isinstance(record.get("keys"), list):
return {"status": "inactive", "allowed_routes": [], "rate_per_min": None, "burst": None, "keys": [], "updated_at": now}
raw_keys = record.get("keys") or []
for item in raw_keys:
normalized = _normalize_key_record(item)
if not normalized:
return {"status": "inactive", "allowed_routes": [], "rate_per_min": None, "burst": None, "keys": [], "updated_at": now}
keys.append(normalized)
# Backward compatibility with the older {consumer: {sha256_prefix, created_at, viewer}} shape.
legacy = _normalize_key_record(record)
if legacy and not any(k["sha256_prefix"] == legacy["sha256_prefix"] for k in keys):
keys.append(legacy)
for token, owner in CALLER_KEYS.items():
if owner == consumer:
digest = hashlib.sha256(token.encode()).hexdigest()
if not any(digest.startswith(k["sha256_prefix"]) for k in keys):
keys.append({"sha256_prefix": digest[:12], "status": "active", "storage": "CALLER_KEYS_JSON"})
for digest, owner in CALLER_KEY_HASHES.items():
if owner == consumer and not any(digest.startswith(k["sha256_prefix"]) for k in keys):
keys.append({"sha256_prefix": digest[:12], "status": "active", "storage": "CALLER_KEYS_SHA256_JSON"})
rate_per_min = _optional_int(record.get("rate_per_min"), min_value=1)
burst = _optional_int(record.get("burst"), min_value=1)
return {
"status": status,
"allowed_routes": _clean_route_list(record.get("allowed_routes")),
"rate_per_min": rate_per_min,
"burst": burst,
"keys": keys,
"updated_at": _optional_int(record.get("updated_at")) or now,
}
def _issued_consumer_records() -> dict[str, dict[str, Any]]:
issued = _load_issued_keys()
consumers = sorted(set(CALLER_KEYS.values()) | set(CALLER_KEY_HASHES.values()) | set(issued.keys()))
return {name: _normalize_consumer_record(name, issued.get(name)) for name in consumers}
def _write_issued_consumer_records(records: dict[str, dict[str, Any]]) -> bool:
"""Persist the consumer records; returns True on success, False on a
persistence failure — a swallowed failure would let a key rotation/revocation
be reported as saved while still working after a restart (a security hole)."""
compact = {}
for consumer, record in sorted(records.items()):
normalized = _normalize_consumer_record(consumer, record)
if normalized["status"] == "active" and not normalized["allowed_routes"] and normalized["rate_per_min"] is None and normalized["burst"] is None and not normalized["keys"]:
continue
compact[consumer] = normalized
return host_store.set_consumer_keys(compact)
def _consumer_meta(consumer: str) -> dict[str, Any]:
records = _issued_consumer_records()
if _issued_keys_load_failed:
meta = _normalize_consumer_record(consumer, {})
meta["status"] = "inactive"
return meta
return records.get(consumer, _normalize_consumer_record(consumer, {}))
def _active_key_rows(keys: list[dict[str, Any]]) -> list[dict[str, Any]]:
now = int(time.time())
rows = []
for key in keys:
row = dict(key)
if row.get("status") == "active" and row.get("expires_at") and int(row["expires_at"]) <= now:
row["status"] = "expired"
rows.append(row)
return rows
def _consumer_key_rows(by_caller_stats: dict[str, dict[str, Any]] | None = None) -> list[dict[str, Any]]:
records = _issued_consumer_records()
plaintext_counts: dict[str, int] = defaultdict(int)
hash_counts: dict[str, int] = defaultdict(int)
for consumer in CALLER_KEYS.values():
plaintext_counts[consumer] += 1
for consumer in CALLER_KEY_HASHES.values():
hash_counts[consumer] += 1
rows = []
for name in _consumers():
meta = records.get(name, _normalize_consumer_record(name, {}))
rows.append({
"consumer": name,
"configured": name in set(CALLER_KEYS.values()) or name in set(CALLER_KEY_HASHES.values()),
"status": meta.get("status", "active"),
"allowed_routes": meta.get("allowed_routes") or [],
"rate_per_min": meta.get("rate_per_min"),
"burst": meta.get("burst"),
"effective_rate_per_min": meta.get("rate_per_min") or RATE_PER_MIN,
"effective_burst": meta.get("burst") or BURST,
"issued_metadata": name in records,
"stored_raw_key": plaintext_counts.get(name, 0) > 0,
"plaintext_key_count": plaintext_counts.get(name, 0),
"hash_key_count": hash_counts.get(name, 0),
"keys": _active_key_rows(meta.get("keys") or []),
"stats": (by_caller_stats or {}).get(name) or _counter_snapshot(_stats["by_caller"].get(name, _counter())),
})
return rows
def _plaintext_key_rows_for_consumer(consumer: str) -> list[dict[str, Any]]:
rows = []
for token, owner in sorted(CALLER_KEYS.items(), key=lambda item: hashlib.sha256(item[0].encode()).hexdigest()):
if owner != consumer:
continue
digest = hashlib.sha256(token.encode()).hexdigest()
rows.append({
"consumer": owner,
"api_key": token,
"sha256_prefix": digest[:12],
"storage": "CALLER_KEYS_JSON",
})
return rows
def _extract_token(request: Request) -> str | None:
auth = request.headers.get("authorization") or ""
if auth.lower().startswith("bearer "):
return auth[7:].strip()
return None
def _caller_from_token(token: str | None) -> str | None:
auth = _caller_auth(token)
return auth.get("caller") if auth.get("ok") else None
def _key_record_allows(digest: str, meta: dict[str, Any]) -> tuple[bool, str | None]:
keys = meta.get("keys") or []
if not keys:
return True, None
matching = [k for k in keys if digest.startswith(str(k.get("sha256_prefix") or ""))]
if not matching:
return True, None
now = int(time.time())
for key in matching:
if key.get("status") == "revoked":
return False, "caller_key_revoked"
expires_at = int(key.get("expires_at") or 0)
if expires_at and expires_at <= now:
return False, "caller_key_expired"
return True, None
def _caller_auth(token: str | None) -> dict[str, Any]:
if not token:
return {"ok": False, "error_code": "caller_auth"}
digest = hashlib.sha256(token.encode()).hexdigest()
caller = CALLER_KEYS.get(token)
storage = "CALLER_KEYS_JSON" if caller else None
if not caller:
caller = CALLER_KEY_HASHES.get(digest)
storage = "CALLER_KEYS_SHA256_JSON" if caller else None
if not caller:
return {"ok": False, "error_code": "caller_auth"}
meta = _consumer_meta(caller)
if meta.get("status") != "active":
return {"ok": False, "caller": caller, "digest": digest, "storage": storage, "error_code": "caller_inactive"}
allowed, key_error = _key_record_allows(digest, meta)
if not allowed:
return {"ok": False, "caller": caller, "digest": digest, "storage": storage, "error_code": key_error}
return {"ok": True, "caller": caller, "digest": digest, "storage": storage, "meta": meta}
def _rate_ok(caller: str) -> bool:
meta = _consumer_meta(caller)
rate_per_min = int(meta.get("rate_per_min") or RATE_PER_MIN)
burst = int(meta.get("burst") or BURST)
now = time.monotonic()
q = _windows[caller]
cutoff = now - 60.0
while q and q[0] < cutoff:
q.popleft()
allowed = max(rate_per_min, burst)
if len(q) >= allowed:
return False
q.append(now)
return True
def _requested_route_from(path: str, body: bytes | None) -> str | None:
route = None
if body:
try:
parsed = json.loads(body.decode("utf-8"))
if isinstance(parsed, dict):
route = parsed.get("model") or parsed.get("name")
except Exception:
route = None
parts = [p for p in path.strip("/").split("/") if p]
if len(parts) >= 3 and parts[1:] == ["v1", "chat", "completions"] and parts[0] != "v1":
route = route or f"profile:{parts[0]}"
return str(route).strip() if route else None
def _route_matches(pattern: str, route: str) -> bool:
pattern = pattern.strip()
if pattern in {"*", "all"} or pattern == route:
return True
if pattern.endswith("*") and route.startswith(pattern[:-1]):
return True
return False
def _route_allowed(caller: str, route: str | None) -> bool:
allowed_routes = _consumer_meta(caller).get("allowed_routes") or []
if not allowed_routes:
return True
if not route:
return False
return any(_route_matches(pattern, route) for pattern in allowed_routes)
def _log(event: dict) -> None:
log.info(json.dumps(event, sort_keys=True, separators=(",", ":")))
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def _b64d(raw: str) -> bytes:
return base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))
def _make_dashboard_session(user: str, *, role: str = "admin", consumer: str | None = None, key_sha256: str | None = None) -> str:
if not DASHBOARD_SESSION_SECRET:
raise RuntimeError("DASHBOARD_SESSION_SECRET is not configured")
payload = {"u": user, "r": role, "e": int(time.time()) + DASHBOARD_COOKIE_MAX_AGE}
if consumer:
payload["c"] = consumer
if key_sha256:
payload["k"] = key_sha256
body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
sig = hmac.new(DASHBOARD_SESSION_SECRET.encode(), body.encode(), hashlib.sha256).hexdigest()
return f"{body}.{sig}"
def _dashboard_session_context(request: Request) -> dict[str, Any] | None:
if not DASHBOARD_SESSION_SECRET:
return None
raw = request.cookies.get(DASHBOARD_COOKIE_NAME, "")
if "." not in raw:
return None
body, sig = raw.rsplit(".", 1)
expected = hmac.new(DASHBOARD_SESSION_SECRET.encode(), body.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
return None
try:
payload = json.loads(_b64d(body))
except Exception:
return None
if int(payload.get("e", 0)) < int(time.time()):
return None
user = str(payload.get("u", "")).strip()
if not user:
return None
role = str(payload.get("r") or "admin").strip()
if role == "consumer":
consumer = str(payload.get("c", "")).strip()
key_sha256 = str(payload.get("k", "")).strip().lower()
if not consumer or not re.fullmatch(r"[a-f0-9]{64}", key_sha256):
return None
return {"role": "consumer", "user": user, "viewer": f"consumer:{consumer}", "consumer": consumer, "key_sha256": key_sha256}
return {"role": "admin", "user": user, "viewer": f"dashboard:{user}", "consumer": None, "key_sha256": None}
def _dashboard_session_user(request: Request) -> str | None:
ctx = _dashboard_session_context(request)
return str(ctx.get("viewer")) if ctx else None
def _dashboard_password_ok(password: str) -> bool:
if not DASHBOARD_PASSWORD_SHA256:
return False
got = hashlib.sha256(password.encode()).hexdigest()
return hmac.compare_digest(got, DASHBOARD_PASSWORD_SHA256)
def _require_dashboard_context(request: Request) -> dict[str, Any] | None:
if DASHBOARD_NO_AUTH:
return {"role": "admin", "user": "local-dev", "viewer": "dashboard:local-dev", "consumer": None, "key_sha256": None}
if DASHBOARD_TRUSTED_USER_HEADER:
trusted_user = (request.headers.get(DASHBOARD_TRUSTED_USER_HEADER) or "").strip()
trusted_secret = (request.headers.get("x-dashboard-trusted-secret") or "").strip()
if trusted_user and DASHBOARD_TRUSTED_USER_SECRET and hmac.compare_digest(trusted_secret, DASHBOARD_TRUSTED_USER_SECRET):
return {"role": "admin", "user": trusted_user, "viewer": f"dashboard:{trusted_user}", "consumer": None, "key_sha256": None}
return _dashboard_session_context(request)
def _require_dashboard_auth(request: Request) -> str | None:
ctx = _require_dashboard_context(request)
return str(ctx.get("viewer")) if ctx else None
def _require_admin_dashboard_auth(request: Request) -> tuple[dict[str, Any] | None, Response | None]:
ctx = _require_dashboard_context(request)
if not ctx:
return None, JSONResponse(status_code=401, content={"error": {"message": "unauthorized dashboard caller", "type": "auth_error", "code": "dashboard_auth"}})
if ctx.get("role") != "admin":
return None, JSONResponse(status_code=403, content={"error": {"message": "admin dashboard session required", "type": "auth_error", "code": "dashboard_admin_required"}})
return ctx, None
def _require_admin_dashboard_caller(request: Request) -> tuple[str | None, Response | None]:
# Privileged dashboard ops (reveal keys, manage codex, add/edit providers)
# gate on the ADMIN role — which both the SSO trusted-header path and the
# password login produce. There are no per-user tiers, so there is no extra
# per-name gate: access control is whoever SSO/the password admits. Returns
# the caller (viewer) string for audit, or an error Response.
ctx, error = _require_admin_dashboard_auth(request)
if error:
return None, error
return str(ctx.get("viewer")), None
def _mask_remote(remote: str | None) -> str | None:
if not remote:
return None
host = str(remote).strip()
if not host:
return None
try:
import ipaddress
ip = ipaddress.ip_address(host)
if ip.version == 4:
parts = host.split(".")
return ".".join(parts[:3] + ["0"]) + "/24"
return str(ipaddress.ip_network(str(ip) + "/64", strict=False))
except Exception:
return hashlib.sha256(host.encode()).hexdigest()[:12]
def _user_agent_hash(request: Request) -> str | None:
ua = (request.headers.get("user-agent") or "").strip()
return hashlib.sha256(ua.encode()).hexdigest()[:12] if ua else None
def _read_login_history() -> list[dict[str, Any]]:
# Dashboard login audit, from the store now (#5: dashboard-logins.jsonl retired).
return host_store.recent_logins(RECENT_LIMIT)
def _record_dashboard_login(*, request: Request, role: str, user: str, consumer: str | None = None, key_sha256: str | None = None) -> None:
key_prefix = key_sha256[:12] if key_sha256 and re.fullmatch(r"[a-f0-9]{64}", key_sha256) else None
row = {
"ts": int(time.time()),
"event": "dashboard_login",
"role": role,
"viewer": f"consumer:{consumer}" if role == "consumer" and consumer else f"dashboard:{user}",
"consumer": consumer,
"key_sha256_prefix": key_prefix,
"remote_masked": _mask_remote(request.client.host if request.client else None),
"user_agent_hash": _user_agent_hash(request),
}
row = {k: v for k, v in row.items() if v is not None}
host_store.insert_login(row)
def _provider_raw_credential(name: str) -> tuple[str | None, str | None]:
"""(kind, raw value) of one provider's credential — env API keys come
from the configured env var; codex OAuth comes from auth.json via
CodexAuth (refreshed, so the copied token is currently valid). Only the
admin-gated reveal endpoint may call this."""
try:
cfg = _load_policy_config()
except Exception:
return None, None
provider = (cfg.get("providers") or {}).get(name)
if not isinstance(provider, dict):
return None, None
auth_env = str(provider.get("auth_env") or "").strip()
if auth_env:
val = os.getenv(auth_env, "").strip()
return "env", (val or None)
auth = provider.get("auth") if isinstance(provider.get("auth"), dict) else {}
if auth.get("kind") == "oauth" or provider.get("api_kind") == "openai_codex":
try:
from codex_auth import CodexAuth
token = CodexAuth(os.getenv("CODEX_AUTH_PATH") or None).access_token()
return "oauth", (token or None)
except Exception:
return "oauth", None
return None, None
def _provider_credentials_snapshot(*, timeframe: str = "all", viewer_role: str = "admin") -> dict[str, Any]:
"""Admin-only provider credential/status/usage view. Never returns raw env values."""
if viewer_role != "admin":
return {"rows": [], "privacy": {"admin_only": True, "hidden_for_consumer_sessions": True}}
now = int(time.time())
since = None
if timeframe == "runtime":
since = int(_started_wall)
elif timeframe == "1h":
since = now - 3600
elif timeframe == "24h":
since = now - 86400
elif timeframe == "7d":
since = now - 7 * 86400
elif timeframe == "30d":
since = now - 30 * 86400
try:
cfg = _load_policy_config()
except Exception:
cfg = {"providers": {}}
providers = cfg.get("providers") or {}
prices = _price_table()
counters: dict[str, dict[str, Any]] = defaultdict(_counter)
last_event: dict[str, dict[str, Any]] = {}
cost_by_provider: dict[str, float] = defaultdict(float)
if timeframe != "runtime":
# SQL per-provider rollup over the window (was: load every retained row
# and fold in Python), TTL-cached; only the not-yet-landed runtime rows
# get folded on top — the old merge deduped landed rows anyway.
cached = _snapshot_cache_get(("provider_stats", timeframe))
if cached is None:
cached = host_store.usage_provider_stats(since_ts=since)
_snapshot_cache_put(("provider_stats", timeframe), cached)
for name, c in cached.items():
counters[name] = _counter_from_sql(c)
if int(c.get("priced") or 0):
cost_by_provider[name] = round(float(c.get("cost_usd") or 0.0), 6)
last_event[name] = {"ts": c.get("last_ts"), "status": c.get("last_status"),
"requested_model": c.get("last_route"),
"model_family": c.get("last_model_family")}
overlay = _unlanded_recent_requests(since)
else:
with _stats_lock:
overlay = [dict(r) for r in _stats["recent"] if r.get("event") == "request"]
if since is not None:
overlay = [r for r in overlay if int(r.get("ts") or 0) >= since]
with _stats_lock:
runtime_by_provider = {k: _counter_snapshot(v) for k, v in sorted(_stats["by_provider"].items())}
for row in overlay:
provider = str(row.get("provider") or "unknown")
cost, _meta = _cost_for_event(row, prices)
_add_counter(counters[provider], row, cost)
if cost is not None:
cost_by_provider[provider] = round(cost_by_provider[provider] + cost, 6)
ts = int(row.get("ts") or 0)
if provider not in last_event or ts >= int(last_event[provider].get("ts") or 0):
last_event[provider] = row
rows = []
for name, provider in sorted(providers.items()):
auth = provider.get("auth") if isinstance(provider.get("auth"), dict) else None
auth_env = str(provider.get("auth_env") or "").strip() or None
auth_kind = str(auth.get("kind")) if auth else ("env_api_key" if auth_env else "none")
key_present = False
key_fingerprint = None
status = "missing"
if auth_env:
val = os.getenv(auth_env, "")
key_present = bool(val.strip())
status = "configured" if key_present else "missing"
key_fingerprint = hashlib.sha256(val.encode()).hexdigest()[:12] if key_present else None
elif auth_kind == "none":
status = "no_auth_required"
elif auth_kind == "oauth":
status = "oauth_configured"
elif auth_kind:
status = "configured"
counter = _counter_snapshot(counters.get(name, _counter()))
if timeframe == "runtime" and not counter.get("requests"):
counter = runtime_by_provider.get(name, counter)
latest = last_event.get(name, {})
rows.append({
"provider": name,
"tier": provider.get("tier"),
"api_kind": provider.get("api_kind"),
"base_url": provider.get("base_url"),
"auth_kind": auth_kind,
"auth_env": auth_env,
"credential_status": status,
"key_present": key_present,
"key_fingerprint": key_fingerprint,
"usage": counter,
"estimated_cost_usd": round(cost_by_provider.get(name, 0.0), 6),
"last_status": latest.get("status"),
"last_route": latest.get("requested_model") or latest.get("route"),
"last_model_family": latest.get("model_family"),
"last_seen": latest.get("ts") or counter.get("last_seen"),
"notes": provider.get("notes"),
})
known = {r["provider"] for r in rows}
for name, counter in sorted(counters.items()):
if name in known or name == "unknown":
continue
latest = last_event.get(name, {})
rows.append({
"provider": name,
"tier": None,
"api_kind": None,
"base_url": None,
"auth_kind": "unknown",
"auth_env": None,
"credential_status": "seen_in_usage_only",
"key_present": None,
"key_fingerprint": None,
"usage": _counter_snapshot(counter),
"estimated_cost_usd": round(cost_by_provider.get(name, 0.0), 6),
"last_status": latest.get("status"),
"last_route": latest.get("requested_model") or latest.get("route"),
"last_model_family": latest.get("model_family"),
"last_seen": latest.get("ts"),
"notes": "Provider appeared in usage but is not in current config.",
})
rows.sort(key=lambda r: (0 if r.get("credential_status") in {"configured", "oauth_configured", "no_auth_required"} else 1, -int((r.get("usage") or {}).get("requests") or 0), str(r.get("provider"))))
return {
"schema_version": 1,
"kind": "router_provider_credentials",
"generated_at": now,
"timeframe": timeframe,
"rows": rows,
"privacy": {
"admin_only": True,
"raw_provider_keys_exposed": False,
"full_key_hashes_exposed": False,
"key_fingerprint": "sha256_prefix_12_when_env_key_present",
},
}
def _login_connections_snapshot(*, timeframe: str = "all", consumer: str | None = None, viewer_role: str = "admin") -> dict[str, Any]:
if viewer_role != "admin":
return {"rows": [], "recent_dashboard_logins": [], "privacy": {"admin_only": True, "hidden_for_consumer_sessions": True}}
now = int(time.time())
since = None
if timeframe == "runtime":
since = int(_started_wall)
elif timeframe == "1h":
since = now - 3600
elif timeframe == "24h":
since = now - 86400
elif timeframe == "7d":
since = now - 7 * 86400
elif timeframe == "30d":
since = now - 30 * 86400
dashboard_rows = list(_read_login_history())
with _stats_lock:
runtime_recent = list(_stats["recent"])
dedup = {}
for row in dashboard_rows:
key = (row.get("ts"), row.get("viewer"), row.get("key_sha256_prefix"), row.get("remote_masked"), row.get("user_agent_hash"))
dedup[key] = row
dashboard_rows = list(dedup.values())
if since is not None:
dashboard_rows = [r for r in dashboard_rows if int(r.get("ts") or 0) >= since]
if consumer:
dashboard_rows = [r for r in dashboard_rows if r.get("consumer") == consumer or r.get("viewer") == f"consumer:{consumer}"]
grouped: dict[tuple[str, str], dict[str, Any]] = {}
if timeframe != "runtime":
# SQL per-(caller, key-prefix) rollup over the window (was: load every
# retained row), TTL-cached; the not-yet-landed runtime rows fold on top.
cached = _snapshot_cache_get(("connections", timeframe, consumer))
if cached is None:
cached = host_store.usage_connections(since_ts=since, caller=consumer)
_snapshot_cache_put(("connections", timeframe, consumer), cached)
for c in cached:
prefix = str(c.get("prefix") or "unknown")
name = str(c.get("caller") or "unknown")
grouped[(name, prefix)] = {
"kind": "api_key", "identity": name, "consumer": name,
"key_sha256_prefix": prefix if prefix != "unknown" else None,
"first_seen": c.get("first_seen"), "last_seen": c.get("last_seen"),
"requests": int(c.get("requests") or 0), "errors": int(c.get("errors") or 0),
"last_status": c.get("last_status"), "last_route": c.get("last_route"),
"last_provider": c.get("last_provider")}
usage_rows = _unlanded_recent_requests(since)
else:
usage_rows = [dict(r) for r in runtime_recent if r.get("event") == "request"]
if since is not None:
usage_rows = [r for r in usage_rows if int(r.get("ts") or 0) >= since]
if consumer:
usage_rows = [r for r in usage_rows if r.get("caller") == consumer]
for row in usage_rows:
caller = str(row.get("caller") or "unknown")
prefix = str(row.get("key_sha256_prefix") or "").strip() or "unknown"
key = (caller, prefix)
item = grouped.setdefault(key, {"kind": "api_key", "identity": caller, "consumer": caller, "key_sha256_prefix": prefix if prefix != "unknown" else None, "first_seen": None, "last_seen": None, "requests": 0, "errors": 0, "last_status": None, "last_route": None, "last_provider": None})
ts = int(row.get("ts") or 0)
item["requests"] += 1
if int(row.get("status") or 0) >= 400:
item["errors"] += 1
item["first_seen"] = ts if not item["first_seen"] else min(int(item["first_seen"]), ts)
if not item["last_seen"] or ts >= int(item["last_seen"]):
item["last_seen"] = ts
item["last_status"] = row.get("status")
item["last_route"] = row.get("requested_model") or row.get("route")
item["last_provider"] = row.get("provider")
api_rows = list(grouped.values())
for item in api_rows:
item["active_now"] = bool(item.get("last_seen") and now - int(item["last_seen"]) <= 3600)
item["error_rate"] = round(item["errors"] / item["requests"], 4) if item["requests"] else 0.0
recent_logins = sorted(dashboard_rows, key=lambda r: int(r.get("ts") or 0), reverse=True)[:100]
rows = sorted(api_rows, key=lambda r: int(r.get("last_seen") or 0), reverse=True)
return {
"rows": rows,
"recent_dashboard_logins": recent_logins,
"generated_at": now,
"active_window_s": 3600,
"privacy": {
"admin_only": True,
"raw_api_keys_exposed": False,
"full_key_hashes_exposed": False,
"remote_addresses_masked": True,
"user_agents_hashed": True,
},
}
def _run_cost_backfill() -> int:
"""One-time (idempotent) stamping of cost_usd on unpriced `calls` rows so the
SQL aggregates can trust SUM(cost_usd) — before this, every dashboard read
re-priced those rows per row per load. Safe to run at every startup: rows the
price table can't price stay NULL (they sum as 0, same as before)."""
try:
n = host_store.backfill_call_costs(_price_table())
if n:
_log({"event": "cost_backfill", "rows_stamped": n})
return n
except Exception as exc: # noqa: BLE001 — best-effort telemetry, never blocks startup
logging.getLogger("auth_proxy").warning("cost backfill failed: %s", exc)
return 0
_backfill_task: "asyncio.Task | None" = None
@app.on_event("startup")
async def startup() -> None:
global _client, _probe_task, _backfill_task
# The ingress is the owner of the operational store (consumer keys, the ledger,
# operator-config writes); all operator state lives in Postgres now (the legacy
# JSON backfill was retired once prod confirmed the tables were populated).
_client = httpx.AsyncClient(timeout=httpx.Timeout(90.0, connect=10.0))
if SYNTHETIC_PROBES_ENABLED and ROUTE_HEALTH_ROUTES:
_probe_task = asyncio.create_task(_synthetic_probe_loop())
# Off the event loop: batched UPDATEs, potentially many rows on first deploy.
_backfill_task = asyncio.create_task(asyncio.to_thread(_run_cost_backfill))
@app.on_event("shutdown")
async def shutdown() -> None:
global _probe_task
if _probe_task:
_probe_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await _probe_task
_probe_task = None
if _client:
await _client.aclose()
@app.get("/healthz")
async def healthz() -> Response:
assert _client is not None
try:
r = await _client.get(f"{UPSTREAM}/healthz", timeout=5.0)
return JSONResponse(status_code=r.status_code, content=r.json())
except Exception as exc:
return JSONResponse(status_code=502, content={"ok": False, "error": str(exc)})
@app.get("/favicon.ico")
async def favicon() -> Response:
return Response(status_code=204)
@app.get("/dashboard")
@app.get("/dashboard/")
@app.get("/dashboard/provider-keys")
@app.get("/dashboard/provider-keys/")
async def dashboard() -> HTMLResponse:
return HTMLResponse(_dashboard_html())