-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1479 lines (1235 loc) · 64.9 KB
/
Copy pathserver.py
File metadata and controls
1479 lines (1235 loc) · 64.9 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
BrainKB MCP server.
Exposes the BrainKB query_service API as MCP tools so an assistant can, on the
user's behalf: authenticate with their credentials, ingest knowledge-graph data,
read/search the graphs, query W3C PROV-O provenance, and check the status of
their ingest jobs.
Transport: stdio (default). Run with: python server.py
Configuration (env, all optional):
BRAINKB_URL Base URL of the query_service (default http://localhost:8010)
BRAINKB_TOKEN A Personal Access Token (brainkb_pat_...) — the recommended
way to authenticate for LOCAL (stdio) use. Mint one with
brainkb_create_token() after logging in once, then paste it
here; no login/browser is needed afterward until it expires.
Ignored on the hosted remote unless MCP_ALLOW_SHARED_IDENTITY
is set, since there it would be a shared fallback identity.
Hardening knobs for the hosted (streamable-http) remote:
MCP_ALLOWED_BASE_URLS Comma-separated backends a caller may target, each
optionally paired with its usermanagement URL:
'https://api.brainkb.org=https://users.brainkb.org'.
BRAINKB_URL is always allowed. Anything else is
refused — the base URL is the destination of requests
that carry credentials, so an arbitrary value is both
SSRF and credential exfiltration.
MCP_TRUSTED_PROXIES Proxy IPs whose X-Forwarded-For may be believed. Empty
by default; an unvalidated forwarding header lets a
caller mint a new identity per request and evade every
rate limit.
MCP_INGEST_ROOT Directory brainkb_ingest_files may read from. File
ingest is disabled on the remote unless this is set,
because paths resolve on the SERVER's filesystem.
MCP_ALLOW_SHARED_IDENTITY Opt in to BRAINKB_TOKEN as an ambient identity
(single-user HTTP deployments only).
There is NO email/password auto-login: a baked-in credential could silently act
as a fallback identity and mis-attribute another user's actions, so it was
removed. Authenticate with BRAINKB_TOKEN, brainkb_login / brainkb_globus_login,
brainkb_use_token, or a per-caller 'Authorization: Bearer' header.
Credentials/token live only in this process's memory; the token is never logged
or returned to the model.
"""
from __future__ import annotations
import os
import sys
import threading
import time
import weakref
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import quote
import httpx
from mcp.server.fastmcp import FastMCP
# Registry identity (https://registry.modelcontextprotocol.io — "org.brainkb/brainkb").
SERVER_NAME = "org.brainkb/brainkb"
SERVER_VERSION = "0.1.0"
# Host/port only matter for the streamable-http transport (the hosted remote at
# https://mcp.brainkb.org/mcp); stdio ignores them.
mcp = FastMCP(
"brainkb",
host=os.getenv("MCP_HOST", "127.0.0.1"),
port=int(os.getenv("MCP_PORT", "8080")),
)
_DEFAULT_URL = os.getenv("BRAINKB_URL", "http://localhost:8010").rstrip("/")
# Which transport we were started with. Several protections below are only correct
# for the multi-user hosted remote (streamable-http), where callers are untrusted
# and anonymous; over stdio the caller IS the local user, so the same restrictions
# would only get in their way.
_TRANSPORT = os.getenv("MCP_TRANSPORT", "stdio").lower().replace("_", "-")
_IS_REMOTE = _TRANSPORT in ("http", "streamable-http")
_TIMEOUT = httpx.Timeout(120.0, connect=15.0)
# File ingest streams potentially very large uploads (TTL/JSON-LD up to ~5GB per
# user). A fixed read/write timeout would abort a legitimate large upload, so we
# disable read/write timeouts here and keep only a connect bound. Files stream
# from disk (httpx multipart), so this does not buffer the whole file in memory.
_UPLOAD_TIMEOUT = httpx.Timeout(None, connect=30.0)
# Per-session login store (fallback for local/stdio use only), keyed by the MCP
# session OBJECT itself. The hosted multi-user remote does NOT rely on this — each
# call carries the caller's own token via the Authorization header (stateless).
#
# Keyed weakly by the session object, never by id(): an address is recycled once
# the object is collected, so an id()-keyed store can hand a brand-new session the
# previous occupant's cached refresh token (wrong-user auth), and it also loses
# writes whenever the address shifts between two calls of the same login. The weak
# keys additionally let dead sessions' credentials be reclaimed automatically.
_SESSIONS: "weakref.WeakKeyDictionary[Any, Dict[str, Any]]" = weakref.WeakKeyDictionary()
# --------------------------------------------------------------------------- #
# multi-user auth resolution
# --------------------------------------------------------------------------- #
def _decode_sub(token: str) -> Optional[str]:
"""Read the 'sub' (email) claim from a JWT without verifying it — used only to
fill the user_id parameter. The server verifies the token for real."""
import base64
import json as _json
try:
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
return _json.loads(base64.urlsafe_b64decode(payload)).get("sub")
except Exception:
return None
_warned_unkeyable = False
def _session_key() -> Optional[Any]:
"""The current MCP session object, used as the _SESSIONS key.
Returns the object, not id(it): addresses are reused after garbage collection,
which both drops writes (login cached under one address, read under another)
and can hand a new session the previous occupant's cached token.
A session that cannot be weak-referenced or hashed cannot be cached under.
That returns None — but LOUDLY: it is reported on stderr, and every caller of
this function surfaces the condition to the user instead of silently behaving
as though no one had logged in.
"""
global _warned_unkeyable
try:
sess = mcp.get_context().session
except Exception:
# No MCP request context (direct/unit-test call) — expected, not an error.
return None
try:
weakref.ref(sess)
hash(sess)
except TypeError as e:
if not _warned_unkeyable:
_warned_unkeyable = True
print(
f"[brainkb-mcp] WARNING: MCP session objects of type "
f"{type(sess).__name__!r} cannot be used as a session-cache key "
f"({e}). Per-session login is DISABLED — authenticate with "
f"BRAINKB_TOKEN or an 'Authorization: Bearer' header instead.",
file=sys.stderr, flush=True,
)
return None
return sess
def _request_headers() -> Dict[str, str]:
"""Headers of the current inbound MCP request (empty for stdio / no request)."""
try:
req = getattr(mcp.get_context().request_context, "request", None)
if req is not None and getattr(req, "headers", None) is not None:
return {k.lower(): v for k, v in req.headers.items()}
except Exception:
pass
return {}
# --------------------------------------------------------------------------- #
# Rate limiting / abuse protection
# --------------------------------------------------------------------------- #
# In-process, per-caller fixed-window limiter. This is a first line of defence
# against abuse / brute-force / accidental floods on the hosted remote — it is
# NOT a substitute for an edge proxy / WAF / API gateway for real DDoS, and it is
# per-process (each worker keeps its own counters). Callers are keyed by client
# IP (X-Forwarded-For / X-Real-IP / socket peer) so header-authenticated users
# behind the same proxy are still separated by source IP. stdio (local) is exempt.
def _int_env(name: str, default: int) -> int:
try:
return int(os.getenv(name, str(default)))
except (TypeError, ValueError):
return default
_RL_ENABLED = os.getenv("MCP_RATELIMIT_ENABLED", "true").strip().lower() not in ("0", "false", "no")
_RL_WINDOW = max(1, _int_env("MCP_RATELIMIT_WINDOW_SEC", 60))
_RL_READ = _int_env("MCP_RATELIMIT_READ_PER_MIN", 120) # GET-style reads
_RL_WRITE = _int_env("MCP_RATELIMIT_WRITE_PER_MIN", 40) # mutations / ingest
_RL_ADMIN = _int_env("MCP_RATELIMIT_ADMIN_PER_MIN", 30) # usermanagement admin
_RL_AUTH = _int_env("MCP_RATELIMIT_AUTH_PER_MIN", 8) # register / login (brute-force)
# Payload guards (0 disables). Bound resource use per ingest call.
_MAX_INGEST_BYTES = _int_env("MCP_MAX_INGEST_BYTES", 10_000_000) # per raw-text ingest
_MAX_INGEST_FILES = _int_env("MCP_MAX_INGEST_FILES", 50) # per file-ingest call
_RL_MAX_KEYS = _int_env("MCP_RATELIMIT_MAX_KEYS", 20000)
# Reverse proxies whose X-Forwarded-For / X-Real-IP we believe. EMPTY BY DEFAULT:
# an unvalidated forwarding header is caller-controlled, so honouring it from any
# peer lets one client rotate a fresh identity per request (bypassing every limit,
# including the brute-force bucket) and lets it pin a VICTIM's IP to exhaust their
# quota. Set MCP_TRUSTED_PROXIES to your ALB/nginx source IPs when deployed behind
# one; until then the socket peer — which cannot be forged — is used.
_TRUSTED_PROXIES = {p.strip() for p in os.getenv("MCP_TRUSTED_PROXIES", "").split(",") if p.strip()}
_RL_LOCK = threading.Lock()
_RL_BUCKETS: Dict[Tuple[str, str], list] = {} # (client_id, bucket) -> [window, count]
_RL_LAST_SWEEP = [-1] # window index of the most recent eviction sweep
def _peer_ip() -> Optional[str]:
"""Socket peer address of the inbound request (None for stdio)."""
try:
req = getattr(mcp.get_context().request_context, "request", None)
client = getattr(req, "client", None)
if client and getattr(client, "host", None):
return client.host
except Exception:
pass
return None
def _client_id() -> str:
"""Identify the caller for rate-limiting. Prefer source IP so many users
behind one reverse proxy are still throttled per origin; fall back to the MCP
session; 'local' for stdio (exempt).
Forwarding headers are only trusted from a peer in MCP_TRUSTED_PROXIES, and we
take the RIGHTMOST entry — the hop that trusted proxy actually observed. The
leftmost entry is whatever the client chose to send and is trivially spoofed.
"""
peer = _peer_ip()
if peer and peer in _TRUSTED_PROXIES:
hdrs = _request_headers()
xff = hdrs.get("x-forwarded-for", "")
if xff:
return "ip:" + xff.split(",")[-1].strip()
xri = hdrs.get("x-real-ip", "")
if xri:
return "ip:" + xri.strip()
if peer:
return "ip:" + peer
sk = _session_key()
return f"sess:{sk}" if sk is not None else "local"
def _rate_ok(bucket: str, limit: int) -> bool:
"""True if this caller may proceed in `bucket`; False if the limit is hit."""
if not _RL_ENABLED or limit <= 0:
return True
cid = _client_id()
if cid == "local":
return True # stdio single-user — nothing to throttle
now = time.time()
win = int(now // _RL_WINDOW)
key = (cid, bucket)
with _RL_LOCK:
slot = _RL_BUCKETS.get(key)
if slot is None or slot[0] != win:
if len(_RL_BUCKETS) >= _RL_MAX_KEYS:
# Evict entries from previous windows — but at most once per
# window: the sweep is O(len(_RL_BUCKETS)) and runs under the
# global lock, so doing it on every insert while the map is full
# would itself be the denial of service.
if _RL_LAST_SWEEP[0] != win:
_RL_LAST_SWEEP[0] = win
for k, v in list(_RL_BUCKETS.items()):
if v[0] != win:
_RL_BUCKETS.pop(k, None)
if len(_RL_BUCKETS) >= _RL_MAX_KEYS:
# Still full: every entry belongs to the CURRENT window, i.e. a
# flood of distinct callers. Refuse the new key instead of
# growing without bound (fail closed — a genuinely new caller
# may be turned away for the rest of this window).
return False
_RL_BUCKETS[key] = [win, 1]
return True
if slot[1] >= limit:
return False
slot[1] += 1
return True
def _rl_error(bucket: str, limit: int) -> Dict[str, Any]:
return {
"error": True,
"status_code": 429,
"detail": (f"Rate limit exceeded for '{bucket}' ({limit} requests per "
f"{_RL_WINDOW}s). Slow down and retry shortly."),
}
class _NotAuthed(RuntimeError):
pass
# --------------------------------------------------------------------------- #
# Backend URL allowlist (SSRF / credential-exfiltration guard)
# --------------------------------------------------------------------------- #
# The backend base URL is caller-influenced: via the `X-BrainKB-Base-URL` header on
# the hosted remote, and via the `base_url` argument of the login tools. Both are
# used as the target of requests that CARRY CREDENTIALS — the caller's bearer
# token, the env Personal Access Token, a session's stored password. Accepting an
# arbitrary value therefore gives any caller two things at once:
#
# * SSRF — the server fetches an attacker-chosen host (link-local metadata at
# 169.254.169.254, internal load balancers, anything in the VPC) and returns
# the response body to them, and
# * credential theft — BRAINKB_TOKEN / a session PAT / stored credentials get
# POSTed to that host by the token-exchange helpers.
#
# So a base URL is only honoured if it is explicitly configured. Loopback is also
# allowed under stdio, where the caller is the local user and pointing at a dev
# backend on another port is routine.
#
# MCP_ALLOWED_BASE_URLS is a comma-separated list of query_service base URLs, each
# optionally paired with its usermanagement URL:
# MCP_ALLOWED_BASE_URLS=https://api.brainkb.org=https://users.brainkb.org,http://localhost:8011
def _norm_base(u: Optional[str]) -> str:
return (u or "").strip().rstrip("/")
def _parse_allowed() -> Dict[str, Optional[str]]:
out: Dict[str, Optional[str]] = {_norm_base(_DEFAULT_URL): None} # paired with _UM_URL
for entry in os.getenv("MCP_ALLOWED_BASE_URLS", "").split(","):
entry = entry.strip()
if not entry:
continue
q, _, u = entry.partition("=")
q = _norm_base(q)
if q:
out[q] = _norm_base(u) or None
return out
_ALLOWED_BASES: Dict[str, Optional[str]] = _parse_allowed()
def _is_loopback(url: str) -> bool:
try:
return httpx.URL(url).host in ("localhost", "127.0.0.1", "::1")
except Exception:
return False
def _allowed_base(candidate: Optional[str] = "") -> str:
"""Validate a caller-supplied backend base URL against the allowlist.
Returns the default backend when nothing was supplied; raises _NotAuthed for an
unknown host rather than silently falling back, so a misconfiguration is
visible instead of quietly routing to the wrong backend.
"""
base = _norm_base(candidate)
if not base:
return _norm_base(_DEFAULT_URL)
if base in _ALLOWED_BASES:
return base
if not _IS_REMOTE and _is_loopback(base):
return base
raise _NotAuthed(
f"Backend URL {base!r} is not allowed. Credentials are only ever sent to "
"configured backends; add it to the MCP_ALLOWED_BASE_URLS environment "
"variable (as '<query-url>' or '<query-url>=<usermanagement-url>') if it "
"is genuinely yours."
)
# --------------------------------------------------------------------------- #
# Phase 2 SSO: single login -> per-service token exchange
# --------------------------------------------------------------------------- #
# usermanagement is the single issuer. A login mints a REFRESH token; we exchange
# it for a short-lived per-service ACCESS token (aud=<service>) whenever a tool
# calls that service. A token minted for one service can't be replayed against
# another (containment). Legacy per-service /api/token still works as a fallback,
# so this keeps working against a backend that doesn't yet expose SSO.
_AUD_QUERY = "query_service"
_AUD_UM = "usermanagement"
# Escape hatch for a deliberately single-user HTTP deployment: allow the env
# BRAINKB_TOKEN to serve as the identity for callers who send no credential of
# their own. Off by default — on a shared remote it makes every anonymous caller
# act as the token's owner.
_ALLOW_SHARED_IDENTITY = os.getenv("MCP_ALLOW_SHARED_IDENTITY", "").strip().lower() in ("1", "true", "yes")
# A cached login is not forever: the session expires with its refresh token (or,
# as a hard cap even if credentials are cached, after MCP_SESSION_TTL_MIN). When it
# lapses the session is forgotten and the user must log in again.
_SESSION_TTL_MIN = _int_env("MCP_SESSION_TTL_MIN", 720) # fallback when no exp claim
def _claims(token: str) -> Dict[str, Any]:
"""Unverified claims of a JWT (for routing only; the server verifies for real)."""
import base64
import json as _json
try:
p = token.split(".")[1]
p += "=" * (-len(p) % 4)
return _json.loads(base64.urlsafe_b64decode(p))
except Exception:
return {}
def _session_expiry(token: str) -> float:
"""Absolute expiry (epoch seconds) for a cached session: the token's `exp`
claim, capped by MCP_SESSION_TTL_MIN, falling back to now + TTL if no exp."""
cap = time.time() + _SESSION_TTL_MIN * 60
exp = _claims(token).get("exp")
if isinstance(exp, (int, float)) and exp > 0:
return min(float(exp), cap)
return cap
def _session_expired(sd: dict) -> bool:
exp = sd.get("expires_at")
return bool(exp) and time.time() >= float(exp)
def _um_base(base: str) -> str:
"""usermanagement base URL for SSO login/exchange, given the query_service base.
`base` must already have passed _allowed_base(). The port rewrite below is only
a convenience for the dev layout (:8010 -> :8004); it cannot be relied on for a
real deployment (e.g. https://api.brainkb.org has no :8010, and the old code
silently sent usermanagement traffic — PAT exchanges, admin calls — to the
query_service host instead). Configure the pairing explicitly there.
"""
base = _norm_base(base)
if base == _norm_base(_DEFAULT_URL):
return _UM_URL
paired = _ALLOWED_BASES.get(base)
if paired:
return paired
if ":8010" in base:
return base.replace(":8010", ":8004")
raise _NotAuthed(
f"No usermanagement URL is configured for backend {base!r}. Pair them in "
"MCP_ALLOWED_BASE_URLS as '<query-url>=<usermanagement-url>'."
)
def _sso_login(um: str, email: str, password: str) -> Optional[str]:
"""POST /api/auth/login -> refresh token, or None (incl. a backend without SSO)."""
try:
r = httpx.post(f"{um}/api/auth/login", json={"email": email, "password": password}, timeout=30)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json().get("refresh_token")
except Exception:
return None
def _exchange(um: str, refresh: str, audience: str) -> Optional[tuple]:
"""POST /api/auth/exchange -> (access_token, ttl_seconds), or None."""
try:
r = httpx.post(f"{um}/api/auth/exchange",
headers={"Authorization": f"Bearer {refresh}"},
json={"audience": audience}, timeout=30)
r.raise_for_status()
d = r.json()
return d["access_token"], int(d.get("expires_in", 900))
except Exception:
return None
_PAT_PREFIX = "brainkb_pat_"
def _is_pat(token: str) -> bool:
"""True if the string is a BrainKB Personal Access Token (opaque, not a JWT)."""
return bool(token) and token.strip().startswith(_PAT_PREFIX)
def _pat_exchange(um: str, pat: str, audience: str) -> Optional[tuple]:
"""POST /api/auth/pat/exchange -> (access_token, ttl_seconds), or None. A PAT is
an opaque, revocable, long-lived credential; it is exchanged for a short-lived
per-service access token exactly like a refresh token, but needs no browser."""
try:
r = httpx.post(f"{um}/api/auth/pat/exchange",
json={"token": pat, "audience": audience}, timeout=30)
if r.status_code == 404:
return None
r.raise_for_status()
d = r.json()
return d["access_token"], int(d.get("expires_in", 900))
except Exception:
return None
def _legacy_login(base: str, email: str, password: str) -> Optional[str]:
"""Legacy per-service password login -> access token, or None. Prefers
/api/login; falls back to the deprecated /api/token for older backends."""
for path in ("/api/login", "/api/token"):
try:
r = httpx.post(f"{base}{path}", json={"email": email, "password": password}, timeout=30)
if r.status_code == 404:
continue
r.raise_for_status()
return r.json().get("access_token")
except Exception:
continue
return None
def _cached_access(sd: dict, aud: str) -> Optional[str]:
acc = (sd.get("access") or {}).get(aud)
if acc and acc[1] - time.time() > 30:
return acc[0]
return None
def _store_access(sd: dict, aud: str, token: str, ttl: int) -> None:
sd.setdefault("access", {})[aud] = (token, time.time() + ttl)
def _token_for(audience: str) -> Dict[str, str]:
"""Resolve an auth context {url, token, email} whose token is valid for
`audience` (query_service | usermanagement). Multi-user safe.
Precedence:
1. Caller's `Authorization: Bearer <token>` header (a PAT or REFRESH token is
exchanged for the requested audience — unlocks every service from one
header; any other token is used as-is). `X-BrainKB-Base-URL` optionally
overrides the backend URL.
2. Env `BRAINKB_TOKEN` Personal Access Token.
3. Per-session login set by `brainkb_login` / `brainkb_finish_login` /
`brainkb_use_token` (with re-login from that session's own stored
credentials if its refresh token has expired).
There is deliberately NO env email/password auto-login: a baked-in credential
could silently shadow a real login and mis-attribute actions to the wrong user.
"""
hdrs = _request_headers()
base = _allowed_base(hdrs.get("x-brainkb-base-url"))
um = _um_base(base)
key = _session_key()
# 1) header pass-through
authz = hdrs.get("authorization", "")
if authz[:7].lower() == "bearer " and authz[7:].strip():
raw = authz[7:].strip()
# A Personal Access Token is opaque (not a JWT); exchange it for the
# requested service audience — one PAT unlocks every service.
if _is_pat(raw):
ex = _pat_exchange(um, raw, audience)
if ex:
return {"url": base, "token": ex[0], "email": _decode_sub(ex[0]) or ""}
raise _NotAuthed(f"Could not exchange the provided access token for '{audience}' "
"(it may be expired or revoked).")
cl = _claims(raw)
if cl.get("typ") == "refresh" or cl.get("aud") == "brainkb-auth":
ex = _exchange(um, raw, audience)
if ex:
return {"url": base, "token": ex[0], "email": cl.get("sub") or ""}
raise _NotAuthed(f"Could not exchange the provided refresh token for '{audience}'.")
return {"url": base, "token": raw, "email": cl.get("sub") or _decode_sub(raw) or ""}
# 2) per-session (cached access -> refresh -> legacy)
if key is not None and key in _SESSIONS and _session_expired(_SESSIONS[key]):
# Session lapsed — forget it so cached creds aren't silently reused; the
# caller must log in again.
_SESSIONS.pop(key, None)
if key is not None and key in _SESSIONS:
sd = _SESSIONS[key]
cached = _cached_access(sd, audience)
if cached:
return {"url": sd.get("url", base), "token": cached, "email": sd.get("email", "")}
if sd.get("pat"):
ex = _pat_exchange(um, sd["pat"], audience)
if ex:
_store_access(sd, audience, ex[0], ex[1])
return {"url": sd.get("url", base), "token": ex[0],
"email": sd.get("email") or _decode_sub(ex[0]) or ""}
if sd.get("refresh"):
ex = _exchange(um, sd["refresh"], audience)
if ex:
_store_access(sd, audience, ex[0], ex[1])
return {"url": sd.get("url", base), "token": ex[0], "email": sd.get("email", "")}
if sd.get("legacy_token") and audience == _AUD_QUERY:
return {"url": sd.get("url", base), "token": sd["legacy_token"], "email": sd.get("email", "")}
# 3) env Personal Access Token (browser-free: mint once, paste into config).
# IGNORED on the hosted remote unless explicitly opted into: there it is an
# ambient fallback identity with exactly the identity-shadowing problem that
# got env email/password removed — an anonymous caller who sends no
# Authorization header would silently execute as the PAT's owner, and the
# result would even be cached into their session below.
pat_env = os.getenv("BRAINKB_TOKEN", "").strip()
if _is_pat(pat_env) and (not _IS_REMOTE or _ALLOW_SHARED_IDENTITY):
ex = _pat_exchange(um, pat_env, audience)
if ex:
email = _decode_sub(ex[0]) or ""
if key is not None:
sd = _SESSIONS.setdefault(key, {})
sd.update({"pat": pat_env, "email": email or sd.get("email", ""),
"url": base, "access": sd.get("access", {})})
_store_access(sd, audience, ex[0], ex[1])
return {"url": base, "token": ex[0], "email": email}
# 4) session credential re-login — ONLY continues an explicit password
# brainkb_login within THIS session (e.g. after its refresh token expired).
# There is NO env auto-login: a baked-in BRAINKB_EMAIL/BRAINKB_PASSWORD must
# never silently act as a fallback identity (that caused calls to run as the
# wrong user). Use BRAINKB_TOKEN, brainkb_globus_login, brainkb_use_token,
# or an Authorization header instead.
em = pw = None
if key is not None and key in _SESSIONS:
sd = _SESSIONS[key]
em, pw = sd.get("email"), sd.get("password")
if em and pw:
refresh = _sso_login(um, em, pw)
if refresh:
ex = _exchange(um, refresh, audience)
if ex:
if key is not None:
sd = _SESSIONS.setdefault(key, {})
sd.update({"refresh": refresh, "email": em, "password": pw, "url": base,
"expires_at": _session_expiry(refresh)})
_store_access(sd, audience, ex[0], ex[1])
return {"url": base, "token": ex[0], "email": em}
# legacy fallback (per-service /api/token)
legacy = _legacy_login(base if audience == _AUD_QUERY else um, em, pw)
if legacy:
if key is not None and audience == _AUD_QUERY:
_SESSIONS.setdefault(key, {}).update(
{"legacy_token": legacy, "email": em, "password": pw, "url": base})
return {"url": base, "token": legacy, "email": em}
raise _NotAuthed(
"Not authenticated (or your session has expired — sessions don't last "
"forever). Easiest: set BRAINKB_TOKEN to a Personal Access Token "
"(brainkb_pat_...) in your config, or pass one with brainkb_use_token(pat) "
"— no browser needed. To sign in as your account, use "
"brainkb_globus_login() (Globus/ORCID/GitHub) — it returns a URL to open, "
"then brainkb_finish_login(code). Do NOT expect a password prompt: password "
"login (brainkb_login) is legacy and only for explicit password accounts. "
"On the hosted remote, send 'Authorization: Bearer <token>' (a PAT or "
"refresh token unlocks all services)."
)
def _resolve() -> Dict[str, str]:
"""Auth context for query_service calls."""
return _token_for(_AUD_QUERY)
def _me() -> str:
return _resolve()["email"]
def _seg(value: str) -> str:
"""Escape a caller-supplied value for use as exactly ONE URL path segment.
urllib's quote() defaults to safe="/", which leaves slashes intact — so a slug
of '../../api/admin/users' passed through quote() rewrites the request path
(httpx collapses the dot segments before sending). safe="" percent-encodes the
slashes so the value stays a single segment. Bare '.'/'..' still survive, since
dots are unreserved and never encoded; _path_ok below rejects those.
"""
return quote((value or "").strip(), safe="")
def _path_ok(path: str) -> bool:
"""False if a request path contains an empty or dot segment — i.e. something
that would traverse to a different endpoint than the tool intended."""
return not any(p in ("", ".", "..") for p in path.split("/")[1:])
_BAD_PATH = {"error": True, "status_code": 400,
"detail": "Invalid or empty identifier in the request path."}
def _result(resp: httpx.Response) -> Any:
"""Return parsed JSON on success, else a compact error dict (never raises)."""
ok = resp.status_code < 400
body: Any
try:
body = resp.json()
except Exception:
body = (resp.text or "")[:2000]
if ok:
return body
return {"error": True, "status_code": resp.status_code, "detail": body}
def _get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
if not _path_ok(path):
return dict(_BAD_PATH)
if not _rate_ok("read", _RL_READ):
return _rl_error("read", _RL_READ)
try:
ctx = _resolve()
with httpx.Client(timeout=_TIMEOUT) as c:
resp = c.get(f"{ctx['url']}{path}", params=params or {},
headers={"Authorization": f"Bearer {ctx['token']}"})
return _result(resp)
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
except Exception as e:
return {"error": True, "detail": str(e)}
def _post(path: str, params: Optional[Dict[str, Any]] = None,
json: Any = None, content: Optional[bytes] = None,
ctype: Optional[str] = None, files: Any = None,
timeout: Optional[httpx.Timeout] = None) -> Any:
if not _path_ok(path):
return dict(_BAD_PATH)
if not _rate_ok("write", _RL_WRITE):
return _rl_error("write", _RL_WRITE)
try:
ctx = _resolve()
headers = {"Authorization": f"Bearer {ctx['token']}"}
if ctype:
headers["Content-Type"] = ctype
with httpx.Client(timeout=timeout or _TIMEOUT) as c:
resp = c.post(f"{ctx['url']}{path}", params=params or {}, headers=headers,
json=json, content=content, files=files)
return _result(resp)
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
except Exception as e:
return {"error": True, "detail": str(e)}
def _patch(path: str, json: Any = None) -> Any:
if not _path_ok(path):
return dict(_BAD_PATH)
if not _rate_ok("write", _RL_WRITE):
return _rl_error("write", _RL_WRITE)
try:
ctx = _resolve()
with httpx.Client(timeout=_TIMEOUT) as c:
resp = c.patch(f"{ctx['url']}{path}",
headers={"Authorization": f"Bearer {ctx['token']}"}, json=json)
return _result(resp)
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
except Exception as e:
return {"error": True, "detail": str(e)}
def _delete(path: str) -> Any:
if not _path_ok(path):
return dict(_BAD_PATH)
if not _rate_ok("write", _RL_WRITE):
return _rl_error("write", _RL_WRITE)
try:
ctx = _resolve()
with httpx.Client(timeout=_TIMEOUT) as c:
resp = c.delete(f"{ctx['url']}{path}", headers={"Authorization": f"Bearer {ctx['token']}"})
return _result(resp)
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
except Exception as e:
return {"error": True, "detail": str(e)}
# --------------------------------------------------------------------------- #
# usermanagement service client (admin: users, roles, activation)
# --------------------------------------------------------------------------- #
# The usermanagement service (:8004) is a SEPARATE service. Under SSO we reach it
# with an access token minted for aud=usermanagement (via the single login +
# exchange in _token_for); no separate login is needed. Legacy /api/token remains
# the fallback inside _token_for. Admin endpoints require an Admin/SuperAdmin role.
_UM_URL = (os.getenv("USERMANAGEMENT_URL") or _DEFAULT_URL.replace(":8010", ":8004")).rstrip("/")
def _um(method: str, path: str, json: Any = None, params: Any = None, _retry: bool = True) -> Any:
if not _path_ok(path):
return dict(_BAD_PATH)
if _retry and not _rate_ok("admin", _RL_ADMIN):
return _rl_error("admin", _RL_ADMIN)
try:
um = _um_base(_allowed_base(_request_headers().get("x-brainkb-base-url")))
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
try:
ctx = _token_for(_AUD_UM)
with httpx.Client(timeout=_TIMEOUT) as c:
resp = c.request(method, f"{um}{path}",
headers={"Authorization": f"Bearer {ctx['token']}"}, json=json, params=params)
if resp.status_code == 401 and _retry:
# The access token may have expired — drop the cached usermanagement
# token so _token_for re-exchanges, and retry once.
key = _session_key()
if key is not None and key in _SESSIONS:
(_SESSIONS[key].get("access") or {}).pop(_AUD_UM, None)
return _um(method, path, json=json, params=params, _retry=False)
return _result(resp)
except _NotAuthed as e:
return {"error": True, "detail": str(e)}
except Exception as e:
return {"error": True, "detail": str(e)}
def _um_profile_id(email: str) -> Optional[int]:
users = _um("GET", "/api/admin/users", params={"q": email, "limit": 200})
if isinstance(users, list):
for u in users:
if (u.get("email") or "").lower() == email.lower():
return u.get("profile_id")
return None
# --------------------------------------------------------------------------- #
# auth / session
# --------------------------------------------------------------------------- #
# NOTE: there is no self-registration tool. Users are onboarded by signing in with
# Globus/ORCID/GitHub (brainkb_globus_login), which auto-creates and links their
# profile on first login. There is no separate "register" step.
@mcp.tool()
def brainkb_login(email: str, password: str, base_url: str = "") -> str:
"""Authenticate to BrainKB with the user's credentials and cache the JWT for
THIS session only (isolated per caller). The password/token are never echoed.
Uses single sign-on: one login mints a refresh token, cached for THIS session,
which is exchanged on demand for per-service access tokens (query_service,
usermanagement, …). Falls back to a legacy per-service token if the backend
has no SSO. On the hosted multi-user remote you can skip this and instead have
your client send an 'Authorization: Bearer <token>' header (a refresh token
unlocks all services)."""
if not _rate_ok("auth", _RL_AUTH):
return _rl_error("auth", _RL_AUTH)["detail"]
key = _session_key()
try:
# base_url decides where this password is sent — allowlist it.
base = _allowed_base(base_url)
um = _um_base(base)
except _NotAuthed as e:
return str(e)
try:
# SSO first: single login -> refresh token (exchanged per service later).
refresh = _sso_login(um, email, password)
if refresh:
if key is None:
return ("Logged in, but this session could not be identified to cache the "
"token; send an Authorization header instead.")
# Credentials kept in memory for THIS session only, to re-login if the
# refresh token expires. Never echoed.
_SESSIONS[key] = {"refresh": refresh, "url": base, "email": email,
"password": password, "access": {},
"expires_at": _session_expiry(refresh)}
return f"Logged in as {email} at {base} (SSO; this session, expires when the token does)."
# Legacy fallback: per-service query_service token.
legacy = _legacy_login(base, email, password)
if not legacy:
return "Login failed. Check email/password and base_url."
if key is None:
return ("Logged in (legacy), but this session could not be identified to cache "
"the token; send an Authorization header instead.")
_SESSIONS[key] = {"legacy_token": legacy, "url": base, "email": email,
"password": password, "access": {},
"expires_at": _session_expiry(legacy)}
return f"Logged in as {email} at {base} (this session)."
except Exception as e:
return f"Login error: {e}"
@mcp.tool()
def brainkb_globus_login(provider: str = "globus", base_url: str = "") -> str:
"""Start an OAuth login (Globus / ORCID / GitHub) for THIS session — use this
instead of brainkb_login when the user signs in with Globus rather than a
password. Returns a URL to open in a browser; after signing in, the page shows
a short one-time code — pass it to brainkb_finish_login(code) to complete.
(The browser step is unavoidable: only the user can consent at the provider.)"""
if not _rate_ok("auth", _RL_AUTH):
return _rl_error("auth", _RL_AUTH)["detail"]
try:
um = _um_base(_allowed_base(base_url))
except _NotAuthed as e:
return str(e)
try:
r = httpx.post(f"{um}/api/auth/cli/start", json={"provider": provider}, timeout=30)
r.raise_for_status()
url = r.json()["authorize_url"]
return (f"Open this URL in a browser and sign in with {provider}:\n{url}\n\n"
"After signing in, the page shows a short code — call "
"brainkb_finish_login(\"<code>\") with it to finish.")
except httpx.HTTPStatusError as e:
return (f"Could not start {provider} login (HTTP {e.response.status_code}). "
f"Is {provider} OAuth configured on the server?")
except Exception as e:
return f"Login start error: {e}"
@mcp.tool()
def brainkb_finish_login(code: str, base_url: str = "") -> str:
"""Complete an OAuth login started with brainkb_globus_login by exchanging the
one-time code shown in the browser for a session token. The code is single-use
and never echoed back."""
if not _rate_ok("auth", _RL_AUTH):
return _rl_error("auth", _RL_AUTH)["detail"]
key = _session_key()
try:
# base_url decides where this single-use OAuth code is redeemed.
base = _allowed_base(base_url)
um = _um_base(base)
except _NotAuthed as e:
return str(e)
try:
r = httpx.post(f"{um}/api/auth/cli/exchange", json={"code": code}, timeout=30)
if r.status_code >= 400:
return ("That code is invalid, expired, or already used. Start again with "
"brainkb_globus_login.")
refresh = r.json()["refresh_token"]
if key is None:
return ("Login completed, but this session could not be identified to cache "
"the token; send an Authorization header (refresh token) instead.")
email = _decode_sub(refresh) or ""
# OAuth session: no password stored (can't password re-login); the refresh
# token drives per-service SSO exchange like a normal login.
_SESSIONS[key] = {"refresh": refresh, "url": base, "email": email, "access": {},
"expires_at": _session_expiry(refresh)}
return f"Logged in as {email or 'your account'} at {base} (via OAuth SSO; this session, expires when the token does)."
except Exception as e:
return f"Finish login error: {e}"
@mcp.tool()
def brainkb_logout() -> str:
"""Forget the cached token for this session."""
key = _session_key()
if key is not None:
_SESSIONS.pop(key, None)
return "Logged out (this session)."
@mcp.tool()
def brainkb_whoami() -> Dict[str, Any]:
"""Report the current caller's auth state (base URL, email, authenticated, and
when the cached session expires)."""
# Rate-limited like a read: resolving auth can trigger a token exchange against
# the backend, so an unmetered whoami is a request amplifier.
if not _rate_ok("read", _RL_READ):
return _rl_error("read", _RL_READ)
try:
ctx = _resolve()
out = {"base_url": ctx["url"], "email": ctx["email"], "authenticated": True}
key = _session_key()
if key is not None and key in _SESSIONS:
exp = _SESSIONS[key].get("expires_at")
if exp:
out["session_expires_in_min"] = max(0, round((float(exp) - time.time()) / 60))
return out
except _NotAuthed as e:
return {"base_url": _DEFAULT_URL, "email": None, "authenticated": False,
"hint": "Session may have expired — log in again (brainkb_login / brainkb_globus_login)."}
# --------------------------------------------------------------------------- #
# personal access tokens (browser-free, long-lived, revocable)
# --------------------------------------------------------------------------- #
# A PAT lets the user authenticate WITHOUT a browser after a one-time login: mint
# it once (while logged in), paste it into the config as BRAINKB_TOKEN, and every
# call thereafter authenticates with it until it expires or is revoked. The PAT is
# opaque (not a key/JWT); the user handles a single string, never a key.
@mcp.tool()
def brainkb_create_token(name: str = "", days: int = 90) -> Any:
"""Generate a Personal Access Token (PAT) for browser-free auth. Requires you
to be logged in already (brainkb_login or brainkb_globus_login). The token is
shown ONCE and never again — copy it and set it as BRAINKB_TOKEN in your
MCP/skill config; then no login or browser is needed until it expires.
`name`: a label so you can tell tokens apart (e.g. 'laptop'). `days`: lifetime
(default 90, server-capped). Treat the returned token like a password."""
if not _rate_ok("auth", _RL_AUTH):
return _rl_error("auth", _RL_AUTH)
return _um("POST", "/api/auth/tokens", json={"name": name, "days": days})
@mcp.tool()
def brainkb_list_tokens() -> Any:
"""List your Personal Access Tokens (metadata only — the secret is never
shown): id, name, prefix, created/last-used/expiry, and whether each is
active/revoked/expired. Use the id with brainkb_revoke_token."""
return _um("GET", "/api/auth/tokens")
@mcp.tool()
def brainkb_revoke_token(token_id: int) -> Any:
"""Revoke one of your Personal Access Tokens by id (see brainkb_list_tokens).
Takes effect immediately — the next call using that token fails."""
return _um("DELETE", f"/api/auth/tokens/{int(token_id)}")
@mcp.tool()
def brainkb_use_token(token: str, base_url: str = "") -> str:
"""Use a Personal Access Token (brainkb_pat_...) for THIS session — an
alternative to setting BRAINKB_TOKEN in the config. Validates the token, then
caches it so subsequent calls authenticate with it. The token is never echoed."""
if not _rate_ok("auth", _RL_AUTH):
return _rl_error("auth", _RL_AUTH)["detail"]
key = _session_key()