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.
- codefactory/__init__.py +3 -0
- codefactory/__main__.py +5 -0
- codefactory/accept.py +68 -0
- codefactory/analyzers/__init__.py +55 -0
- codefactory/analyzers/generic.py +392 -0
- codefactory/analyzers/parallel.py +113 -0
- codefactory/analyzers/python.py +279 -0
- codefactory/analyzers/python_parse.py +402 -0
- codefactory/analyzers/treewalk.py +299 -0
- codefactory/analyzers/ts_helper.js +483 -0
- codefactory/analyzers/typescript.py +118 -0
- codefactory/apple.py +80 -0
- codefactory/audit.py +227 -0
- codefactory/baseline.py +58 -0
- codefactory/brief.py +330 -0
- codefactory/cache.py +93 -0
- codefactory/checks.py +608 -0
- codefactory/cli.py +782 -0
- codefactory/config.py +157 -0
- codefactory/coverage.py +104 -0
- codefactory/deps.py +182 -0
- codefactory/diff.py +197 -0
- codefactory/efficiency.py +250 -0
- codefactory/flags.py +263 -0
- codefactory/graph.py +95 -0
- codefactory/hotspots.py +344 -0
- codefactory/infra.py +242 -0
- codefactory/intent.py +106 -0
- codefactory/layers.py +143 -0
- codefactory/org.py +131 -0
- codefactory/owners.py +72 -0
- codefactory/patch.py +81 -0
- codefactory/paths.py +93 -0
- codefactory/plan.py +476 -0
- codefactory/privacy.py +221 -0
- codefactory/profile.py +667 -0
- codefactory/rerank.py +161 -0
- codefactory/review.py +1504 -0
- codefactory/rules.py +50 -0
- codefactory/sarif.py +661 -0
- codefactory/sbom.py +78 -0
- codefactory/security.py +537 -0
- codefactory/similar.py +199 -0
- codefactory/skill.py +144 -0
- codefactory/skill_template/SKILL.md +68 -0
- codefactory/skill_template/__init__.py +0 -0
- codefactory/sqlgraph.py +109 -0
- codefactory/suppress.py +92 -0
- codefactory/taint.py +439 -0
- codefactory/trace.py +72 -0
- codefactory/viewer/__init__.py +19 -0
- codefactory/viewer/dashboard.html +43 -0
- codefactory/viewer/factory.css +61 -0
- codefactory/viewer/factory.js +665 -0
- codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1.dist-info/METADATA +250 -0
- codefactory_cli-0.20.1.dist-info/RECORD +61 -0
- codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
- codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
- codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/taint.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Data flow (taint) for Python: does a value from a network request reach a dangerous call, and through which
|
|
2
|
+
variables?
|
|
3
|
+
|
|
4
|
+
Per function, the analysis finds which parameters (and which sources inside it) reach a sink, and which reach the
|
|
5
|
+
return value. Those summaries are combined across the call graph to a fixed point, so a request parameter handed to a
|
|
6
|
+
helper that builds SQL is followed into the helper. A value passed through a sanitizer (int(), uuid.UUID(),
|
|
7
|
+
shlex.quote, secure_filename, html.escape…) stops being tainted; SQL with bound parameters is never a sink, because
|
|
8
|
+
its query text is a constant.
|
|
9
|
+
|
|
10
|
+
Within a function it's flow-insensitive (a variable tainted anywhere is tainted everywhere) and an unknown call with
|
|
11
|
+
a tainted argument returns a tainted value: generous on purpose, because the sinks are specific.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import re
|
|
18
|
+
from collections import deque
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from .graph import Flag, Graph
|
|
23
|
+
|
|
24
|
+
ROUTE_ATTRS = {"get", "post", "put", "patch", "delete", "route", "api_route", "websocket"}
|
|
25
|
+
REQUEST_ATTRS = {"args", "form", "values", "json", "data", "files", "cookies", "headers", "query_params", "path_params",
|
|
26
|
+
"GET", "POST", "body", "FILES", "COOKIES", "META", "get_json", "query_string"} # fmt: skip
|
|
27
|
+
SANITIZERS = {"int", "float", "bool", "len", "abs", "round", "UUID", "uuid4", "basename", "secure_filename", "quote",
|
|
28
|
+
"escape", "clean", "quote_plus", "urlencode", "isdigit", "isalnum", "hexdigest", "count"} # fmt: skip
|
|
29
|
+
SQL = {"execute", "executemany", "executescript", "raw", "text", "extra"}
|
|
30
|
+
SHELL = {"system", "popen", "getoutput", "getstatusoutput"}
|
|
31
|
+
SUBPROCESS = {"run", "call", "check_call", "check_output", "Popen"}
|
|
32
|
+
CODE = {"eval", "exec", "loads", "load", "compile"} # loads/load: pickle, marshal, yaml (unsafe loader)
|
|
33
|
+
PATHS = {"open", "send_file", "remove", "unlink", "rmtree", "FileResponse", "read_text", "write_text", "read_bytes"}
|
|
34
|
+
NETWORK = {"get", "post", "put", "delete", "patch", "request", "urlopen", "head"}
|
|
35
|
+
# not `session`: in SQLAlchemy / SQLModel code that's the database (`session.delete(user)`, `session.get(User, id)`)
|
|
36
|
+
NETWORK_MODULES = {"requests", "httpx", "urllib", "aiohttp", "client", "http", "http_session", "http_client"}
|
|
37
|
+
REDIRECT = {"redirect", "RedirectResponse", "HttpResponseRedirect"}
|
|
38
|
+
TEMPLATE = {"render_template_string", "Markup", "mark_safe", "Template"}
|
|
39
|
+
DB_RESULTS = {"fetchone", "fetchall", "fetchmany", "first", "one", "one_or_none", "scalar", "scalars", "all", "get_or_404"}
|
|
40
|
+
# A request parameter declared with one of these types is converted and validated before the handler runs (FastAPI,
|
|
41
|
+
# Django path converters): it can't carry attacker text.
|
|
42
|
+
SAFE_TYPES = {"int", "float", "bool", "UUID", "date", "datetime", "time", "Decimal", "conint", "confloat", "PositiveInt",
|
|
43
|
+
"NonNegativeInt", "Literal"} # fmt: skip
|
|
44
|
+
# request *data*, not any mention of "request" (urllib.request, request objects passed around in an HTTP library)
|
|
45
|
+
SOURCE_HINT = re.compile(
|
|
46
|
+
r"\b(?:request|req)\.(?:args|form|values|json|data|files|cookies|headers|query_params|path_params|GET|POST|body|"
|
|
47
|
+
r"FILES|COOKIES|META|get_json|query_string)\b|@\w+\.(?:get|post|put|patch|delete|route|api_route)\("
|
|
48
|
+
)
|
|
49
|
+
SINK_HINT = re.compile(
|
|
50
|
+
r"execute|system|popen|subprocess|eval\(|exec\(|pickle|yaml|open\(|send_file|FileResponse|"
|
|
51
|
+
r"unlink|remove\(|rmtree|requests\.|httpx|urlopen|redirect|Redirect|render_template_string|Markup|mark_safe"
|
|
52
|
+
)
|
|
53
|
+
KIND_TEXT = {"sql": "SQL query", "shell": "shell command", "code": "code execution", "path": "file path",
|
|
54
|
+
"ssrf": "outgoing request URL", "redirect": "redirect target", "template": "template / HTML"} # fmt: skip
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Summary:
|
|
59
|
+
params: list[str]
|
|
60
|
+
sinks: dict[int, list[tuple]] = field(default_factory=dict) # param index -> [(kind, line, call, via, sink fn id)]
|
|
61
|
+
returns: set[int] = field(default_factory=set) # params that reach the return value
|
|
62
|
+
source_sinks: list[tuple] = field(default_factory=list) # (source text, kind, line, call, via, sink fn id)
|
|
63
|
+
source_returns: str = "" # a source the function returns, if any
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _name(func: ast.AST) -> str:
|
|
67
|
+
return func.attr if isinstance(func, ast.Attribute) else func.id if isinstance(func, ast.Name) else ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _root(node: ast.AST) -> str:
|
|
71
|
+
while isinstance(node, (ast.Attribute, ast.Subscript, ast.Call)):
|
|
72
|
+
node = node.func if isinstance(node, ast.Call) else node.value
|
|
73
|
+
return node.id if isinstance(node, ast.Name) else ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _source(node: ast.AST) -> str:
|
|
77
|
+
"""`request.args["q"]`, `request.json`: the text of a source expression, or "". Only network requests count:
|
|
78
|
+
`sys.argv` and `input()` come from whoever runs the program, who already has its rights (a CLI opening the file
|
|
79
|
+
it's given, a debugger running what's typed, are features)."""
|
|
80
|
+
cur = node
|
|
81
|
+
while isinstance(cur, (ast.Subscript, ast.Call, ast.Attribute)):
|
|
82
|
+
if isinstance(cur, ast.Attribute) and cur.attr in REQUEST_ATTRS and _root(cur) in ("request", "req", "self"):
|
|
83
|
+
return ast.unparse(node)[:60]
|
|
84
|
+
cur = cur.func if isinstance(cur, ast.Call) else cur.value
|
|
85
|
+
return ""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _sink(call: ast.Call) -> tuple[str, list[ast.AST]] | None:
|
|
89
|
+
"""(kind, the arguments that matter) when this call is a sink."""
|
|
90
|
+
name, f = _name(call.func), call.func
|
|
91
|
+
root = _root(f) if isinstance(f, ast.Attribute) else ""
|
|
92
|
+
args = list(call.args)
|
|
93
|
+
if name in SQL and isinstance(f, ast.Attribute) and args:
|
|
94
|
+
return "sql", args[:1]
|
|
95
|
+
if name in SHELL and root == "os" and args:
|
|
96
|
+
return "shell", args[:1]
|
|
97
|
+
if name in SUBPROCESS and root == "subprocess" and args:
|
|
98
|
+
shell = any(k.arg == "shell" and isinstance(k.value, ast.Constant) and k.value.value for k in call.keywords)
|
|
99
|
+
first = args[0]
|
|
100
|
+
if shell or isinstance(first, (ast.JoinedStr, ast.BinOp)):
|
|
101
|
+
return "shell", args[:1]
|
|
102
|
+
if name in ("eval", "exec") and isinstance(f, ast.Name) and args:
|
|
103
|
+
return "code", args[:1]
|
|
104
|
+
if name in ("loads", "load") and root in ("pickle", "marshal", "dill", "shelve") and args:
|
|
105
|
+
return "code", args[:1]
|
|
106
|
+
if name == "load" and root == "yaml" and args and not any(k.arg == "Loader" for k in call.keywords):
|
|
107
|
+
return "code", args[:1]
|
|
108
|
+
if name in PATHS and (isinstance(f, ast.Name) or root in ("os", "shutil", "Path", "pathlib")) and args:
|
|
109
|
+
return "path", args[:1]
|
|
110
|
+
if name in NETWORK and root in NETWORK_MODULES and args:
|
|
111
|
+
return "ssrf", args[:1]
|
|
112
|
+
if name == "urlopen" and args:
|
|
113
|
+
return "ssrf", args[:1]
|
|
114
|
+
if name in REDIRECT and args:
|
|
115
|
+
return "redirect", args[:1]
|
|
116
|
+
if name in TEMPLATE and args:
|
|
117
|
+
return "template", args[:1]
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
VALIDATOR = re.compile(r"allow|safe|valid|whitelist|allowlist|trusted|permitted|has_allowed_host", re.I)
|
|
122
|
+
LOCAL_URL = {"reverse", "reverse_lazy", "url_for", "resolve_url", "url_path_for"}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _guards(func) -> dict[int, set[str]]:
|
|
126
|
+
"""For each call, the names an enclosing `if` checked with a validator: `if x and _allow_redirect(x): call(x)`."""
|
|
127
|
+
out: dict[int, set[str]] = {}
|
|
128
|
+
|
|
129
|
+
def visit(node, checked: frozenset):
|
|
130
|
+
if isinstance(node, ast.If):
|
|
131
|
+
names = {
|
|
132
|
+
a.id
|
|
133
|
+
for c in ast.walk(node.test)
|
|
134
|
+
if isinstance(c, ast.Call) and VALIDATOR.search(_name(c.func))
|
|
135
|
+
for a in c.args
|
|
136
|
+
if isinstance(a, ast.Name)
|
|
137
|
+
}
|
|
138
|
+
for child in node.body:
|
|
139
|
+
visit(child, checked | names)
|
|
140
|
+
for child in node.orelse:
|
|
141
|
+
visit(child, checked)
|
|
142
|
+
return
|
|
143
|
+
if isinstance(node, ast.Call):
|
|
144
|
+
out[id(node)] = set(checked)
|
|
145
|
+
for child in ast.iter_child_nodes(node):
|
|
146
|
+
visit(child, checked)
|
|
147
|
+
|
|
148
|
+
visit(func, frozenset())
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _local_url(expr: ast.AST, body: list) -> bool:
|
|
153
|
+
"""The expression is a path this app builds: reverse()/url_for(), "/x" (not "//x"), or a name only ever assigned
|
|
154
|
+
one of those (later `url += "?…"` keeps the prefix)."""
|
|
155
|
+
|
|
156
|
+
def local(e) -> bool:
|
|
157
|
+
if isinstance(e, ast.Call) and _name(e.func) in LOCAL_URL:
|
|
158
|
+
return True
|
|
159
|
+
if isinstance(e, ast.Constant) and isinstance(e.value, str):
|
|
160
|
+
return e.value.startswith("/") and not e.value.startswith("//")
|
|
161
|
+
if isinstance(e, ast.JoinedStr) and e.values and isinstance(e.values[0], ast.Constant):
|
|
162
|
+
return local(e.values[0])
|
|
163
|
+
if isinstance(e, ast.BinOp) and isinstance(e.op, ast.Add):
|
|
164
|
+
return local(e.left)
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
if local(expr):
|
|
168
|
+
return True
|
|
169
|
+
if isinstance(expr, ast.Name):
|
|
170
|
+
values = [n.value for n in body if isinstance(n, ast.Assign)
|
|
171
|
+
and any(isinstance(t, ast.Name) and t.id == expr.id for t in n.targets)] # fmt: skip
|
|
172
|
+
return bool(values) and all(local(v) for v in values)
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _Function:
|
|
177
|
+
"""Taint inside one function, given which parameters are tainted and the callees' summaries."""
|
|
178
|
+
|
|
179
|
+
def __init__(self, node, callees: dict[str, Summary], fid: str = ""):
|
|
180
|
+
self.node, self.callees, self.fid = node, callees, fid
|
|
181
|
+
self.params = [a.arg for a in node.args.posonlyargs + node.args.args + node.args.kwonlyargs]
|
|
182
|
+
|
|
183
|
+
def origins(self, expr: ast.AST, env: dict[str, set]) -> set:
|
|
184
|
+
"""The taint labels an expression carries: ("param", i) or ("source", text)."""
|
|
185
|
+
if isinstance(expr, ast.Name):
|
|
186
|
+
return set(env.get(expr.id, ()))
|
|
187
|
+
if src := _source(expr):
|
|
188
|
+
return {("source", src)}
|
|
189
|
+
if isinstance(expr, ast.Call):
|
|
190
|
+
name = _name(expr.func)
|
|
191
|
+
if name in SANITIZERS or name in SQL or name in DB_RESULTS:
|
|
192
|
+
return set() # converted, or read back from a database (second-order injection is out of scope)
|
|
193
|
+
out = set()
|
|
194
|
+
summary = self.callees.get(name)
|
|
195
|
+
parts = list(expr.args) + [k.value for k in expr.keywords]
|
|
196
|
+
if summary is not None:
|
|
197
|
+
for i, a in enumerate(expr.args):
|
|
198
|
+
if i in summary.returns:
|
|
199
|
+
out |= self.origins(a, env)
|
|
200
|
+
if summary.source_returns:
|
|
201
|
+
out.add(("source", summary.source_returns))
|
|
202
|
+
return out
|
|
203
|
+
for a in parts: # an unknown call: what goes in comes out (str(x), x.strip(), "".join(xs)…)
|
|
204
|
+
out |= self.origins(a, env)
|
|
205
|
+
if isinstance(expr.func, ast.Attribute):
|
|
206
|
+
out |= self.origins(expr.func.value, env)
|
|
207
|
+
return out
|
|
208
|
+
if isinstance(expr, ast.Compare):
|
|
209
|
+
return set() # a comparison is a yes/no: it carries no attacker text
|
|
210
|
+
out = set()
|
|
211
|
+
for child in ast.iter_child_nodes(expr):
|
|
212
|
+
if isinstance(child, ast.expr):
|
|
213
|
+
out |= self.origins(child, env)
|
|
214
|
+
return out
|
|
215
|
+
|
|
216
|
+
def run(self, tainted_params: set[int]) -> tuple[dict, list, set]:
|
|
217
|
+
env: dict[str, set] = {p: {("param", i)} for i, p in enumerate(self.params) if i in tainted_params}
|
|
218
|
+
body = _body(self.node)
|
|
219
|
+
for _ in range(4): # assignments to a fixed point (flow-insensitive)
|
|
220
|
+
changed = False
|
|
221
|
+
for n in body:
|
|
222
|
+
targets, value = [], None
|
|
223
|
+
if isinstance(n, ast.Assign):
|
|
224
|
+
targets, value = n.targets, n.value
|
|
225
|
+
elif isinstance(n, (ast.AnnAssign, ast.AugAssign)) and n.value is not None:
|
|
226
|
+
targets, value = [n.target], n.value
|
|
227
|
+
elif isinstance(n, (ast.For, ast.AsyncFor)):
|
|
228
|
+
targets, value = [n.target], n.iter
|
|
229
|
+
elif isinstance(n, ast.withitem) and n.optional_vars is not None:
|
|
230
|
+
targets, value = [n.optional_vars], n.context_expr
|
|
231
|
+
if value is None:
|
|
232
|
+
continue
|
|
233
|
+
labels = self.origins(value, env)
|
|
234
|
+
if not labels:
|
|
235
|
+
continue
|
|
236
|
+
for t in targets:
|
|
237
|
+
for name in (x.id for x in ast.walk(t) if isinstance(x, ast.Name)):
|
|
238
|
+
if not labels <= env.get(name, set()):
|
|
239
|
+
env[name] = env.get(name, set()) | labels
|
|
240
|
+
changed = True
|
|
241
|
+
if not changed:
|
|
242
|
+
break
|
|
243
|
+
hits, calls, returns = [], [], set()
|
|
244
|
+
guards = _guards(self.node)
|
|
245
|
+
for n in body:
|
|
246
|
+
if isinstance(n, ast.Call):
|
|
247
|
+
sink = _sink(n)
|
|
248
|
+
if sink:
|
|
249
|
+
kind, args = sink
|
|
250
|
+
for a in args:
|
|
251
|
+
if isinstance(a, ast.Constant):
|
|
252
|
+
continue # a constant query or command: bound parameters, nothing to inject
|
|
253
|
+
if isinstance(a, ast.Name) and a.id in guards.get(id(n), ()):
|
|
254
|
+
continue # inside `if is_safe(x):` / `if _allow_redirect(x):`: checked first
|
|
255
|
+
if kind == "redirect" and _local_url(a, body):
|
|
256
|
+
continue # a path this app builds (reverse(), url_for(), "/…"): a query string can't leave it
|
|
257
|
+
for label in self.origins(a, env):
|
|
258
|
+
hits.append((label, kind, n.lineno, ast.unparse(n.func)[:50], "", self.fid))
|
|
259
|
+
summary = self.callees.get(_name(n.func))
|
|
260
|
+
if summary is not None:
|
|
261
|
+
for i, a in enumerate(n.args):
|
|
262
|
+
for flow in summary.sinks.get(i, []):
|
|
263
|
+
for label in self.origins(a, env):
|
|
264
|
+
via = f"{_name(n.func)}({summary.params[i] if i < len(summary.params) else '…'})"
|
|
265
|
+
hits.append(
|
|
266
|
+
(label, flow[0], flow[1], flow[2], via + (" → " + flow[3] if flow[3] else ""), flow[4])
|
|
267
|
+
)
|
|
268
|
+
calls.append(n)
|
|
269
|
+
if isinstance(n, ast.Return) and n.value is not None:
|
|
270
|
+
returns |= self.origins(n.value, env)
|
|
271
|
+
return hits, calls, returns
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _closure(start: set[str], edges: dict[str, list[str]], keep: dict) -> set[str]:
|
|
275
|
+
seen, stack = set(start), list(start)
|
|
276
|
+
while stack:
|
|
277
|
+
for nxt in edges.get(stack.pop(), ()):
|
|
278
|
+
if nxt in keep and nxt not in seen:
|
|
279
|
+
seen.add(nxt)
|
|
280
|
+
stack.append(nxt)
|
|
281
|
+
return seen
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _body(node) -> list[ast.AST]:
|
|
285
|
+
"""Every node inside a function (cached on it: the worklist revisits functions)."""
|
|
286
|
+
cached = getattr(node, "_cf_body", None)
|
|
287
|
+
if cached is None:
|
|
288
|
+
cached = [n for n in ast.walk(node) if n is not node]
|
|
289
|
+
node._cf_body = cached
|
|
290
|
+
return cached
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def summarize(node, callees: dict[str, Summary], fid: str = "") -> Summary:
|
|
294
|
+
f = _Function(node, callees, fid)
|
|
295
|
+
s = Summary(f.params)
|
|
296
|
+
hits, _, returns = f.run(set(range(len(f.params))))
|
|
297
|
+
for label, kind, line, text, via, where in hits:
|
|
298
|
+
if label[0] == "param":
|
|
299
|
+
s.sinks.setdefault(label[1], []).append((kind, line, text, via, where))
|
|
300
|
+
else:
|
|
301
|
+
s.source_sinks.append((label[1], kind, line, text, via, where))
|
|
302
|
+
s.returns = {lab[1] for lab in returns if lab[0] == "param"}
|
|
303
|
+
s.source_returns = next((lab[1] for lab in returns if lab[0] == "source"), "")
|
|
304
|
+
return s
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _entry(node, source: str) -> str:
|
|
308
|
+
"""`GET /search` when the function is a route handler (FastAPI, Flask), else ""."""
|
|
309
|
+
for d in node.decorator_list:
|
|
310
|
+
if isinstance(d, ast.Call) and isinstance(d.func, ast.Attribute) and d.func.attr in ROUTE_ATTRS:
|
|
311
|
+
path = d.args[0].value if d.args and isinstance(d.args[0], ast.Constant) else ""
|
|
312
|
+
verb = d.func.attr.upper() if d.func.attr not in ("route", "api_route") else "ROUTE"
|
|
313
|
+
return f"{verb} {path}".strip()
|
|
314
|
+
return ""
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def taint_flags(g: Graph, root: Path) -> list[Flag]:
|
|
318
|
+
"""Proven flows from request data (or another source) to a sink, one finding per sink line."""
|
|
319
|
+
fns = [f for f in g.functions if f.file.endswith(".py") and f.kind != "module"]
|
|
320
|
+
if not fns:
|
|
321
|
+
return []
|
|
322
|
+
callees_of: dict[str, list[str]] = {}
|
|
323
|
+
for e in g.edges:
|
|
324
|
+
if e.kind == "call":
|
|
325
|
+
callees_of.setdefault(e.src, []).append(e.dst)
|
|
326
|
+
by_id = {f.id: f for f in fns}
|
|
327
|
+
lines_of: dict[str, list[str]] = {}
|
|
328
|
+
for file in {f.file for f in fns}:
|
|
329
|
+
try:
|
|
330
|
+
lines_of[file] = (root / file).read_text(encoding="utf-8", errors="replace").splitlines()
|
|
331
|
+
except OSError:
|
|
332
|
+
lines_of[file] = []
|
|
333
|
+
text_of = {f.id: "\n".join(lines_of[f.file][max(0, f.line - 4) : f.end]) for f in fns} # (with decorators)
|
|
334
|
+
# Only functions on a path from a source to a sink matter, and both ends show in the text: functions holding a
|
|
335
|
+
# source (a route decorator, request.args and the like) and functions holding a sink. Keep what's reachable from
|
|
336
|
+
# the first and can reach the second, along call edges, before parsing anything: on big codebases this is a few
|
|
337
|
+
# percent of the functions.
|
|
338
|
+
callers_of: dict[str, list[str]] = {}
|
|
339
|
+
for src, dsts in callees_of.items():
|
|
340
|
+
for d in dsts:
|
|
341
|
+
callers_of.setdefault(d, []).append(src)
|
|
342
|
+
sources = {fid for fid, text in text_of.items() if SOURCE_HINT.search(text)}
|
|
343
|
+
sinks = {fid for fid, text in text_of.items() if SINK_HINT.search(text)}
|
|
344
|
+
if not sources or not sinks:
|
|
345
|
+
return []
|
|
346
|
+
forward = _closure(sources, callees_of, by_id)
|
|
347
|
+
backward = _closure(sinks, callers_of, by_id)
|
|
348
|
+
relevant = forward & backward
|
|
349
|
+
relevant |= {c for fid in list(relevant) for c in callees_of.get(fid, ()) if c in sources} # request-data helpers
|
|
350
|
+
if not relevant:
|
|
351
|
+
return []
|
|
352
|
+
nodes: dict[str, ast.AST] = {}
|
|
353
|
+
for file in sorted({by_id[fid].file for fid in relevant}):
|
|
354
|
+
try:
|
|
355
|
+
tree = ast.parse("\n".join(lines_of[file]))
|
|
356
|
+
except (SyntaxError, ValueError):
|
|
357
|
+
continue
|
|
358
|
+
wanted = {(by_id[fid].line, by_id[fid].name): fid for fid in relevant if by_id[fid].file == file}
|
|
359
|
+
for n in ast.walk(tree):
|
|
360
|
+
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and (n.lineno, n.name) in wanted:
|
|
361
|
+
nodes[wanted[(n.lineno, n.name)]] = n
|
|
362
|
+
relevant &= set(nodes)
|
|
363
|
+
summaries: dict[str, Summary] = {}
|
|
364
|
+
work = deque(sorted(relevant, key=lambda f: -len(callees_of.get(f, ())))) # leaves last: callees settle first
|
|
365
|
+
queued, budget = set(work), 8 * len(relevant) + 100
|
|
366
|
+
redone: dict[str, int] = {}
|
|
367
|
+
while work and budget > 0: # a worklist to a fixed point: a function is redone only when a callee changed
|
|
368
|
+
budget -= 1
|
|
369
|
+
fid = work.popleft()
|
|
370
|
+
queued.discard(fid)
|
|
371
|
+
redone[fid] = redone.get(fid, 0) + 1
|
|
372
|
+
if redone[fid] > 6: # recursion and long call cycles: enough rounds to settle what matters
|
|
373
|
+
continue
|
|
374
|
+
callees = {by_id[c].name: summaries[c] for c in callees_of.get(fid, []) if c in summaries}
|
|
375
|
+
s = summarize(nodes[fid], callees, fid)
|
|
376
|
+
old = summaries.get(fid)
|
|
377
|
+
if old is None or (s.sinks, s.returns, s.source_sinks, s.source_returns) != (
|
|
378
|
+
old.sinks,
|
|
379
|
+
old.returns,
|
|
380
|
+
old.source_sinks,
|
|
381
|
+
old.source_returns,
|
|
382
|
+
):
|
|
383
|
+
summaries[fid] = s
|
|
384
|
+
for caller in callers_of.get(fid, ()):
|
|
385
|
+
if caller in relevant and caller not in queued:
|
|
386
|
+
work.append(caller)
|
|
387
|
+
queued.add(caller)
|
|
388
|
+
out, seen = [], set()
|
|
389
|
+
for fid, s in summaries.items():
|
|
390
|
+
node, fn = nodes[fid], by_id[fid]
|
|
391
|
+
route = _entry(node, "")
|
|
392
|
+
flows = list(s.source_sinks)
|
|
393
|
+
if route: # a handler's parameters come from the request (FastAPI path, query and body parameters)
|
|
394
|
+
deps = {a.arg for a, d in _defaults(node) if isinstance(d, ast.Call) and _name(d.func) in ("Depends", "Security")}
|
|
395
|
+
typed = {a.arg for a in node.args.args + node.args.kwonlyargs if _safe_annotation(a.annotation)}
|
|
396
|
+
for i, flows_i in s.sinks.items():
|
|
397
|
+
pname = s.params[i] if i < len(s.params) else "?"
|
|
398
|
+
if (
|
|
399
|
+
pname in deps
|
|
400
|
+
or pname in typed
|
|
401
|
+
or pname in ("self", "cls", "db", "session", "conn", "request", "background_tasks")
|
|
402
|
+
):
|
|
403
|
+
continue
|
|
404
|
+
flows += [(f"parameter `{pname}` of {route}", *flow) for flow in flows_i]
|
|
405
|
+
for src, kind, line, text, via, where in flows:
|
|
406
|
+
key = (kind, where, line)
|
|
407
|
+
if key in seen:
|
|
408
|
+
continue
|
|
409
|
+
seen.add(key)
|
|
410
|
+
chain = f"{src} → {fn.qualname}" + (f" → {via}" if via else "") + f" → {text}()"
|
|
411
|
+
sink_fn = by_id.get(where, fn)
|
|
412
|
+
what = KIND_TEXT[kind]
|
|
413
|
+
article = "an" if what[0] in "aeiou" else "a"
|
|
414
|
+
out.append(Flag("taint", "high", sink_fn.id, f"Request data reaches {article} {what}: {chain}",
|
|
415
|
+
[fid] if fid != sink_fn.id else [], line=line, detail=kind)) # fmt: skip
|
|
416
|
+
return out
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _safe_annotation(ann: ast.AST | None) -> bool:
|
|
420
|
+
"""`int`, `uuid.UUID`, `Annotated[int, Path(...)]`, `Literal["a", "b"]`, an Enum-looking name…"""
|
|
421
|
+
if ann is None:
|
|
422
|
+
return False
|
|
423
|
+
modules = {id(n.value) for n in ast.walk(ann) if isinstance(n, ast.Attribute)} # `uuid` in `uuid.UUID`
|
|
424
|
+
names = {n.id for n in ast.walk(ann) if isinstance(n, ast.Name) and id(n) not in modules} | {
|
|
425
|
+
n.attr for n in ast.walk(ann) if isinstance(n, ast.Attribute)
|
|
426
|
+
}
|
|
427
|
+
names.discard("Annotated")
|
|
428
|
+
names.discard("Optional")
|
|
429
|
+
return bool(names) and (
|
|
430
|
+
names <= SAFE_TYPES | {"None", "Path", "Query"} or any(n.endswith(("Enum", "Kind", "Type")) for n in names)
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _defaults(node) -> list[tuple]:
|
|
435
|
+
a = node.args
|
|
436
|
+
positional = a.posonlyargs + a.args
|
|
437
|
+
pairs = list(zip(positional[len(positional) - len(a.defaults) :], a.defaults, strict=False))
|
|
438
|
+
pairs += [(arg, d) for arg, d in zip(a.kwonlyargs, a.kw_defaults, strict=False) if d is not None]
|
|
439
|
+
return pairs
|
codefactory/trace.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""EXPLAIN for a function: everything it eventually calls, how deep, and how much code that is; and the shortest
|
|
2
|
+
call path from one function to another. Works on the graph dict, so also on a saved graph .json."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections import defaultdict, deque
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _adjacency(graph: dict, kinds=("call",)) -> dict[str, list[str]]:
|
|
10
|
+
adj = defaultdict(list)
|
|
11
|
+
for e in graph["edges"]:
|
|
12
|
+
if e["kind"] in kinds:
|
|
13
|
+
adj[e["src"]].append(e["dst"])
|
|
14
|
+
return adj
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def find_function(graph: dict, query: str) -> list[dict]:
|
|
18
|
+
"""Matches an id ("file::qualname"), a qualname ("Class.method") or a bare name; exact matches first."""
|
|
19
|
+
fns = [f for f in graph["functions"] if f["kind"] != "module"]
|
|
20
|
+
for key in ("id", "qualname", "name"):
|
|
21
|
+
hits = [f for f in fns if f[key] == query]
|
|
22
|
+
if hits:
|
|
23
|
+
return hits
|
|
24
|
+
return [f for f in fns if f["id"].endswith(query)]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def trace(graph: dict, start: str, kinds=("call",)) -> dict:
|
|
28
|
+
"""Breadth-first walk of what `start` calls, directly or not. Each function appears once, at its shortest depth."""
|
|
29
|
+
by_id = {f["id"]: f for f in graph["functions"]}
|
|
30
|
+
adj = _adjacency(graph, kinds)
|
|
31
|
+
depth = {start: 0}
|
|
32
|
+
via: dict[str, str] = {}
|
|
33
|
+
loops: set[str] = set()
|
|
34
|
+
q = deque([start])
|
|
35
|
+
while q:
|
|
36
|
+
cur = q.popleft()
|
|
37
|
+
for nxt in adj[cur]:
|
|
38
|
+
if nxt == start:
|
|
39
|
+
loops.add(cur) # something it calls calls it back
|
|
40
|
+
if nxt not in depth:
|
|
41
|
+
depth[nxt] = depth[cur] + 1
|
|
42
|
+
via[nxt] = cur
|
|
43
|
+
q.append(nxt)
|
|
44
|
+
reached = [by_id[i] | {"depth": d, "via": via.get(i)} for i, d in depth.items() if i != start and i in by_id]
|
|
45
|
+
reached.sort(key=lambda f: (f["depth"], f["file"], f["line"]))
|
|
46
|
+
return {
|
|
47
|
+
"start": start,
|
|
48
|
+
"functions": reached,
|
|
49
|
+
"files": sorted({f["file"] for f in reached}),
|
|
50
|
+
"depth": max((f["depth"] for f in reached), default=0),
|
|
51
|
+
"loc": sum(f["loc"] for f in reached),
|
|
52
|
+
"calls_back": sorted(loops),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def shortest_path(graph: dict, src: str, dst: str, kinds=("call",)) -> list[str] | None:
|
|
57
|
+
adj = _adjacency(graph, kinds)
|
|
58
|
+
prev = {src: None}
|
|
59
|
+
q = deque([src])
|
|
60
|
+
while q:
|
|
61
|
+
cur = q.popleft()
|
|
62
|
+
if cur == dst:
|
|
63
|
+
path = []
|
|
64
|
+
while cur is not None:
|
|
65
|
+
path.append(cur)
|
|
66
|
+
cur = prev[cur]
|
|
67
|
+
return path[::-1]
|
|
68
|
+
for nxt in adj[cur]:
|
|
69
|
+
if nxt not in prev:
|
|
70
|
+
prev[nxt] = cur
|
|
71
|
+
q.append(nxt)
|
|
72
|
+
return None
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Renders a graph into one self-contained HTML file (no server, no network) that opens in any browser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
|
|
9
|
+
_HERE = files(__package__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def render_html(graph: dict) -> str:
|
|
13
|
+
template = (_HERE / "template.html").read_text(encoding="utf-8")
|
|
14
|
+
css = (_HERE / "factory.css").read_text(encoding="utf-8")
|
|
15
|
+
js = (_HERE / "factory.js").read_text(encoding="utf-8")
|
|
16
|
+
# "</" can't appear inside a <script> block: escape it so code text in the data can't end the script early.
|
|
17
|
+
data = json.dumps(graph, separators=(",", ":")).replace("</", "<\\/")
|
|
18
|
+
title = html.escape(graph.get("root", "").replace("\\", "/").rstrip("/").split("/")[-1] or "codebase")
|
|
19
|
+
return template.replace("__TITLE__", title).replace("/*CSS*/", css).replace("/*JS*/", js).replace("__DATA__", data)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
6
|
+
<title>codefactory dashboard</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root { --bg: #fff; --fg: #1d1d1f; --muted: #6e6e73; --line: #e5e5ea;
|
|
9
|
+
--crit: #b3261e; --high: #d9480f; --med: #b8860b; --low: #5f6b7a; --good: #2e7d32; }
|
|
10
|
+
@media (prefers-color-scheme: dark) {
|
|
11
|
+
:root { --bg: #111214; --fg: #f2f2f7; --muted: #a1a1aa; --line: #2c2c2e; --good: #66bb6a; --med: #e0b100; }
|
|
12
|
+
}
|
|
13
|
+
body { margin: 0; padding: 24px 16px; background: var(--bg); color: var(--fg);
|
|
14
|
+
font: 14px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif; }
|
|
15
|
+
h1 { font-size: 20px; margin: 0 0 4px; }
|
|
16
|
+
h2 { font-size: 16px; margin: 24px 0 0; }
|
|
17
|
+
.muted { color: var(--muted); font-size: 12px; }
|
|
18
|
+
.wrap { overflow-x: auto; }
|
|
19
|
+
table { border-collapse: collapse; width: 100%; margin: 12px 0; }
|
|
20
|
+
th, td { border-bottom: 1px solid var(--line); padding: 8px; text-align: left; vertical-align: top; }
|
|
21
|
+
th { font-size: 12px; color: var(--muted); font-weight: 600; }
|
|
22
|
+
.num { text-align: right; font-variant-numeric: tabular-nums; }
|
|
23
|
+
.top { font-size: 12px; max-width: 360px; }
|
|
24
|
+
.sev-critical, .grade-at-risk { color: var(--crit); font-weight: 600; }
|
|
25
|
+
.sev-high, .grade-fragile { color: var(--high); font-weight: 600; }
|
|
26
|
+
.sev-medium, .grade-adequate { color: var(--med); }
|
|
27
|
+
.sev-low { color: var(--low); }
|
|
28
|
+
.grade-strong { color: var(--good); font-weight: 600; }
|
|
29
|
+
</style>
|
|
30
|
+
</head>
|
|
31
|
+
<body>
|
|
32
|
+
<h1>codefactory dashboard</h1>
|
|
33
|
+
<div class="muted">__SUMMARY__</div>
|
|
34
|
+
<div class="wrap"><table>
|
|
35
|
+
<thead><tr><th>Repository</th><th>Health</th><th class="num">Critical</th><th class="num">High</th>
|
|
36
|
+
<th class="num">Medium</th><th class="num">Low</th><th class="num">Endpoints</th><th class="num">Tests reach</th>
|
|
37
|
+
<th>Trend</th><th>Top findings</th></tr></thead>
|
|
38
|
+
<tbody>
|
|
39
|
+
__ROWS__
|
|
40
|
+
</tbody></table></div>
|
|
41
|
+
__OWNERS__
|
|
42
|
+
</body>
|
|
43
|
+
</html>
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
:root {
|
|
2
|
+
--floor: #eef0ea; --grid: #d6dad0; --panel: #fbfbf8; --ink: #22262b; --muted: #646b73; --line: #d5d8d0;
|
|
3
|
+
--machine: #ffffff; --machine-edge: #8b929a; --belt: #6f7d8c; --belt-dot: #2b3a4a; --back: #c2660a;
|
|
4
|
+
--high: #c62828; --warn: #c98a00; --info: #4f6d8f; --accent: #2a6f97; --idle: #b9bdb6; --sel: #2a6f97;
|
|
5
|
+
--dup: #8a4fd0; --slow: #d2452f; --size: #2f74c0;
|
|
6
|
+
--mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", Consolas, monospace;
|
|
7
|
+
--sans: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
8
|
+
}
|
|
9
|
+
@media (prefers-color-scheme: dark) { :root {
|
|
10
|
+
--floor: #16191d; --grid: #23282e; --panel: #1c2025; --ink: #e2e6ea; --muted: #959ca5; --line: #2e343b;
|
|
11
|
+
--machine: #252a31; --machine-edge: #6b747e; --belt: #5d6b79; --belt-dot: #c9d6e2; --back: #f0973d;
|
|
12
|
+
--high: #ef6b62; --warn: #e8b84a; --info: #8fb0d3; --accent: #6fb3d9; --idle: #3a3f45; --sel: #6fb3d9;
|
|
13
|
+
--dup: #b78cf0; --slow: #f07a5e; --size: #6aa6e8;
|
|
14
|
+
color-scheme: dark; } }
|
|
15
|
+
* { box-sizing: border-box; }
|
|
16
|
+
html, body { height: 100%; margin: 0; }
|
|
17
|
+
body { background: var(--floor); color: var(--ink); font: 13px/1.45 var(--sans); display: flex; overflow: hidden; }
|
|
18
|
+
#stage { flex: 1; position: relative; min-width: 0; }
|
|
19
|
+
canvas { display: block; width: 100%; height: 100%; cursor: grab; }
|
|
20
|
+
canvas.drag { cursor: grabbing; }
|
|
21
|
+
#hud { position: absolute; top: 12px; left: 12px; display: flex; gap: 6px; flex-wrap: wrap; }
|
|
22
|
+
#hud button, #hud input, #hud select { font: inherit; background: var(--panel); color: var(--ink); border: 1px solid var(--line);
|
|
23
|
+
border-radius: 6px; padding: 6px 10px; }
|
|
24
|
+
#hud button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
|
|
25
|
+
#hud input { width: 180px; }
|
|
26
|
+
#tip { position: absolute; pointer-events: none; background: var(--panel); border: 1px solid var(--line);
|
|
27
|
+
border-radius: 6px; padding: 6px 8px; font: 12px/1.35 var(--mono); display: none; max-width: 360px; }
|
|
28
|
+
#legend { position: absolute; bottom: 12px; left: 12px; background: var(--panel); border: 1px solid var(--line);
|
|
29
|
+
border-radius: 6px; padding: 8px 10px; font-size: 12px; color: var(--muted); display: flex; gap: 14px; flex-wrap: wrap; }
|
|
30
|
+
#legend i { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 5px; vertical-align: -1px; }
|
|
31
|
+
aside { width: 360px; max-width: 45vw; background: var(--panel); border-left: 1px solid var(--line); display: flex;
|
|
32
|
+
flex-direction: column; min-height: 0; }
|
|
33
|
+
aside header { padding: 14px 16px 10px; border-bottom: 1px solid var(--line); }
|
|
34
|
+
aside h1 { font-size: 15px; margin: 0 0 4px; }
|
|
35
|
+
aside .sub { color: var(--muted); font: 12px var(--mono); word-break: break-all; }
|
|
36
|
+
.tabs { display: flex; gap: 4px; padding: 8px 12px 0; }
|
|
37
|
+
.tabs button { font: inherit; background: none; border: 0; border-bottom: 2px solid transparent; color: var(--muted);
|
|
38
|
+
padding: 6px 8px; cursor: pointer; }
|
|
39
|
+
.tabs button[aria-selected="true"] { color: var(--ink); border-color: var(--accent); }
|
|
40
|
+
.pane { overflow: auto; padding: 10px 16px 24px; flex: 1; min-height: 0; }
|
|
41
|
+
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 10px; }
|
|
42
|
+
.chip { font: 12px var(--sans); border: 1px solid var(--line); border-radius: 999px; padding: 3px 9px; cursor: pointer;
|
|
43
|
+
background: none; color: var(--ink); }
|
|
44
|
+
.chip[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
|
|
45
|
+
.flag { border-left: 3px solid var(--info); padding: 6px 8px; margin: 6px 0; cursor: pointer; border-radius: 0 4px 4px 0; }
|
|
46
|
+
.flag:hover { background: color-mix(in srgb, var(--accent) 8%, transparent); }
|
|
47
|
+
.flag.high { border-color: var(--high); } .flag.warn { border-color: var(--warn); }
|
|
48
|
+
.flag b { font-weight: 600; } .flag .where { color: var(--muted); font: 11.5px var(--mono); word-break: break-all; }
|
|
49
|
+
table { width: 100%; border-collapse: collapse; font-size: 12px; margin-top: 6px; }
|
|
50
|
+
th, td { text-align: left; padding: 4px 6px; border-bottom: 1px solid var(--line); vertical-align: top; }
|
|
51
|
+
th { color: var(--muted); font-weight: 500; }
|
|
52
|
+
td.n { text-align: right; font-variant-numeric: tabular-nums; }
|
|
53
|
+
h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 16px 0 4px; }
|
|
54
|
+
.link { color: var(--accent); cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
|
|
55
|
+
.empty { color: var(--muted); }
|
|
56
|
+
button:focus-visible, input:focus-visible, .flag:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
57
|
+
.fixbtn { display: block; width: fit-content; margin-top: 6px; font: 11.5px var(--sans); padding: 3px 9px; border-radius: 999px;
|
|
58
|
+
border: 1px solid var(--accent); color: var(--accent); background: none; cursor: pointer; }
|
|
59
|
+
.fixbtn:hover { background: color-mix(in srgb, var(--accent) 10%, transparent); }
|
|
60
|
+
#toast { position: absolute; bottom: 64px; left: 50%; transform: translateX(-50%); background: var(--ink); color: var(--panel);
|
|
61
|
+
padding: 8px 14px; border-radius: 6px; font-size: 13px; }
|