Repository navigation
Expand file tree
/
Copy pathcache.py
More file actions
427 lines (346 loc) · 15.2 KB
/
Copy pathcache.py
File metadata and controls
427 lines (346 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
"""Persistent per-module cache (architecture §11, §38 Phase 10).
A module's results are stored under a key derived from everything they depend on: its
source text and identity, the engine, schema and plugin API versions, the plugins and
their code, the security models, the advisories, the dependency graph, and the keys of
the project modules it imports transitively. A module whose key is unchanged on a later
run is served from the cache: its summaries seed the project index, its call sites and
symbol reads serve the project plugins and its findings are reported as they were.
Entries are JSON, so a tampered or foreign file can never execute anything; an
unreadable entry is a miss.
"""
from __future__ import annotations
import hashlib
import json
import os
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Any
from coretrace_python.findings import Confidence, Finding, RelatedLocation, Severity
from coretrace_python.interprocedural import (
Arguments,
CallSite,
Cleared,
ExternalCall,
ExternalSymbol,
FunctionSummary,
KnownFunction,
ModuleFunction,
ModuleGraph,
Mutation,
NonlocalWrite,
PriorCall,
SymbolRead,
Target,
UnknownTarget,
)
from coretrace_python.semantic.symbols import SymbolId
from coretrace_python.source import FileLocation, Location, SourceId, SourceSpan
# Cached summaries from earlier versions preserve unstable external-call
# insertion order. They must be recomputed with canonical ordering (#261).
# Findings carry their related locations from format 18 on (#271). A module's key holds
# the names it is imported by from format 19 on (#264).
CACHE_FORMAT = 19
@dataclass(frozen=True)
class CachedModule:
"""Everything a later run needs from one module without lowering it again."""
functions: tuple[ModuleFunction, ...]
summaries: Mapping[str, FunctionSummary]
sites: tuple[CallSite, ...]
findings: tuple[Finding, ...]
reads: tuple[SymbolRead, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "summaries", MappingProxyType(dict(self.summaries)))
# --------------------------------------------------------------------------- keys
def fingerprint(*parts: str) -> str:
digest = hashlib.sha256()
for part in parts:
digest.update(part.encode("utf-8"))
digest.update(b"\0")
return digest.hexdigest()
def directory_fingerprint(directory: Path) -> str:
"""A digest of every file under ``directory``, so an edited plugin misses: its code,
its manifest and the rule or advisory data it ships in any format. Bytecode and
hidden files are not part of what the plugin does."""
parts: list[str] = []
for path in sorted(directory.rglob("*")):
relative = path.relative_to(directory)
if not path.is_file() or any(p == "__pycache__" or p.startswith(".") for p in relative.parts):
continue
parts.append(str(relative))
parts.append(path.read_bytes().hex())
return fingerprint(*parts)
def module_keys(graph: ModuleGraph, own: Mapping[str, str]) -> dict[str, str]:
"""The key of each module: its own key plus those of every module it imports,
transitively, so a change anywhere below a module misses for that module too."""
keys: dict[str, str] = {}
for name in graph.modules:
closure: set[str] = set()
pending = [name]
while pending:
current = pending.pop()
for imported in graph.imports(current):
if imported in own and imported not in closure and imported != name:
closure.add(imported)
pending.append(imported)
keys[name] = fingerprint(own[name], *(own[m] for m in sorted(closure)))
return keys
# --------------------------------------------------------------------------- store
class ProjectCache:
"""A directory of JSON entries, one per module key."""
def __init__(self, directory: Path) -> None:
self.directory = directory
def load(self, key: str) -> CachedModule | None:
path = self.directory / f"{key}.json"
try:
with path.open(encoding="utf-8") as handle:
return decode(json.load(handle))
except (OSError, ValueError, KeyError, TypeError, IndexError, AttributeError):
return None
def store(self, key: str, module: CachedModule) -> None:
self.directory.mkdir(parents=True, exist_ok=True)
path = self.directory / f"{key}.json"
temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
temporary.write_text(json.dumps(encode(module)), encoding="utf-8")
temporary.replace(path)
# --------------------------------------------------------------------------- codec
def encode(module: CachedModule) -> dict[str, Any]:
return {
"format": CACHE_FORMAT,
"functions": [[f.name, _encode_span(f.span), f.entry_point, list(f.aliases)] for f in module.functions],
"summaries": {name: _encode_summary(s) for name, s in module.summaries.items()},
"sites": [_encode_site(site) for site in module.sites],
"findings": [_encode_finding(finding) for finding in module.findings],
"reads": [[r.function, _encode_span(r.location), str(r.symbol)] for r in module.reads],
}
def decode(data: Mapping[str, Any]) -> CachedModule:
if data["format"] != CACHE_FORMAT:
raise ValueError(f"unsupported cache format {data['format']!r}")
return CachedModule(
tuple(_decode_function(function) for function in data["functions"]),
{_string(name): _decode_summary(s) for name, s in data["summaries"].items()},
tuple(_decode_site(site) for site in data["sites"]),
tuple(_decode_finding(finding) for finding in data["findings"]),
tuple(_decode_read(read) for read in data["reads"]),
)
def _string(value: Any) -> str:
if not isinstance(value, str):
raise TypeError(f"expected a string, got {value!r}")
return value
def _integer(value: Any) -> int:
if not isinstance(value, int) or isinstance(value, bool):
raise TypeError(f"expected an integer, got {value!r}")
return value
def _indices(values: Any) -> frozenset[int]:
return frozenset(_integer(v) for v in values)
def _encode_span(span: SourceSpan) -> list[Any]:
return [str(span.source_id), span.start_line, span.start_column, span.end_line, span.end_column]
def _encode_location(location: Location) -> Any:
if isinstance(location, FileLocation):
return {
"file": str(location.source_id),
"pointer": location.pointer,
"digest": location.digest,
}
return _encode_span(location)
def _decode_location(data: Any) -> Location:
if isinstance(data, Mapping):
return FileLocation(
SourceId(_string(data["file"])), _string(data["pointer"]), _string(data["digest"])
)
return _decode_span(data)
def _decode_span(data: Any) -> SourceSpan:
file, line, column, end_line, end_column = data
return SourceSpan(
SourceId(_string(file)),
_integer(line),
_integer(column),
None if end_line is None else _integer(end_line),
None if end_column is None else _integer(end_column),
)
def _decode_function(data: Any) -> ModuleFunction:
name, span, entry_point, aliases = data
return ModuleFunction(
_string(name),
_decode_span(span),
None if entry_point is None else _string(entry_point),
tuple(_string(alias) for alias in aliases),
)
def _decode_read(data: Any) -> SymbolRead:
function, span, symbol = data
return SymbolRead(_string(function), _decode_span(span), SymbolId(_string(symbol)))
def _encode_finding(finding: Finding) -> dict[str, Any]:
return {
"rule": finding.rule_id,
"message": finding.message,
"severity": finding.severity.value,
"confidence": finding.confidence.value,
"span": _encode_location(finding.span),
"function": finding.function,
"metadata": dict(finding.metadata),
"related": [[_encode_span(r.span), r.message] for r in finding.related],
}
def _decode_finding(data: Mapping[str, Any]) -> Finding:
function = data["function"]
return Finding(
_string(data["rule"]),
_string(data["message"]),
Severity(data["severity"]),
Confidence(data["confidence"]),
_decode_location(data["span"]),
None if function is None else _string(function),
{_string(k): _string(v) for k, v in data["metadata"].items()},
tuple(RelatedLocation(_decode_span(span), _string(message)) for span, message in data["related"]),
)
def _encode_call(call: ExternalCall) -> dict[str, Any]:
return {
"symbol": str(call.symbol),
"arguments": [sorted(deps) for deps in call.argument_dependencies],
"keywords": [[name, sorted(deps)] for name, deps in call.keyword_dependencies],
"location": _encode_span(call.location),
"call_site": None if call.call_site is None else _encode_span(call.call_site),
"given": _encode_arguments(call.arguments),
"argument_cleared": [_encode_cleared(c) for c in call.argument_cleared],
"keyword_cleared": [_encode_cleared(c) for c in call.keyword_cleared],
"invoked_at": None if call.invoked_at is None else _encode_span(call.invoked_at),
}
def _decode_call(data: Mapping[str, Any]) -> ExternalCall:
site = data["call_site"]
invoked_at = data["invoked_at"]
return ExternalCall(
SymbolId(_string(data["symbol"])),
tuple(_indices(deps) for deps in data["arguments"]),
tuple((None if name is None else _string(name), _indices(deps)) for name, deps in data["keywords"]),
_decode_span(data["location"]),
None if site is None else _decode_span(site),
_decode_arguments(data["given"]),
tuple(_decode_cleared(c) for c in data["argument_cleared"]),
tuple(_decode_cleared(c) for c in data["keyword_cleared"]),
None if invoked_at is None else _decode_span(invoked_at),
)
def _encode_cleared(cleared: Cleared) -> list[list[int]]:
return [[parameter, bits] for parameter, bits in cleared]
def _decode_cleared(data: Any) -> Cleared:
return tuple((_integer(parameter), _integer(bits)) for parameter, bits in data)
def _encode_summary(summary: FunctionSummary) -> dict[str, Any]:
return {
"name": summary.name,
"parameters": summary.parameters,
"returns": sorted(summary.return_dependencies),
"external_calls": [_encode_call(call) for call in summary.external_calls],
"unsupported": summary.unsupported,
"return_externals": sorted(str(s) for s in summary.return_externals),
"mutations": [
{
"parameter": m.parameter,
"field": m.field,
"dependencies": sorted(m.dependencies),
"externals": sorted(str(s) for s in m.externals),
}
for m in summary.mutations
],
"side_effects": sorted(summary.side_effects),
"nonlocal_writes": [
{
"name": w.name,
"dependencies": sorted(w.dependencies),
"externals": sorted(str(s) for s in w.externals),
"kept": w.kept,
}
for w in summary.nonlocal_writes
],
"static": summary.static,
"return_cleared": _encode_cleared(summary.return_cleared),
}
def _decode_summary(data: Mapping[str, Any]) -> FunctionSummary:
return FunctionSummary(
_string(data["name"]),
_integer(data["parameters"]),
_indices(data["returns"]),
tuple(_decode_call(call) for call in data["external_calls"]),
bool(data["unsupported"]),
frozenset(SymbolId(_string(s)) for s in data["return_externals"]),
tuple(
Mutation(
_integer(m["parameter"]),
_string(m["field"]),
_indices(m["dependencies"]),
frozenset(SymbolId(_string(s)) for s in m["externals"]),
)
for m in data["mutations"]
),
frozenset(_string(name) for name in data["side_effects"]),
tuple(
NonlocalWrite(
_string(w["name"]),
_indices(w["dependencies"]),
frozenset(SymbolId(_string(s)) for s in w["externals"]),
bool(w["kept"]),
)
for w in data["nonlocal_writes"]
),
bool(data["static"]),
_decode_cleared(data["return_cleared"]),
)
def _encode_target(target: Target) -> dict[str, Any]:
if isinstance(target, KnownFunction):
return {"kind": "known", "name": target.name}
if isinstance(target, ExternalSymbol):
return {"kind": "external", "symbol": str(target.symbol)}
return {"kind": "unknown"}
def _decode_target(data: Mapping[str, Any]) -> Target:
kind = data["kind"]
if kind == "known":
return KnownFunction(_string(data["name"]))
if kind == "external":
return ExternalSymbol(SymbolId(_string(data["symbol"])))
if kind == "unknown":
return UnknownTarget()
raise ValueError(f"unknown call target kind {kind!r}")
def _encode_site(site: CallSite) -> dict[str, Any]:
return {
"caller": site.caller,
"location": _encode_span(site.location),
"target": _encode_target(site.target),
"arguments": _encode_arguments(site.arguments),
"prior": None
if site.prior_calls is None
else [
[str(p.symbol), _encode_span(p.location), _encode_arguments(p.arguments), p.dominates]
for p in site.prior_calls
],
}
def _decode_site(data: Mapping[str, Any]) -> CallSite:
prior = data["prior"]
return CallSite(
_string(data["caller"]),
_decode_span(data["location"]),
_decode_target(data["target"]),
_decode_arguments(data["arguments"]),
None if prior is None else tuple(_decode_prior(entry) for entry in prior),
)
def _decode_prior(data: Any) -> PriorCall:
symbol, span, arguments, dominates = data
if not isinstance(dominates, bool):
raise TypeError(f"expected a boolean, got {dominates!r}")
return PriorCall(SymbolId(_string(symbol)), _decode_span(span), _decode_arguments(arguments), dominates)
def _encode_arguments(arguments: Arguments) -> dict[str, Any]:
return {
"positional": list(arguments.positional),
"keywords": [[name, value] for name, value in arguments.keywords],
"unpacked": arguments.unpacked,
"keyword_unpacked": arguments.keyword_unpacked,
}
def _decode_arguments(data: Mapping[str, Any]) -> Arguments:
def denoted(value: Any) -> str | None:
return None if value is None else _string(value)
unpacked, keyword_unpacked = data["unpacked"], data["keyword_unpacked"]
if not isinstance(unpacked, bool) or not isinstance(keyword_unpacked, bool):
raise TypeError(f"expected booleans, got {unpacked!r} and {keyword_unpacked!r}")
return Arguments(
tuple(denoted(value) for value in data["positional"]),
tuple((_string(name), denoted(value)) for name, value in data["keywords"]),
unpacked,
keyword_unpacked,
)