Skip to content

Commit 53eb3f8

Browse files
committed
feat(findings): mark vendored code with its origin, apart from its context
Closes #243
1 parent 6a1729d commit 53eb3f8

5 files changed

Lines changed: 214 additions & 16 deletions

File tree

‎docs/usage.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,13 @@ wrappers, readers and refiner plugins, which see it. A rule may still give its o
368368
context, as `hardcoded-credential` does with `example` for template files, and the
369369
SARIF result carries that context too.
370370

371+
A finding in vendored code, under a `third_party`, `third-party`, `vendor` or `vendored`
372+
directory, carries `origin: vendored`, in the JSON report and as a property of its SARIF
373+
result. The origin is told apart from the context: the tests of a vendored project
374+
carry both `context: test` and `origin: vendored`. Vendored code is still analysed and
375+
its findings reported, so that a flow from the project through a vendored module is
376+
not lost; the origin changes no verdict either.
377+
371378
`root` is the directory the paths are relative to. A file's `status` is `analysed`,
372379
`ambiguous` (analysed, but another file has its module name, see above), `syntax-error`
373380
or `unreadable`; only `analysed` files count in `files_analysed`.

‎src/coretrace_python/engine.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
Finding,
7373
Severity,
7474
)
75-
from coretrace_python.findings.context import code_context
75+
from coretrace_python.findings.context import code_context, code_origin
7676
from coretrace_python.findings.refutation import RefutationAnalysis
7777
from coretrace_python.findings.suppressions import partition
7878
from coretrace_python.frontend import HIRBuildError, ParseError, build_hir
@@ -709,16 +709,21 @@ def _path_from(source_id: object, root: Path) -> str | None:
709709

710710

711711
def _situated(finding: Finding, path: str | None) -> Finding:
712-
"""``finding`` with the context of its code in its metadata (``code_context``), judged
713-
on ``path``, its file's path from the root of the report. A context the rule gave the
714-
finding stays: it is the rule's (#244)."""
712+
"""``finding`` with the context (``code_context``) and the origin (``code_origin``) of
713+
its code in its metadata, judged on ``path``, its file's path from the root of the
714+
report. A context the rule gave the finding stays: it is the rule's (#244). The origin
715+
is told apart from the context, so vendored test code is both (#243)."""
715716

716-
if path is None or "context" in finding.metadata:
717+
if path is None:
717718
return finding
718-
situation = code_context(path)
719-
if situation is None:
720-
return finding
721-
return replace(finding, metadata={**finding.metadata, "context": situation})
719+
added: dict[str, str] = {}
720+
context = code_context(path)
721+
if context is not None and "context" not in finding.metadata:
722+
added["context"] = context
723+
origin = code_origin(path)
724+
if origin is not None:
725+
added["origin"] = origin
726+
return replace(finding, metadata={**finding.metadata, **added}) if added else finding
722727

723728

724729
def _sourced(finding: Finding, origins: Origins) -> Finding:

‎src/coretrace_python/findings/context.py‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
1-
"""Where the code of a finding lives, by its path in the project (#244): test code, which
2-
a project runs to check itself and does not ship. The context is a fact about the file,
3-
shown in the finding's metadata; what it changes, if anything, is the rule's decision, or
4-
a refiner plugin's."""
1+
"""Where the code of a finding lives, by its path in the project, as two separate facts:
2+
its context, test code a project runs to check itself and does not ship (#244), and its
3+
origin, vendored code, someone else's kept in the project (#243). A vendored project's
4+
tests are both. Both are shown in the finding's metadata; what they change, if
5+
anything, is the rule's decision, or a refiner plugin's."""
56

67
from __future__ import annotations
78

89
import re
910
from pathlib import PurePosixPath
1011

1112
TEST = "test"
13+
VENDORED = "vendored"
14+
15+
_VENDORED_DIRECTORIES = frozenset({"third_party", "third-party", "vendor", "vendored"})
1216

1317
_TEST_DIRECTORIES = frozenset({"test", "tests", "testing", "fixtures", "__tests__"})
1418
_TEST_FILE = re.compile(r"^(test_.*|.*_test|conftest)\.py$")
@@ -30,3 +34,11 @@ def code_context(path: str) -> str | None:
3034
does not count."""
3135

3236
return TEST if is_test_code(path) else None
37+
38+
39+
def code_origin(path: str) -> str | None:
40+
"""The origin a finding at ``path`` carries: ``"vendored"`` under a ``third_party``,
41+
``third-party``, ``vendor`` or ``vendored`` directory of the project, ``None`` for the
42+
project's own code."""
43+
44+
return VENDORED if any(part in _VENDORED_DIRECTORIES for part in PurePosixPath(path).parts[:-1]) else None

‎src/coretrace_python/reporters/sarif.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@
1919
Severity.LOW: "note",
2020
Severity.INFO: "note",
2121
}
22-
# The kinds of injection and the contexts of code a finding may carry, the only metadata
23-
# a result exports: other metadata, such as evidence, may quote what the analysed code
24-
# holds.
22+
# The kinds of injection, the contexts and the origins of code a finding may carry, the
23+
# only metadata a result exports: other metadata, such as evidence, may quote what the
24+
# analysed code holds.
2525
_INJECTIONS = frozenset({"option", "command"})
2626
_CONTEXTS = frozenset({"test", "example"})
27+
_ORIGINS = frozenset({"vendored"})
2728

2829

2930
def _artifact(report: Report, path: str) -> dict[str, str]:
@@ -65,6 +66,9 @@ def _result(
6566
context = finding.metadata.get("context")
6667
if context in _CONTEXTS:
6768
properties["context"] = context
69+
origin = finding.metadata.get("origin")
70+
if origin in _ORIGINS:
71+
properties["origin"] = origin
6872
if properties:
6973
result["properties"] = properties
7074
if suppressed:

‎tests/test_vendored_context.py‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
"""Acceptance tests for issue #243: vendored code is still analysed, and its findings say
2+
where they come from.
3+
4+
Code a project keeps under a ``third_party``, ``third-party``, ``vendor`` or ``vendored``
5+
directory is someone else's: its findings carry ``origin: vendored`` in their metadata,
6+
in the JSON report and in SARIF. The origin is told apart from the context of #244: a
7+
vendored project's tests carry both ``context: test`` and ``origin: vendored``, so a
8+
reader and a refiner still see why they are test code. Nothing is excluded: the
9+
findings and the flows through vendored modules stay as they were.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import json
15+
from pathlib import Path
16+
17+
import pytest
18+
19+
from coretrace_python import engine
20+
from coretrace_python.findings import Confidence, Finding
21+
from coretrace_python.findings.context import code_context, code_origin
22+
from coretrace_python.reporters.sarif import render_sarif
23+
24+
XML_TEST = """\
25+
from xml.dom import minidom
26+
27+
PASSWORD = "Zx81kQpLw0RtY7vB"
28+
EXPECTED = "<testsuites><testsuite name='Filter'/></testsuites>"
29+
30+
31+
def expected_document():
32+
return minidom.parseString(EXPECTED)
33+
"""
34+
35+
PARSER = "from xml.dom import minidom\n\n\ndef parse(document):\n return minidom.parseString(document)\n"
36+
RUNNER = "import os\n\n\ndef run(cmd):\n os.system(cmd)\n"
37+
VIEWS = (
38+
"from flask import request\n\nfrom third_party.tools.runner import run\n\n\n"
39+
"def view():\n run(request.args['c'])\n"
40+
)
41+
42+
43+
@pytest.mark.parametrize(
44+
("path", "origin", "context"),
45+
[
46+
("third_party/gtest/test/xml_output_test.py", "vendored", "test"),
47+
("third-party/lib/parse.py", "vendored", None),
48+
("vendor/requests/api.py", "vendored", None),
49+
("src/vendored/six.py", "vendored", None),
50+
("vendor/lib/tests/test_api.py", "vendored", "test"),
51+
("app/vendor_api.py", None, None),
52+
("external/client.py", None, None),
53+
("tests/test_app.py", None, "test"),
54+
],
55+
)
56+
def test_origin_and_context_are_told_apart(path: str, origin: str | None, context: str | None) -> None:
57+
assert (code_origin(path), code_context(path)) == (origin, context)
58+
59+
60+
def write(root: Path, files: dict[str, str]) -> Path:
61+
for name, text in files.items():
62+
(root / name).parent.mkdir(parents=True, exist_ok=True)
63+
(root / name).write_text(text, encoding="utf-8")
64+
return root
65+
66+
67+
def located(findings: tuple[Finding, ...], name: str) -> dict[str, Finding]:
68+
return {f.rule_id: f for f in findings if Path(str(f.span.source_id)).as_posix().endswith(name)}
69+
70+
71+
def situation(finding: Finding) -> tuple[str | None, str | None]:
72+
return finding.metadata.get("context"), finding.metadata.get("origin")
73+
74+
75+
def test_vendored_findings_are_kept_and_carry_both_facts(tmp_path: Path) -> None:
76+
root = write(
77+
tmp_path / "project",
78+
{
79+
"third_party/gtest/test/xml_output_test.py": XML_TEST,
80+
"vendor/lib/vendored_output.py": XML_TEST,
81+
"app/own_output.py": XML_TEST,
82+
},
83+
)
84+
85+
findings = engine.analyze_project(root, [engine.BUNDLED_PLUGINS]).findings
86+
vendored_test = located(findings, "third_party/gtest/test/xml_output_test.py")
87+
vendored = located(findings, "vendor/lib/vendored_output.py")
88+
own = located(findings, "app/own_output.py")
89+
90+
assert set(vendored_test) == set(vendored) == set(own) == {"hardcoded-credential", "unsafe-xml"}
91+
assert {rule: situation(f) for rule, f in vendored_test.items()} == dict.fromkeys(vendored_test, ("test", "vendored"))
92+
assert {rule: situation(f) for rule, f in vendored.items()} == dict.fromkeys(vendored, (None, "vendored"))
93+
assert {rule: situation(f) for rule, f in own.items()} == dict.fromkeys(own, (None, None))
94+
# The origin changes no verdict: the credential is low as test code, medium otherwise.
95+
assert vendored_test["hardcoded-credential"].confidence is Confidence.LOW
96+
assert vendored["hardcoded-credential"].confidence is Confidence.MEDIUM
97+
assert vendored["unsafe-xml"].confidence == own["unsafe-xml"].confidence
98+
99+
100+
def test_a_flow_through_a_vendored_module_is_still_reported(tmp_path: Path) -> None:
101+
root = write(
102+
tmp_path / "project",
103+
{
104+
"third_party/__init__.py": "",
105+
"third_party/tools/__init__.py": "",
106+
"third_party/tools/runner.py": RUNNER,
107+
"app/__init__.py": "",
108+
"app/views.py": VIEWS,
109+
},
110+
)
111+
112+
findings = engine.analyze_project(root, [engine.BUNDLED_PLUGINS]).findings
113+
flows = [f for f in findings if f.rule_id == "command-injection"]
114+
115+
assert [(Path(str(f.span.source_id)).name, f.span.start_line) for f in flows] == [("views.py", 7)]
116+
assert situation(flows[0]) == (None, None)
117+
118+
119+
def test_the_sarif_result_carries_both_facts(tmp_path: Path) -> None:
120+
root = write(tmp_path / "project", {"vendor/lib/tests/test_output.py": XML_TEST})
121+
analysis = engine.analyze_project(root, [engine.BUNDLED_PLUGINS])
122+
123+
results = json.loads(render_sarif(engine.report(analysis.findings, root=root)))["runs"][0]["results"]
124+
125+
assert {r["ruleId"]: r["properties"] for r in results} == {
126+
"hardcoded-credential": {"context": "test", "origin": "vendored"},
127+
"unsafe-xml": {"context": "test", "origin": "vendored"},
128+
}
129+
130+
131+
REFINER_MANIFEST = (
132+
'name = "test-confidence"\nversion = "1.0.0"\nplugin_api = ">=1,<2"\nrequires = []\n'
133+
'provides = []\n\n[entrypoint]\nmodule = "refiner"\nclass = "TestConfidence"\n'
134+
)
135+
REFINER = '''
136+
from dataclasses import replace
137+
from typing import ClassVar
138+
139+
from coretrace_python.findings import Confidence
140+
from coretrace_python.plugins import ProjectPlugin
141+
142+
143+
class TestConfidence(ProjectPlugin):
144+
name: ClassVar[str] = "test-confidence"
145+
146+
def analyze_project(self, ctx):
147+
return ()
148+
149+
def refine(self, ctx, findings):
150+
return [
151+
replace(f, confidence=Confidence.LOW) if f.metadata.get("context") == "test" else f
152+
for f in findings
153+
]
154+
'''
155+
156+
157+
def test_a_refiner_still_recognises_vendored_test_code(tmp_path: Path) -> None:
158+
plugin = tmp_path / "plugins" / "refiner"
159+
plugin.mkdir(parents=True)
160+
(plugin / "plugin.toml").write_text(REFINER_MANIFEST, encoding="utf-8")
161+
(plugin / "refiner.py").write_text(REFINER, encoding="utf-8")
162+
root = write(
163+
tmp_path / "project",
164+
{"vendor/lib/tests/test_parser.py": PARSER, "vendor/lib/parser.py": PARSER},
165+
)
166+
167+
findings = engine.analyze_project(root, [engine.BUNDLED_PLUGINS, tmp_path / "plugins"]).findings
168+
169+
assert located(findings, "vendor/lib/tests/test_parser.py")["unsafe-xml"].confidence is Confidence.LOW
170+
assert located(findings, "vendor/lib/parser.py")["unsafe-xml"].confidence is Confidence.HIGH

0 commit comments

Comments
 (0)