graphlore 0.7.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.
graphlore/oauth.py ADDED
@@ -0,0 +1,169 @@
1
+ """OAuth for the HTTP transport: graphlore as a resource server.
2
+
3
+ Remote MCP clients (claude.ai and ChatGPT connectors, Claude Code over HTTP)
4
+ sign in with OAuth 2.1 as the MCP specification describes: the server
5
+ publishes RFC 9728 Protected Resource Metadata naming its authorization
6
+ server, answers a request without a valid token with 401 and a
7
+ ``WWW-Authenticate: Bearer resource_metadata=…`` header, and accepts only
8
+ tokens issued for it. graphlore issues no token: any OAuth / OpenID provider
9
+ does (Auth0, Keycloak, Entra ID, Okta, Google…), and the clients register with
10
+ it themselves.
11
+
12
+ ``GRAPHLORE_AUTH_ISSUER`` (the provider's issuer URL) and
13
+ ``GRAPHLORE_AUTH_RESOURCE_URL`` (this server's public URL, the token audience)
14
+ turn it on; ``GRAPHLORE_AUTH_SCOPES`` (comma-separated) are required of every
15
+ token (403 ``insufficient_scope`` otherwise). `JwtVerifier` checks a JWT's
16
+ signature against the provider's keys (found by RFC 8414 / OpenID discovery),
17
+ its issuer, audience and expiry; the SDK's middleware does the rest (401/403,
18
+ the metadata route). The discovery and key fetches reach the network, so
19
+ ``GRAPHLORE_OFFLINE`` refuses this mode.
20
+
21
+ Needs the ``remote`` extra (pyjwt[crypto]), imported only when configured.
22
+ Imports only ``config``.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import urllib.request
28
+ from typing import Any
29
+ from urllib.parse import urlsplit, urlunsplit
30
+
31
+ from . import config
32
+
33
+ # Signature algorithms a provider's JWT may use: asymmetric only (a shared
34
+ # secret, or "none", would let a token be made without the provider's key).
35
+ ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512",
36
+ "ES256", "ES384", "ES512", "EdDSA"]
37
+ _TIMEOUT = 10
38
+
39
+
40
+ class AuthConfigError(Exception):
41
+ """OAuth is asked for but cannot run (offline, the extra missing, a URL wrong)."""
42
+
43
+
44
+ def settings() -> dict[str, Any] | None:
45
+ """``{issuer, resource, scopes}`` from the environment, or None when OAuth
46
+ is not asked for; an error when it is asked for half."""
47
+ issuer = (config.env("AUTH_ISSUER") or "").strip().rstrip("/")
48
+ resource = (config.env("AUTH_RESOURCE_URL") or "").strip()
49
+ if not issuer and not resource:
50
+ return None
51
+ if not issuer or not resource:
52
+ raise AuthConfigError(
53
+ "OAuth needs both GRAPHLORE_AUTH_ISSUER (the provider's issuer URL) and "
54
+ "GRAPHLORE_AUTH_RESOURCE_URL (this server's public URL).")
55
+ for name, url in (("GRAPHLORE_AUTH_ISSUER", issuer),
56
+ ("GRAPHLORE_AUTH_RESOURCE_URL", resource)):
57
+ parts = urlsplit(url)
58
+ if parts.scheme != "https" and parts.hostname not in ("localhost", "127.0.0.1"):
59
+ raise AuthConfigError(f"{name} must be an https URL (or localhost): {url}")
60
+ scopes = [s.strip() for s in (config.env("AUTH_SCOPES") or "").split(",") if s.strip()]
61
+ return {"issuer": issuer, "resource": resource, "scopes": scopes}
62
+
63
+
64
+ def discovery_urls(issuer: str) -> list[str]:
65
+ """Where an issuer's metadata is: RFC 8414 (the well-known path inserted
66
+ before the issuer's own path), then OpenID Connect discovery."""
67
+ parts = urlsplit(issuer)
68
+ path = parts.path.rstrip("/")
69
+ rfc8414 = urlunsplit((parts.scheme, parts.netloc,
70
+ "/.well-known/oauth-authorization-server" + path, "", ""))
71
+ oidc = issuer.rstrip("/") + "/.well-known/openid-configuration"
72
+ return [rfc8414, oidc]
73
+
74
+
75
+ def _get_json(url: str) -> dict[str, Any]:
76
+ with urllib.request.urlopen(url, timeout=_TIMEOUT) as resp: # noqa: S310 - https URL checked
77
+ data = json.loads(resp.read().decode("utf-8"))
78
+ if not isinstance(data, dict):
79
+ raise ValueError(f"{url} did not return a JSON object")
80
+ return data
81
+
82
+
83
+ def jwks_uri(issuer: str) -> str:
84
+ """The provider's key set URL, from its metadata (whose issuer must match)."""
85
+ errors = []
86
+ for url in discovery_urls(issuer):
87
+ try:
88
+ meta = _get_json(url)
89
+ except Exception as e: # noqa: BLE001 - try the next form, report all
90
+ errors.append(f"{url}: {e}")
91
+ continue
92
+ if str(meta.get("issuer", "")).rstrip("/") != issuer:
93
+ errors.append(f"{url}: its issuer is {meta.get('issuer')!r}, not {issuer!r}")
94
+ continue
95
+ if meta.get("jwks_uri"):
96
+ return str(meta["jwks_uri"])
97
+ errors.append(f"{url}: no jwks_uri")
98
+ raise AuthConfigError("could not find the provider's keys: " + "; ".join(errors))
99
+
100
+
101
+ class JwtVerifier:
102
+ """The SDK's ``TokenVerifier``: a JWT signed by the provider, for this
103
+ resource (``aud``), from this issuer (``iss``), not expired. Scopes are
104
+ read from ``scope`` (space-separated) or ``scp`` (a list) and checked by
105
+ the SDK's middleware against the required ones."""
106
+
107
+ def __init__(self, issuer: str, resource: str, keys: Any = None) -> None:
108
+ try:
109
+ import jwt # noqa: F401
110
+ except ImportError as e:
111
+ raise AuthConfigError(
112
+ "OAuth needs the remote extra: pip install 'graphlore[remote]'") from e
113
+ self.issuer = issuer
114
+ self.resource = resource
115
+ # a PyJWKClient (or anything with get_signing_key_from_jwt), made on first use
116
+ self._keys = keys
117
+
118
+ def _signing_key(self, token: str) -> Any:
119
+ import jwt
120
+
121
+ if self._keys is None:
122
+ if config.offline():
123
+ raise AuthConfigError("GRAPHLORE_OFFLINE: the provider's keys cannot be fetched")
124
+ self._keys = jwt.PyJWKClient(jwks_uri(self.issuer), cache_keys=True,
125
+ lifespan=3600, timeout=_TIMEOUT)
126
+ return self._keys.get_signing_key_from_jwt(token).key
127
+
128
+ def verify(self, token: str) -> Any:
129
+ """The token's ``AccessToken``, or None when it is not one for us."""
130
+ import jwt
131
+ from mcp.server.auth.provider import AccessToken
132
+
133
+ try:
134
+ claims = jwt.decode(
135
+ token, self._signing_key(token), algorithms=ALGORITHMS,
136
+ audience=self.resource, issuer=self.issuer,
137
+ options={"require": ["exp", "iss", "aud"]})
138
+ except (jwt.PyJWTError, AuthConfigError, ValueError, KeyError):
139
+ return None
140
+ raw = claims.get("scope")
141
+ scopes = raw.split() if isinstance(raw, str) else list(claims.get("scp") or [])
142
+ client = claims.get("client_id") or claims.get("azp") or claims.get("sub") or ""
143
+ return AccessToken(
144
+ token=token, client_id=str(client), scopes=[str(s) for s in scopes],
145
+ expires_at=int(claims["exp"]), resource=self.resource,
146
+ subject=str(claims["sub"]) if claims.get("sub") else None,
147
+ claims={"iss": claims["iss"]})
148
+
149
+ async def verify_token(self, token: str) -> Any:
150
+ import anyio
151
+
152
+ # the key fetch blocks: off the event loop
153
+ return await anyio.to_thread.run_sync(self.verify, token)
154
+
155
+
156
+ def apply(mcp: Any, conf: dict[str, Any], keys: Any = None) -> None:
157
+ """Make ``mcp``'s HTTP app require these tokens: the SDK reads its auth
158
+ settings and token verifier when it builds the app."""
159
+ from mcp.server.auth.settings import AuthSettings
160
+
161
+ if config.offline() and keys is None:
162
+ raise AuthConfigError("GRAPHLORE_OFFLINE is set: OAuth needs the provider's keys "
163
+ "from the network")
164
+ mcp.settings.auth = AuthSettings(
165
+ issuer_url=conf["issuer"], resource_server_url=conf["resource"],
166
+ required_scopes=conf["scopes"] or None,
167
+ # the verifier checks the audience itself
168
+ validate_token_resource=False)
169
+ mcp._token_verifier = JwtVerifier(conf["issuer"], conf["resource"], keys)
graphlore/resolve.py ADDED
@@ -0,0 +1,332 @@
1
+ """Edges the graph lacks and the source proves: calls through an imported module.
2
+
3
+ graphify's local extractor links ``from pkg import helper; helper()`` to the
4
+ function, but not ``from pkg import mod; mod.helper()`` — nor, often, the import
5
+ of ``mod`` itself. A test file that says ``from graphlore import server`` and
6
+ calls ``server.graphlore_unreferenced(...)`` four times then leaves that tool
7
+ with no caller at all, and every answer read from the edges (impact, neighbors,
8
+ subgraph, tests-for, references discounted in ``graphlore_unreferenced``) is
9
+ short by exactly those calls.
10
+
11
+ :func:`_resolved` adds them at read time, from the importing file's own AST:
12
+ ``mod.name(...)`` where ``mod`` is bound by an import to a first-party module
13
+ that defines ``name`` (or re-exports it from one that does). Added edges are
14
+ marked ``resolved_by: "graphlore"`` and never written back to graph.json.
15
+
16
+ Per language, only what its extractor is seen to leave out:
17
+
18
+ * **Python** — every call through a module object, and the module import.
19
+ * **JS / TS** — calls through a default import (``import api from './api'``)
20
+ and through a dynamically imported module (``const m = await import(..)``);
21
+ graphify already links namespace imports and ``require``.
22
+ * **Go, Java** — nothing: graphify links package-selector and static calls
23
+ itself, so there is no gap to fill.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import ast
28
+ from dataclasses import dataclass
29
+ from typing import Any, NamedTuple
30
+
31
+ from . import config
32
+ from .graph import (
33
+ _CALL_RELATIONS,
34
+ _IMPORT_RELATIONS,
35
+ _bare_name,
36
+ _edge_ends,
37
+ _engine_resolved,
38
+ _is_file_hub_node,
39
+ _node_file,
40
+ _node_id,
41
+ _node_label,
42
+ _node_line,
43
+ _rel,
44
+ )
45
+ from .imports import _JS_EXTS, ImportChecker, _js_for_file, _module_parts
46
+ from .spans import _cached_file_analysis, _enclosing_spans, _norm_relpath
47
+
48
+ RESOLVED_BY = "graphlore"
49
+ # How far a name is followed through re-exports (`from .graph import x` in the
50
+ # module the caller went through).
51
+ _REEXPORT_DEPTH = 3
52
+
53
+
54
+ class _Binding(NamedTuple):
55
+ level: int # 0 = absolute import, n = leading dots
56
+ module: tuple[str, ...] # dotted path of the statement's module
57
+ name: str | None # the from-imported name, None for `import a.b [as m]`
58
+ rooted: bool # `import a.b.c` with no alias: the name is the root `a`
59
+ line: int = 0 # line of the import statement
60
+
61
+
62
+ class _FileCalls(NamedTuple):
63
+ bindings: dict[str, _Binding]
64
+ # (lines of the enclosing defs, innermost first; line of the call; a.b.name chain)
65
+ calls: list[tuple[tuple[int, ...], int, tuple[str, ...]]]
66
+
67
+
68
+ def _attribute_chain(node: ast.expr) -> tuple[str, ...] | None:
69
+ """``a.b.c`` -> (a, b, c); None for anything not a plain dotted name."""
70
+ parts: list[str] = []
71
+ while isinstance(node, ast.Attribute):
72
+ parts.append(node.attr)
73
+ node = node.value
74
+ if not isinstance(node, ast.Name):
75
+ return None
76
+ parts.append(node.id)
77
+ return tuple(reversed(parts))
78
+
79
+
80
+ def _python_module_calls(src: bytes) -> _FileCalls | None:
81
+ try:
82
+ tree = ast.parse(src)
83
+ except Exception: # noqa: BLE001 - unparseable: nothing to resolve
84
+ return None
85
+ bindings: dict[str, _Binding] = {}
86
+ raw: list[tuple[tuple[int, ...], int, tuple[str, ...]]] = []
87
+
88
+ def walk(node: ast.AST, stack: tuple[int, ...]) -> None:
89
+ for child in ast.iter_child_nodes(node):
90
+ if isinstance(child, ast.Import):
91
+ for a in child.names:
92
+ parts = tuple(a.name.split("."))
93
+ if a.asname:
94
+ bindings[a.asname] = _Binding(0, parts, None, False, child.lineno)
95
+ else:
96
+ bindings.setdefault(
97
+ parts[0], _Binding(0, parts[:1], None, True, child.lineno)
98
+ )
99
+ elif isinstance(child, ast.ImportFrom):
100
+ module = tuple(child.module.split(".")) if child.module else ()
101
+ for a in child.names:
102
+ if a.name != "*":
103
+ bindings[a.asname or a.name] = _Binding(
104
+ child.level or 0, module, a.name, False, child.lineno
105
+ )
106
+ elif isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
107
+ walk(child, (child.lineno, *stack))
108
+ continue
109
+ elif isinstance(child, ast.Call):
110
+ chain = _attribute_chain(child.func)
111
+ if chain is not None and len(chain) >= 2:
112
+ raw.append((stack, child.lineno, chain))
113
+ walk(child, stack)
114
+
115
+ try:
116
+ walk(tree, ())
117
+ except RecursionError:
118
+ return None
119
+ return _FileCalls(bindings, [c for c in raw if c[2][0] in bindings])
120
+
121
+
122
+ # rel path -> (mtime, _FileCalls | None); the (path, mtime) scheme of the span cache.
123
+ _CALLS_CACHE: dict[str, tuple[float, Any]] = {}
124
+
125
+
126
+ def _module_calls_for_file(rel: str) -> _FileCalls | None:
127
+ if not rel.lower().endswith(".py"):
128
+ return None
129
+ return _cached_file_analysis(
130
+ _CALLS_CACHE, rel, lambda src, _rel_path: _python_module_calls(src), lambda: None
131
+ )
132
+
133
+
134
+ @dataclass
135
+ class Resolved:
136
+ """The graph's edges plus the ones graphlore resolved from the source.
137
+
138
+ ``edges`` IS the list passed in when nothing was added, so identity-keyed
139
+ caches keep hitting; otherwise it is built once per graph and reused.
140
+ """
141
+
142
+ edges: list[dict]
143
+ calls: int = 0
144
+ imports: int = 0
145
+
146
+ def payload(self) -> dict[str, int]:
147
+ return {"calls": self.calls, "imports": self.imports}
148
+
149
+ def note(self) -> str:
150
+ """One line naming what was added; "" when nothing was."""
151
+ if not (self.calls or self.imports):
152
+ return ""
153
+ bits = []
154
+ if self.calls:
155
+ bits.append(f"{self.calls} call(s) made through an imported module")
156
+ if self.imports:
157
+ bits.append(f"{self.imports} module import(s)")
158
+ return (
159
+ "Includes " + " and ".join(bits) + " that graph.json lacks, resolved by "
160
+ "graphlore from the source."
161
+ )
162
+
163
+
164
+ def _enabled() -> bool:
165
+ return config.env("RESOLVE", "1").strip().lower() not in ("0", "false", "no", "off")
166
+
167
+
168
+ def _build(nodes: list[dict], edges: list[dict]) -> Resolved:
169
+ # Indexes over the graph's Python files: module path -> file, the node that
170
+ # stands for each file, and each file's definitions by name and by line.
171
+ by_parts: dict[tuple[str, ...], str] = {}
172
+ by_last: dict[str, list[tuple[str, ...]]] = {}
173
+ hub: dict[str, str] = {}
174
+ by_name: dict[str, dict[str, str]] = {}
175
+ by_line: dict[str, dict[int, str]] = {}
176
+ js_files: set[str] = set()
177
+ for n in nodes:
178
+ file = _norm_relpath(_node_file(n))
179
+ low = file.lower()
180
+ if low.endswith(_JS_EXTS):
181
+ js_files.add(file)
182
+ elif not low.endswith(".py"):
183
+ continue
184
+ parts = _module_parts(file) if low.endswith(".py") else None
185
+ if parts is not None and parts not in by_parts:
186
+ by_parts[parts] = file
187
+ if parts:
188
+ by_last.setdefault(parts[-1], []).append(parts)
189
+ nid = _node_id(n)
190
+ if _is_file_hub_node(n):
191
+ hub.setdefault(file, nid)
192
+ continue
193
+ if str(n.get("file_type") or "code").lower() != "code":
194
+ continue
195
+ label = _node_label(n)
196
+ if not label.startswith("."): # a module's own names, not its classes' methods
197
+ by_name.setdefault(file, {}).setdefault(_bare_name(label), nid)
198
+ try:
199
+ by_line.setdefault(file, {}).setdefault(int(_node_line(n)), nid)
200
+ except (TypeError, ValueError):
201
+ pass
202
+ if not by_parts and not js_files:
203
+ return Resolved(edges)
204
+
205
+ known_calls: set[tuple[str, str]] = set()
206
+ known_imports: set[tuple[str, str]] = set()
207
+ byid = {_node_id(n): n for n in nodes}
208
+ for e in edges:
209
+ rel = _rel(e)
210
+ s, t = _edge_ends(e)
211
+ if rel in _CALL_RELATIONS:
212
+ known_calls.add((s, t))
213
+ elif rel in _IMPORT_RELATIONS:
214
+ sn, tn = byid.get(s), byid.get(t)
215
+ if sn is not None and tn is not None:
216
+ known_imports.add((_norm_relpath(_node_file(sn)), _norm_relpath(_node_file(tn))))
217
+
218
+ checker = ImportChecker()
219
+
220
+ def module_file(importer: str, b: _Binding, extra: tuple[str, ...]) -> str | None:
221
+ dotted = b.module + ((b.name,) if b.name else ()) + extra
222
+ return checker.resolve(importer, b.level, dotted, by_parts, by_last)
223
+
224
+ def definition(file: str, name: str, depth: int = 0) -> str | None:
225
+ """Node of ``name`` in ``file``, following re-exports a few modules deep."""
226
+ got = by_name.get(file, {}).get(name)
227
+ if got is not None or depth >= _REEXPORT_DEPTH:
228
+ return got
229
+ analysis = _module_calls_for_file(file)
230
+ b = analysis.bindings.get(name) if analysis else None
231
+ if b is None or b.name is None:
232
+ return None
233
+ origin = checker.resolve(file, b.level, b.module, by_parts, by_last)
234
+ return definition(origin, b.name, depth + 1) if origin else None
235
+
236
+ added: list[dict] = []
237
+ calls = imports = 0
238
+ for file in sorted(f for f in by_line.keys() | hub.keys() if f not in js_files):
239
+ analysis = _module_calls_for_file(file)
240
+ if analysis is None:
241
+ continue
242
+ for b in analysis.bindings.values():
243
+ target_file = module_file(file, b, ()) if not b.rooted else None
244
+ if (target_file and target_file != file and file in hub and target_file in hub
245
+ and (file, target_file) not in known_imports):
246
+ known_imports.add((file, target_file))
247
+ imports += 1
248
+ added.append({
249
+ "source": hub[file], "target": hub[target_file],
250
+ "relation": "imports_from", "confidence": "EXTRACTED",
251
+ "source_file": file, "source_location": f"L{b.line}",
252
+ "context": "import", "resolved_by": RESOLVED_BY,
253
+ })
254
+ for stack, line, chain in analysis.calls:
255
+ target_file = module_file(file, analysis.bindings[chain[0]], chain[1:-1])
256
+ if not target_file:
257
+ continue
258
+ target = definition(target_file, chain[-1])
259
+ lines = by_line.get(file, {})
260
+ source = next((lines[ln] for ln in stack if ln in lines), hub.get(file))
261
+ if not target or not source or source == target or (source, target) in known_calls:
262
+ continue
263
+ known_calls.add((source, target))
264
+ calls += 1
265
+ added.append({
266
+ "source": source, "target": target, "relation": "calls",
267
+ "confidence": "EXTRACTED", "source_file": file,
268
+ "source_location": f"L{line}", "context": "call",
269
+ "resolved_by": RESOLVED_BY,
270
+ })
271
+ # JS / TS: `name.prop(...)` where `name` stands for a whole module.
272
+ for file in sorted(js_files):
273
+ js = _js_for_file(file)
274
+ if js is None:
275
+ continue
276
+ targets: dict[str, str | None] = {}
277
+ for line, name, prop in js.calls:
278
+ specifier = js.bindings[name]
279
+ if specifier not in targets:
280
+ targets[specifier] = checker.resolve_js(file, specifier, js_files)
281
+ target_file = targets[specifier]
282
+ target = by_name.get(target_file, {}).get(prop) if target_file else None
283
+ if not target:
284
+ continue
285
+ # the innermost enclosing definition that has a node, else the file
286
+ lines = by_line.get(file, {})
287
+ source = next(
288
+ (lines[span[2]] for span in _enclosing_spans(file, line, line)
289
+ if span[2] in lines),
290
+ hub.get(file),
291
+ )
292
+ if not source or source == target or (source, target) in known_calls:
293
+ continue
294
+ known_calls.add((source, target))
295
+ calls += 1
296
+ added.append({
297
+ "source": source, "target": target, "relation": "calls",
298
+ "confidence": "EXTRACTED", "source_file": file,
299
+ "source_location": f"L{line}", "context": "call",
300
+ "resolved_by": RESOLVED_BY,
301
+ })
302
+ if not added:
303
+ return Resolved(edges)
304
+ return Resolved([*edges, *added], calls, imports)
305
+
306
+
307
+ # (id(nodes), id(edges)) -> (nodes, edges, project dir, Resolved), identity-guarded
308
+ # like graph._ADJ_CACHE: the extended list must be the same object across calls.
309
+ _RESOLVED_CACHE: dict[tuple[int, int], tuple[list[dict], list[dict], str, Resolved]] = {}
310
+ _RESOLVED_CACHE_MAX = 8
311
+
312
+
313
+ def _resolved(nodes: list[dict], edges: list[dict]) -> Resolved:
314
+ """``edges`` plus the calls and imports graphlore can prove from the source.
315
+
316
+ Off with ``GRAPHLORE_RESOLVE=0``. Costs one parse per Python and JS/TS file
317
+ of the graph (cached per file by mtime), once per loaded graph.
318
+ """
319
+ if not _enabled() or _engine_resolved(nodes):
320
+ # graphlore's native engine resolved these calls and imports itself
321
+ return Resolved(edges)
322
+ ident = (id(nodes), id(edges))
323
+ project = str(config.PROJECT_DIR)
324
+ cached = _RESOLVED_CACHE.get(ident)
325
+ if (cached is not None and cached[0] is nodes and cached[1] is edges
326
+ and cached[2] == project):
327
+ return cached[3]
328
+ result = _build(nodes, edges)
329
+ if ident not in _RESOLVED_CACHE and len(_RESOLVED_CACHE) >= _RESOLVED_CACHE_MAX:
330
+ _RESOLVED_CACHE.pop(next(iter(_RESOLVED_CACHE)), None) # FIFO
331
+ _RESOLVED_CACHE[ident] = (nodes, edges, project, result)
332
+ return result