codefactory-cli 0.20.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/sbom.py ADDED
@@ -0,0 +1,78 @@
1
+ """`codefactory sbom`: a CycloneDX 1.5 software bill of materials from the repository's lockfiles.
2
+
3
+ The same lockfiles the vulnerability check reads (npm, yarn, pnpm, Poetry, uv, Pipfile, pinned requirements, Cargo,
4
+ Go, Bundler, Composer), so the versions are exactly what's installed. Each component has a package URL (purl), the
5
+ lockfile it came from, and scope "optional" when it's development-only. Offline; nothing leaves the machine.
6
+
7
+ The output is deterministic (sorted, no random serial number, timestamp only from SOURCE_DATE_EPOCH), so the same
8
+ lockfiles give the same file and an SBOM can be diffed, signed and attested.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import uuid
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+ from urllib.parse import quote
19
+
20
+ from . import __version__
21
+ from .deps import Package, packages
22
+
23
+ PURL_TYPE = {"npm": "npm", "PyPI": "pypi", "crates.io": "cargo", "Go": "golang", "RubyGems": "gem", "Packagist": "composer"}
24
+
25
+
26
+ def purl(p: Package) -> str:
27
+ kind = PURL_TYPE[p.ecosystem]
28
+ name = p.name.lower().replace("_", "-") if kind == "pypi" else p.name
29
+ if kind == "npm" and name.startswith("@"): # pkg:npm/%40scope/name
30
+ scope, _, rest = name.partition("/")
31
+ path = f"{quote(scope)}/{quote(rest)}"
32
+ else:
33
+ path = "/".join(quote(part) for part in name.split("/"))
34
+ return f"pkg:{kind}/{path}@{quote(p.version, safe='')}"
35
+
36
+
37
+ def document(root: Path) -> dict:
38
+ pkgs = sorted(packages(root), key=lambda p: (p.ecosystem, p.name.lower(), p.version, p.source))
39
+ components, seen = [], set()
40
+ for p in pkgs:
41
+ ref = purl(p)
42
+ if ref in seen: # the same package in two lockfiles: once, from the first
43
+ continue
44
+ seen.add(ref)
45
+ components.append(
46
+ {
47
+ "type": "library",
48
+ "bom-ref": ref,
49
+ "name": p.name,
50
+ "version": p.version,
51
+ "purl": ref,
52
+ "scope": "optional" if p.dev else "required",
53
+ "properties": [{"name": "codefactory:lockfile", "value": p.source}],
54
+ }
55
+ )
56
+ body = json.dumps(components, sort_keys=True)
57
+ meta: dict = {
58
+ "tools": {"components": [{"type": "application", "name": "codefactory", "version": __version__}]},
59
+ "component": {"type": "application", "bom-ref": "root", "name": root.resolve().name},
60
+ }
61
+ if epoch := os.environ.get("SOURCE_DATE_EPOCH"): # reproducible builds set this; otherwise no clock in the file
62
+ meta["timestamp"] = datetime.fromtimestamp(int(epoch), UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
63
+ return {
64
+ "bomFormat": "CycloneDX",
65
+ "specVersion": "1.5",
66
+ "serialNumber": f"urn:uuid:{uuid.uuid5(uuid.NAMESPACE_URL, 'codefactory:' + body)}", # same content, same id
67
+ "version": 1,
68
+ "metadata": meta,
69
+ "components": components,
70
+ "dependencies": [{"ref": "root", "dependsOn": [c["bom-ref"] for c in components if c["scope"] == "required"]}],
71
+ }
72
+
73
+
74
+ def write(root: Path, out: Path | None) -> str:
75
+ text = json.dumps(document(root), indent=2) + "\n"
76
+ if out:
77
+ out.write_text(text, encoding="utf-8")
78
+ return text
@@ -0,0 +1,537 @@
1
+ """The attack surface: where requests come in, whether they check who's asking, and what risky code they reach.
2
+
3
+ Entry points are found per framework from the source text around each handler (decorators, route registrations,
4
+ file conventions): FastAPI, Flask, Django and DRF, Express-style routers (Express, Koa, Fastify, Hono), Next.js API
5
+ routes, Spring, Go net/http and gin/echo/chi, Rails and Sinatra. From each entry, the call graph says which risky
6
+ lines it reaches (SQL built from strings, shell commands, eval, raw HTML) and whether it writes data. A finding on a
7
+ path from a request is evidence; one no request reaches is a lead at most.
8
+
9
+ All of it is pattern-based: an auth check done some other way (a gateway, a custom decorator with an unusual name)
10
+ is missed, so "no auth check found" is a question to answer, and the report says so.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections import deque
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ from .brief import View
21
+ from .efficiency import kind_of
22
+ from .paths import is_test
23
+
24
+ AUTH = re.compile(
25
+ r"auth|login|logged|jwt|token|session|permission|current_?user|require_?user|verify|protect|guard|admin|"
26
+ r"secured|roles?_?(?:required|allowed)|principal|bearer|api_?key|signed_?in|ensure_?user|clerk|passport|"
27
+ r"require_?account|require_?user|authenticated",
28
+ re.I,
29
+ )
30
+ SINK_KINDS = ("sql_built", "shell", "eval", "raw_html")
31
+ METHODS = "get|post|put|patch|delete|head|options"
32
+
33
+ PY_ROUTE = re.compile(
34
+ rf"@\s*(?!mock\.|patch\.|unittest\.)[\w.]+\.({METHODS}|api_route|route|websocket)\(\s*(?:path\s*=\s*)?[rf]?['\"]([^'\"]*)['\"]([^\n]*)"
35
+ )
36
+ PY_METHODS = re.compile(r"methods\s*=\s*[\[(]([^\])]*)")
37
+ DRF_VIEW = re.compile(r"@\s*api_view\(\s*\[?([^\])]*)")
38
+ PY_AUTH_DECORATOR = re.compile(
39
+ r"@\s*[\w.]*(?:login_required|permission_required|jwt_required|token_required|auth\w*_required|requires?_auth\w*|"
40
+ r"admin_required|roles?_(?:required|accepted)|authenticated|protected|user_passes_test|staff_member_required)\b"
41
+ )
42
+ DEPENDS = re.compile(r"(?:Depends|Security)\(\s*([\w.]+)")
43
+ ALIAS = re.compile(r"^(\w+)\s*=\s*Annotated\[[^\n]*?(?:Depends|Security)\(\s*([\w.]+)", re.M)
44
+ ROUTER_DEPS = re.compile(r"(?:APIRouter|FastAPI|include_router)\([^)]*dependencies\s*=\s*\[([^\]]*)\]", re.S)
45
+ DJANGO_PATH = re.compile(r"\b(?:re_)?path\(\s*r?['\"]([^'\"]*)['\"]\s*,\s*([\w.]+)")
46
+ JS_ROUTE = re.compile(rf"\b(\w+)\.({METHODS}|all)\(\s*['\"`](/[^'\"`]*)['\"`]\s*,([^\n]*)")
47
+ JS_APP_AUTH = re.compile(r"\b\w+\.use\(\s*([^\n)]*)")
48
+ NEXT_METHOD = re.compile(r"^(GET|POST|PUT|PATCH|DELETE)$")
49
+ SPRING = re.compile(r"@(Get|Post|Put|Patch|Delete|Request)Mapping\b\s*(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?\"([^\"]*)\")?")
50
+ SPRING_AUTH = re.compile(r"@(?:PreAuthorize|Secured|RolesAllowed|PostAuthorize)\b")
51
+ GO_ROUTE = re.compile(
52
+ r"\b\w+\.(HandleFunc|Handle|GET|POST|PUT|PATCH|DELETE|Get|Post|Put|Patch|Delete|Any)\(\s*\"(/[^\"]*)\"\s*,\s*([^\n]*)"
53
+ )
54
+ # Laravel (routes/*.php) and Symfony attributes
55
+ LARAVEL_ROUTE = re.compile(
56
+ r"Route::(get|post|put|patch|delete|any|match|resource|apiResource)\(\s*(?:\[[^\]]*\],\s*)?['\"]([^'\"]+)['\"]"
57
+ )
58
+ SYMFONY_ROUTE = re.compile(r"#\[Route\(\s*(?:path:\s*)?['\"]([^'\"]+)['\"][^\]]*?(?:methods:\s*\[([^\]]*)\])?")
59
+ # Rust: Rocket / Actix attribute macros, Axum's router
60
+ RUST_ATTR_ROUTE = re.compile(r"#\[(get|post|put|patch|delete|head|options|route)\(\s*\"([^\"]*)\"")
61
+ AXUM_ROUTE = re.compile(r"\.route\(\s*\"(/[^\"]*)\"\s*,\s*(get|post|put|patch|delete|any)\(\s*([\w:]+)")
62
+ RUST_GUARD = re.compile(r"impl\s*(?:<[^>]*>)?\s*FromRequest(?:Parts)?\s*(?:<[^>]*>)?\s*for\s+(\w+)")
63
+ # ASP.NET: minimal APIs and controller attributes
64
+ ASPNET_MAP = re.compile(r"(\w+)\.Map(Get|Post|Put|Patch|Delete|Methods)\(\s*\"([^\"]*)\"")
65
+ ASPNET_GROUP = re.compile(r"(?:var\s+)?(\w+)\s*=\s*[^;]*?MapGroup\([^;]*;", re.S)
66
+ ASPNET_ATTR = re.compile(r"\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*\"([^\"]*)\"\s*\))?\]")
67
+ # Phoenix (Elixir) router
68
+ PHOENIX_ROUTE = re.compile(r"^\s*(get|post|put|patch|delete|live|resources|forward)\s+\"(/[^\"]*)\"(?:\s*,\s*([\w.]+))?", re.M)
69
+ SINATRA = re.compile(r"^\s*(get|post|put|patch|delete)\s+['\"](/[^'\"]*)['\"]", re.M)
70
+ RAILS_AUTH = re.compile(r"before_action\s+:(\w+[!?]?)")
71
+ LOCAL = re.compile(r"""(?:host|bind|api_host|HOST)(?:\s*:\s*\w+)?\s*[=:]\s*['"](127\.0\.0\.1|localhost|::1)['"]""")
72
+ OPEN = re.compile(r"""['"]0\.0\.0\.0['"]""") # anywhere: a server that can listen on every interface
73
+ # What shows a change: the SQL verb, or a call named for it. A bare commit/rollback only ends a transaction (every
74
+ # `with db.session():` helper does it), so it isn't evidence that anything changed.
75
+ CHANGES = re.compile(
76
+ r"INSERT|UPDATE|DELETE|REPLACE|UPSERT|MERGE|(?:^|\.)(?:save|insert\w*|update\w*|delete\w*|remove\w*|create\w*|"
77
+ r"upsert\w*|put\w*|write\w*|add\w*|set\w*|destroy\w*|bulk_\w+)(?:\(|$)",
78
+ )
79
+ WRITE_CALL = re.compile(r"(?:^|\.)(?:run|runAsync|runSync|execAsync|execSync|executeUpdate|executemany|executescript)\b")
80
+
81
+
82
+ @dataclass
83
+ class Entry:
84
+ fn: str # the handler's function id (the file's <module> for an inline handler)
85
+ method: str
86
+ path: str
87
+ framework: str
88
+ file: str
89
+ line: int
90
+ auth: str = "" # what checks the caller ("Depends(get_current_user)", "@login_required", "app-wide …"), or ""
91
+
92
+
93
+ @dataclass
94
+ class Surface:
95
+ entries: list[Entry] = field(default_factory=list)
96
+ reach: dict[str, tuple[int, list[str]]] = field(default_factory=dict) # fn -> (entry index, path of fn ids)
97
+ exposure: str = "unknown" # local | open | configurable | unknown
98
+ exposure_evidence: str = ""
99
+
100
+ def chain(self, fid: str, v: View) -> str:
101
+ if fid not in self.reach:
102
+ return ""
103
+ i, path = self.reach[fid]
104
+ e = self.entries[i]
105
+ names = [v.fn[p]["qualname"] for p in path if p in v.fn and v.fn[p]["kind"] != "module"]
106
+ return f"{e.method} {e.path} → " + " → ".join(names or [Path(e.file).name])
107
+
108
+
109
+ def _read(root: Path, cache: dict, file: str) -> list[str]:
110
+ if file not in cache:
111
+ try:
112
+ cache[file] = (root / file).read_text(encoding="utf-8", errors="replace").splitlines()
113
+ except OSError:
114
+ cache[file] = []
115
+ return cache[file]
116
+
117
+
118
+ def _above(lines: list[str], line: int, limit: int = 12) -> str:
119
+ """Decorators and annotations right above a definition (line is 1-based)."""
120
+ out, i = [], line - 2
121
+ while i >= 0 and len(out) < limit:
122
+ s = lines[i].strip()
123
+ if not s or not (s.startswith("@") or s.endswith((",", "(", ")", "]")) or out and s.startswith(("'", '"', ")"))):
124
+ break
125
+ out.append(lines[i])
126
+ i -= 1
127
+ return "\n".join(reversed(out))
128
+
129
+
130
+ def _signature(lines: list[str], line: int) -> str:
131
+ return "\n".join(lines[line - 1 : line + 8]).split(":\n")[0]
132
+
133
+
134
+ RAILS_CLASS = re.compile(r"^\s*class\s+([\w:]+)\s*<\s*([\w:]+)", re.M)
135
+ RAILS_SKIP = re.compile(r"skip_before_action\s+:(\w+)(?:[^\n]*?only:\s*\[?([^\]\n]*))?")
136
+
137
+
138
+ class _RailsControllers:
139
+ """Auth a Rails controller gets from the controllers it inherits from (`before_action :authenticate_user!` in
140
+ ApplicationController or an API base controller), and what it skips with `skip_before_action`."""
141
+
142
+ def __init__(self, root: Path, files: list[str], cache: dict):
143
+ self.own: dict[str, tuple[str, str]] = {} # class short name -> (guard, parent short name)
144
+ self.concerns: dict[str, str] = {} # concern module name -> the auth before_action its `included` block adds
145
+ for file in files:
146
+ text = "\n".join(_read(root, cache, file))
147
+ if "/concerns/" in file:
148
+ guard = next((a for a in RAILS_AUTH.findall(text) if AUTH.search(a)), "")
149
+ m = re.search(r"^\s*module\s+([\w:]+)", text, re.M)
150
+ if guard and m:
151
+ self.concerns[m.group(1).split("::")[-1]] = guard
152
+ for file in files:
153
+ text = "\n".join(_read(root, cache, file))
154
+ m = RAILS_CLASS.search(text)
155
+ if m and "/concerns/" not in file:
156
+ self.own[m.group(1).split("::")[-1]] = (self._own(text), m.group(2).split("::")[-1])
157
+
158
+ def _own(self, text: str) -> str:
159
+ """The controller's own auth before_action, or one an included concern adds (`include Authentication`)."""
160
+ own = next((a for a in RAILS_AUTH.findall(text) if AUTH.search(a)), "")
161
+ if own:
162
+ return own
163
+ for line in re.findall(r"^\s*include\s+([^\n]+)", text, re.M):
164
+ for name in re.findall(r"[\w:]+", line):
165
+ if name.split("::")[-1] in self.concerns:
166
+ return self.concerns[name.split("::")[-1]]
167
+ return ""
168
+
169
+ def guard(self, text: str) -> tuple[str, str]:
170
+ """(the auth before_action that applies, "from <Parent>" when inherited)."""
171
+ m = RAILS_CLASS.search(text)
172
+ own = self._own(text)
173
+ if own or not m:
174
+ return own, ""
175
+ parent, seen = m.group(2).split("::")[-1], set()
176
+ while parent in self.own and parent not in seen:
177
+ seen.add(parent)
178
+ guard, grand = self.own[parent]
179
+ if guard:
180
+ return guard, f"from {parent}"
181
+ parent = grand
182
+ return "", ""
183
+
184
+ @staticmethod
185
+ def skipped(text: str) -> set[str] | None:
186
+ """Actions an auth before_action is skipped for: None (not skipped), empty (all), or the `only:` ones."""
187
+ for m in RAILS_SKIP.finditer(text):
188
+ if AUTH.search(m.group(1)):
189
+ return set(re.findall(r"\w+", m.group(2) or ""))
190
+ # a concern's helper: `skip_authentication only: :new` (Rails 8's generator, and many apps)
191
+ for m in re.finditer(r"^\s*(?:skip_\w*auth\w*|allow_unauthenticated_access)\b([^\n]*)", text, re.M):
192
+ only = re.search(r"only:\s*\[?([^\]\n]*)", m.group(1))
193
+ return set(re.findall(r"\w+", only.group(1))) if only else set()
194
+ return None
195
+
196
+
197
+ def _php_entries(file: str, lines: list[str], text: str, module, fns: list[dict]) -> list[Entry]:
198
+ out = []
199
+ if module and re.search(r"(?:^|/)routes/[\w/]+\.php$", file):
200
+ auth_until = [] # brace depths of open groups whose middleware checks who's asking
201
+ depth = 0
202
+ for i, ln in enumerate(lines, 1):
203
+ if re.search(r"middleware\(", ln) and AUTH.search(ln) and ("{" in ln or "group(" in ln):
204
+ auth_until.append(depth)
205
+ m = LARAVEL_ROUTE.search(ln)
206
+ if m:
207
+ verb = {"any": "ANY", "match": "ANY", "resource": "ANY", "apiresource": "ANY"}.get(m.group(1).lower(),
208
+ m.group(1).upper()) # fmt: skip
209
+ guard = "middleware(auth) group" if auth_until else ""
210
+ if re.search(r"->middleware\(", ln) and AUTH.search(ln.split("->middleware(", 1)[1]):
211
+ guard = "->middleware(auth)"
212
+ out.append(Entry(module["id"], verb, "/" + m.group(2).lstrip("/"), "Laravel", file, i, guard))
213
+ depth += ln.count("{") - ln.count("}")
214
+ while auth_until and depth <= auth_until[-1]:
215
+ auth_until.pop()
216
+ for f in fns: # Symfony: #[Route('/x', methods: ['POST'])] on a controller method
217
+ if f["kind"] == "module":
218
+ continue
219
+ head = "\n".join(lines[max(0, f["line"] - 6) : f["line"] + 1])
220
+ m = SYMFONY_ROUTE.search(head)
221
+ if m:
222
+ verb = ",".join(re.findall(r"\w+", m.group(2) or "")).upper() or "ANY"
223
+ auth = re.search(r"#\[IsGranted|denyAccessUnlessGranted|#\[Security", head + "\n".join(lines[f["line"] : f["end"]]))
224
+ out.append(Entry(f["id"], verb, m.group(1), "Symfony", file, f["line"], auth.group(0) if auth else ""))
225
+ return out
226
+
227
+
228
+ def _rust_entries(file, lines, text, module, named, fns, guards: set[str]) -> list[Entry]:
229
+ out = []
230
+ for f in fns: # Rocket / Actix: the attribute is on (or just above) the function's first line
231
+ if f["kind"] == "module":
232
+ continue
233
+ # the attributes stacked directly above (or starting) this function, then its signature up to the body
234
+ start = f["line"] - 1
235
+ while start > 0 and re.match(r"\s*(?:#\[|///)", lines[start - 1]):
236
+ start -= 1
237
+ attrs = "\n".join(ln for ln in lines[start : f["line"]] if re.match(r"\s*#\[", ln))
238
+ sig = "\n".join(lines[f["line"] - 1 : f["line"] + 6]).split("{")[0]
239
+ m = RUST_ATTR_ROUTE.search(attrs + "\n" + sig.split("fn ", 1)[0])
240
+ if m:
241
+ auth = next((g for g in guards if re.search(rf":\s*{g}\b", sig)), "") or ((a := AUTH.search(sig)) and a.group(0))
242
+ out.append(Entry(f["id"], m.group(1).upper(), m.group(2), "Rust", file, f["line"], auth or ""))
243
+ for i, ln in enumerate(lines, 1): # Axum: .route("/x", get(handler))
244
+ m = AXUM_ROUTE.search(ln)
245
+ if m and (handler := named.get(m.group(3).split("::")[-1]) or module):
246
+ out.append(Entry(handler["id"], m.group(2).upper(), m.group(1), "Axum", file, i, ""))
247
+ return out
248
+
249
+
250
+ def _aspnet_entries(file, lines, text, module, fns) -> list[Entry]:
251
+ out = []
252
+ authed = {m.group(1) for m in ASPNET_GROUP.finditer(text) if "RequireAuthorization" in m.group(0)}
253
+ class_auth = re.search(r"\[Authorize[\](]", text) and not re.search(r"\[AllowAnonymous\]", text)
254
+ for i, ln in enumerate(lines, 1): # minimal APIs: app.MapGet("/x", ...), group.MapPost(...)
255
+ m = ASPNET_MAP.search(ln)
256
+ if m and module:
257
+ tail = " ".join(lines[i - 1 : i + 3])
258
+ auth = "RequireAuthorization()" if (m.group(1) in authed or "RequireAuthorization" in tail) else ""
259
+ out.append(Entry(module["id"], m.group(2).upper(), m.group(3), "ASP.NET", file, i, auth))
260
+ for f in fns: # controllers: [HttpGet("x")] on a method, [Authorize] on it or its class
261
+ if f["kind"] == "module":
262
+ continue
263
+ head = "\n".join(lines[max(0, f["line"] - 6) : f["line"] + 1])
264
+ m = ASPNET_ATTR.search(head)
265
+ if m:
266
+ auth = "[Authorize]" if ("[Authorize" in head or class_auth) and "[AllowAnonymous]" not in head else ""
267
+ out.append(Entry(f["id"], m.group(1).upper(), m.group(2) or "", "ASP.NET", file, f["line"], auth))
268
+ return out
269
+
270
+
271
+ def _phoenix_entries(file, lines, module, plugs: dict[str, str]) -> list[Entry]:
272
+ """Routes from a Phoenix router. Auth: a `pipe_through` or `live_session` with an auth plug or hook, or a `plug`
273
+ in the controller (or LiveView) the route points at."""
274
+ out, piped, session = [], "", ""
275
+ for i, ln in enumerate(lines, 1):
276
+ if m := re.search(r"pipe_through\s+(.+)", ln):
277
+ piped = m.group(1)
278
+ elif re.match(r"\s*scope\b", ln):
279
+ piped = ""
280
+ if m := re.match(r"\s*live_session\s+(.+)", ln):
281
+ session = m.group(1)
282
+ elif session and re.match(r"\s*end\b", ln) and len(ln) - len(ln.lstrip()) <= 4:
283
+ session = ""
284
+ m = PHOENIX_ROUTE.match(ln)
285
+ if m and module:
286
+ target = (m.group(3) or "").split(".")[-1]
287
+ auth = (
288
+ (AUTH.search(piped) and f"pipe_through {piped.strip()}")
289
+ or (AUTH.search(session) and f"live_session {session.strip()[:60]}")
290
+ or (target in plugs and f"{target}: plug {plugs[target]}")
291
+ or ""
292
+ )
293
+ verb = "ANY" if m.group(1) in ("live", "resources", "forward") else m.group(1).upper()
294
+ out.append(Entry(module["id"], verb, m.group(2), "Phoenix", file, i, auth))
295
+ return out
296
+
297
+
298
+ def find_entries(root: Path, g: dict, v: View) -> list[Entry]:
299
+ cache: dict[str, list[str]] = {}
300
+ by_file: dict[str, list[dict]] = {}
301
+ for f in g["functions"]:
302
+ by_file.setdefault(f["file"], []).append(f)
303
+ entries: list[Entry] = []
304
+ rust_guards: set[str] = set() # request guards that check a token or session (`impl FromRequest for Headers`)
305
+ for f in (f for f in by_file if f.endswith(".rs")):
306
+ rust_text = "\n".join(_read(root, cache, f))
307
+ rust_guards |= {m.group(1) for m in RUST_GUARD.finditer(rust_text) if AUTH.search(rust_text[m.end() : m.end() + 3000])}
308
+ phoenix_plugs: dict[str, str] = {} # controller or LiveView short name -> the auth plug / on_mount hook it uses
309
+ for f in (f for f in by_file if f.endswith(".ex")):
310
+ ex_text = "\n".join(_read(root, cache, f))
311
+ mod = re.search(r"^\s*defmodule\s+([\w.]+)", ex_text, re.M)
312
+ guard = next((m.group(1) for m in re.finditer(r"^\s*(?:plug|on_mount)\s+([\w.:]+)", ex_text, re.M)
313
+ if AUTH.search(m.group(1))), "") # fmt: skip
314
+ if mod and guard:
315
+ phoenix_plugs[mod.group(1).split(".")[-1]] = guard
316
+ by_name: dict[str, list[dict]] = {} # Django URL handlers by name, and class-based views' methods by class
317
+ by_class: dict[str, list[dict]] = {}
318
+ for fn in g["functions"]:
319
+ if fn["kind"] != "module":
320
+ by_name.setdefault(fn["name"], []).append(fn)
321
+ if fn["kind"] == "method":
322
+ by_class.setdefault(fn["qualname"].split(".")[0], []).append(fn)
323
+ rails = _RailsControllers(root, [f for f in by_file if f.endswith("_controller.rb") or "controllers/concerns/" in f], cache)
324
+ aliases = {} # FastAPI: CurrentUser = Annotated[User, Depends(get_current_user)]
325
+ for file in by_file:
326
+ if file.endswith(".py"):
327
+ for m in ALIAS.finditer("\n".join(_read(root, cache, file))):
328
+ aliases[m.group(1)] = m.group(2)
329
+ for file, fns in by_file.items():
330
+ if is_test(file): # a test's `@mock.patch(...)` or a fake server isn't the product's surface
331
+ continue
332
+ lines = _read(root, cache, file)
333
+ text = "\n".join(lines)
334
+ module = next((f for f in fns if f["kind"] == "module"), None)
335
+ named = {f["name"]: f for f in fns if f["kind"] != "module"}
336
+ if file.endswith(".py"):
337
+ pm = re.search(r"(?:APIRouter|Blueprint)\([^)]*?(?:prefix|url_prefix)\s*=\s*['\"]([^'\"]*)['\"]", text, re.S)
338
+ prefix = pm.group(1).rstrip("/") if pm else ""
339
+ router_auth = ", ".join(n for m in ROUTER_DEPS.finditer(text) for n in DEPENDS.findall(m.group(1)) if AUTH.search(n))
340
+ for f in fns:
341
+ if f["kind"] == "module":
342
+ continue
343
+ deco = _above(lines, f["line"])
344
+ route, drf = PY_ROUTE.search(deco), DRF_VIEW.search(deco)
345
+ if not (route or drf):
346
+ continue
347
+ if route:
348
+ verb, path, rest = route.group(1).upper(), route.group(2), route.group(3)
349
+ if verb in ("ROUTE", "API_ROUTE"):
350
+ ms = PY_METHODS.search(rest)
351
+ verb = ",".join(re.findall(r"\w+", ms.group(1))).upper() if ms else "GET"
352
+ framework = "FastAPI" if re.search(r"APIRouter|FastAPI", text) else "Flask"
353
+ else:
354
+ verb, path, framework = ",".join(re.findall(r"\w+", drf.group(1))).upper() or "GET", f["name"], "DRF"
355
+ sig = _signature(lines, f["line"])
356
+ deps = [d for d in DEPENDS.findall(deco + sig) if AUTH.search(d)]
357
+ deps += [aliases[a] for a in re.findall(r":\s*(\w+)", sig) if a in aliases and AUTH.search(aliases[a])]
358
+ auth = (
359
+ (PY_AUTH_DECORATOR.search(deco) and PY_AUTH_DECORATOR.search(deco).group(0).strip())
360
+ or (deps and f"Depends({deps[0]})")
361
+ or (router_auth and f"router: Depends({router_auth})")
362
+ or ""
363
+ )
364
+ entries.append(Entry(f["id"], verb, (prefix + path) if route else path, framework, file, f["line"], auth))
365
+ if file.endswith("urls.py"):
366
+ here = file.rsplit("/", 1)[0] if "/" in file else ""
367
+ for m in DJANGO_PATH.finditer(text):
368
+ dotted = m.group(2).split(".")
369
+ target, module = dotted[-1], (dotted[-2] if len(dotted) > 1 else "views")
370
+ # one handler per URL: the function (or class-based view) of that name, nearest the urls.py and
371
+ # in the module it names; not every function called `index` in the project
372
+ cands = by_name.get(target, []) or by_class.get(target, [])
373
+ if not cands:
374
+ continue
375
+ f = min(cands, key=lambda c: (not c["file"].startswith(here + "/") if here else False,
376
+ Path(c["file"]).stem != module, c["file"].count("/"), c["line"])) # fmt: skip
377
+ deco = _above(_read(root, cache, f["file"]), f["line"])
378
+ auth = PY_AUTH_DECORATOR.search(deco)
379
+ entries.append(Entry(f["id"], "ANY", "/" + m.group(1), "Django", f["file"], f["line"],
380
+ auth.group(0).strip() if auth else "")) # fmt: skip
381
+ elif file.endswith((".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")):
382
+ app_auth = next((m.group(1) for m in JS_APP_AUTH.finditer(text) if AUTH.search(m.group(1))), "")
383
+ for i, ln in enumerate(lines, 1):
384
+ m = JS_ROUTE.search(ln)
385
+ if not m or m.group(1) in ("axios", "http", "fetch", "client", "api", "request", "supertest", "agent"):
386
+ continue
387
+ rest = re.sub(r"\)\s*;?\s*(?://.*)?$", "", m.group(4)) # the call's closing `);`
388
+ args = [a.strip() for a in rest.split(",") if a.strip()]
389
+ idents = [a for a in args if re.fullmatch(r"[\w.]+", a)]
390
+ handler = named.get(idents[-1].split(".")[-1]) if idents and not re.search(r"=>|function", args[-1]) else None
391
+ middleware = idents[:-1] if handler else idents
392
+ auth = next((mw for mw in middleware if AUTH.search(mw)), "") or (app_auth and f"app.use({app_auth})")
393
+ target = handler or module
394
+ if target:
395
+ entries.append(Entry(target["id"], m.group(2).upper(), m.group(3), "Express-style", file, i, auth))
396
+ api_route = re.search(r"(?:^|/)pages/api/", file) or re.search(r"(?:^|/)app/.*route\.[jt]sx?$", file)
397
+ if api_route:
398
+ for f in fns:
399
+ if f["kind"] == "module" or not (NEXT_METHOD.match(f["name"]) or f.get("exported")):
400
+ continue
401
+ body = "\n".join(lines[f["line"] - 1 : f["end"]])
402
+ auth = re.search(
403
+ r"getServerSession|getToken|auth\(\)|currentUser|requireAuth|clerk|withAuth|"
404
+ r"verify\w*(?:user|access|auth|session|token)\w*\(|"
405
+ r"constructEvent\(|verify\w*signature|webhooks?\.verify", # a webhook checks its signature
406
+ body,
407
+ re.I,
408
+ )
409
+ path = "/" + re.sub(r"^.*?(?:pages/api|app)/|/?route\.[jt]sx?$|\.[jt]sx?$", "", file)
410
+ method = f["name"] if NEXT_METHOD.match(f["name"]) else "ANY"
411
+ entries.append(Entry(f["id"], method, path, "Next.js", file, f["line"], auth.group(0) if auth else ""))
412
+ elif file.endswith((".java", ".kt")):
413
+ for f in fns:
414
+ if f["kind"] == "module":
415
+ continue
416
+ # tree-sitter starts a Java/Kotlin method at its annotations: read them from the method's own lines
417
+ head = "\n".join(lines[f["line"] - 1 : f["line"] + 8]).split("{")[0]
418
+ deco = _above(lines, f["line"]) + "\n" + head
419
+ m = SPRING.search(deco)
420
+ if m:
421
+ auth = SPRING_AUTH.search(deco)
422
+ verb = "ANY" if m.group(1) == "Request" else m.group(1).upper()
423
+ entries.append(
424
+ Entry(f["id"], verb, m.group(2) or "", "Spring", file, f["line"], auth.group(0) if auth else "")
425
+ )
426
+ elif file.endswith(".php"):
427
+ entries += _php_entries(file, lines, text, module, fns)
428
+ elif file.endswith(".rs"):
429
+ entries += _rust_entries(file, lines, text, module, named, fns, rust_guards)
430
+ elif file.endswith(".cs"):
431
+ entries += _aspnet_entries(file, lines, text, module, fns)
432
+ elif file.endswith(".ex") and file.endswith("router.ex"):
433
+ entries += _phoenix_entries(file, lines, module, phoenix_plugs)
434
+ elif file.endswith(".go"):
435
+ for i, ln in enumerate(lines, 1):
436
+ m = GO_ROUTE.search(ln)
437
+ if m:
438
+ args = re.findall(r"[\w.]+", m.group(3))
439
+ handler = next((named[a.split(".")[-1]] for a in reversed(args) if a.split(".")[-1] in named), None)
440
+ auth = next((a for a in args if AUTH.search(a)), "")
441
+ verb = "ANY" if m.group(1) in ("HandleFunc", "Handle", "Any") else m.group(1).upper()
442
+ if handler or module:
443
+ entries.append(Entry((handler or module)["id"], verb, m.group(2), "Go", file, i, auth))
444
+ elif file.endswith(".rb"):
445
+ for m in SINATRA.finditer(text):
446
+ if module:
447
+ line = text[: m.start()].count("\n") + 1
448
+ entries.append(Entry(module["id"], m.group(1).upper(), m.group(2), "Sinatra", file, line))
449
+ if re.search(r"(?:^|/)app/controllers/.*_controller\.rb$", file):
450
+ private_at = next((i for i, ln in enumerate(lines, 1) if re.match(r"\s*(private|protected)\s*$", ln)), 10**9)
451
+ guard, inherited = rails.guard(text)
452
+ skipped = rails.skipped(text)
453
+ for f in fns:
454
+ if f["kind"] == "method" and f["line"] < private_at:
455
+ action = f"{Path(file).stem.removesuffix('_controller')}#{f['name']}"
456
+ open_here = skipped is not None and (not skipped or f["name"] in skipped)
457
+ auth = "" if open_here else (f"before_action :{guard}" + (f" ({inherited})" if inherited else "")
458
+ if guard else "") # fmt: skip
459
+ entries.append(Entry(f["id"], "ANY", action, "Rails", file, f["line"], auth))
460
+ return entries
461
+
462
+
463
+ def exposure(root: Path, files: list[str]) -> tuple[str, str]:
464
+ local = opened = ""
465
+ for file in files:
466
+ if is_test(file): # a test's server on 0.0.0.0 says nothing about the product's
467
+ continue
468
+ try:
469
+ text = (root / file).read_text(encoding="utf-8", errors="replace")
470
+ except OSError:
471
+ continue
472
+ if not local and (m := LOCAL.search(text)):
473
+ local = f"{file}: {m.group(0)}"
474
+ if not opened and (m := OPEN.search(text)):
475
+ opened = f"{file}: {m.group(0)}"
476
+ if local and opened:
477
+ return "configurable", f"{local}; {opened}"
478
+ if local:
479
+ return "local", local
480
+ if opened:
481
+ return "open", opened
482
+ return "unknown", ""
483
+
484
+
485
+ def surface(root: Path, g: dict, v: View) -> Surface:
486
+ entries = find_entries(root, g, v)
487
+ s = Surface(entries=entries)
488
+ s.exposure, s.exposure_evidence = exposure(root, [f["id"] for f in g["files"] if not f["id"].startswith(("test", "tests/"))])
489
+ out_edges: dict[str, list[str]] = {}
490
+ for e in g["edges"]:
491
+ if e["kind"] in ("call", "ref"):
492
+ out_edges.setdefault(e["src"], []).append(e["dst"])
493
+ parent: dict[str, str | None] = {}
494
+ origin: dict[str, int] = {}
495
+ q: deque[str] = deque()
496
+ for i, e in enumerate(entries):
497
+ if e.fn not in origin:
498
+ origin[e.fn], parent[e.fn] = i, None
499
+ q.append(e.fn)
500
+ while q:
501
+ cur = q.popleft()
502
+ for nxt in out_edges.get(cur, ()):
503
+ if nxt not in origin:
504
+ origin[nxt], parent[nxt] = origin[cur], cur
505
+ q.append(nxt)
506
+ for fid in origin:
507
+ path, cur = [], fid
508
+ while cur is not None:
509
+ path.append(cur)
510
+ cur = parent[cur]
511
+ s.reach[fid] = (origin[fid], list(reversed(path)))
512
+ return s
513
+
514
+
515
+ def function_at(v: View, file: str, line: int) -> str | None:
516
+ """The innermost function holding a line (a sink's owner), else the file's top-level code."""
517
+ best = None
518
+ for f in v.fns_in.get(file, []):
519
+ if f["line"] <= line <= f["end"] and (best is None or f["line"] >= best["line"]):
520
+ best = f
521
+ return best["id"] if best else (f"{file}::<module>" if f"{file}::<module>" in v.fn else None)
522
+
523
+
524
+ def writes(v: View) -> set[str]:
525
+ """Functions that visibly change something themselves: a database write (INSERT/UPDATE/DELETE, commit, save…), a
526
+ file write, or a program run. An `execute` whose SQL can't be seen doesn't count (it may well be a read), and
527
+ neither does a bare commit."""
528
+ out = set()
529
+ for fid, f in v.fn.items():
530
+ if "migrat" in f["name"].lower() or "migration" in f["file"].lower():
531
+ continue # schema setup runs on every open: not a change a request makes
532
+ for io in f.get("io", []):
533
+ kind = kind_of(io)
534
+ if kind == "process" or (kind in ("write", "file") and (CHANGES.search(io) or WRITE_CALL.search(io))):
535
+ out.add(fid)
536
+ break
537
+ return out