seculens 0.3.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.
seculens/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """SecuLens Python implementation; no JavaScript runtime dependency."""
2
+
3
+ from .analysis import analyze
4
+ from .core import scan_sbom, sha256
5
+ from .database import fetch_database, validate_database
6
+ from .licenses import evaluate_license
7
+ from .matcher import match_record
8
+ from .sbom import parse_sbom
9
+ from .word import write_word_report
10
+
11
+ __version__ = "0.3.1"
12
+ __all__ = [
13
+ "scan_sbom",
14
+ "sha256",
15
+ "parse_sbom",
16
+ "match_record",
17
+ "evaluate_license",
18
+ "fetch_database",
19
+ "validate_database",
20
+ "analyze",
21
+ "__version__",
22
+ "write_word_report",
23
+ ]
seculens/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
seculens/analysis.py ADDED
@@ -0,0 +1,211 @@
1
+ """Python syntax-tree review candidates and function complexity measurements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import tokenize
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ _IGNORED = {
11
+ ".git",
12
+ ".venv",
13
+ "venv",
14
+ "env",
15
+ "node_modules",
16
+ "vendor",
17
+ "dist",
18
+ "build",
19
+ "__pycache__",
20
+ }
21
+ _FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
22
+ _BRANCHES = (
23
+ ast.If,
24
+ ast.For,
25
+ ast.AsyncFor,
26
+ ast.While,
27
+ ast.IfExp,
28
+ ast.ExceptHandler,
29
+ ast.comprehension,
30
+ )
31
+
32
+
33
+ def _qualified(node: ast.AST, aliases: dict[str, str]) -> str:
34
+ if isinstance(node, ast.Name):
35
+ return aliases.get(node.id, node.id)
36
+ if isinstance(node, ast.Attribute):
37
+ parent = _qualified(node.value, aliases)
38
+ return f"{parent}.{node.attr}" if parent else ""
39
+ return ""
40
+
41
+
42
+ def _complexity(function: ast.AST) -> tuple[int, int]:
43
+ complexity, deepest = 1, 0
44
+
45
+ def count(node: ast.AST, depth: int) -> None:
46
+ nonlocal complexity, deepest
47
+ if node is not function and isinstance(node, _FUNCTIONS):
48
+ return
49
+ branch = isinstance(node, _BRANCHES)
50
+ if branch:
51
+ complexity += 1
52
+ if isinstance(node, ast.BoolOp):
53
+ complexity += len(node.values) - 1
54
+ if isinstance(node, ast.comprehension):
55
+ complexity += len(node.ifs)
56
+ if isinstance(node, ast.match_case) and not (
57
+ isinstance(node.pattern, ast.MatchAs)
58
+ and node.pattern.pattern is None
59
+ and node.pattern.name is None
60
+ ):
61
+ complexity += 1
62
+ branch = True
63
+ depth += int(branch)
64
+ deepest = max(deepest, depth)
65
+ for child in ast.iter_child_nodes(node):
66
+ count(child, depth)
67
+
68
+ # Function defaults and decorators are outside its executed body.
69
+ if isinstance(function, ast.Lambda):
70
+ count(function.body, 0)
71
+ else:
72
+ for node in function.body:
73
+ count(node, 0)
74
+ return complexity, deepest
75
+
76
+
77
+ def analyze(directory: str | Path) -> list[dict[str, Any]]:
78
+ root = Path(directory).resolve()
79
+ if not root.is_dir():
80
+ raise ValueError("Source must be a directory")
81
+ files: list[Path] = []
82
+
83
+ def collect(folder: Path) -> None:
84
+ for path in sorted(folder.iterdir()):
85
+ if path.is_symlink() or path.name in _IGNORED:
86
+ continue
87
+ if path.is_dir():
88
+ collect(path)
89
+ elif path.is_file() and path.suffix == ".py":
90
+ files.append(path)
91
+
92
+ collect(root)
93
+ findings: list[dict[str, Any]] = []
94
+ for file in files:
95
+ relative = file.relative_to(root).as_posix()
96
+ try:
97
+ with tokenize.open(file) as stream:
98
+ source = stream.read()
99
+ tree = ast.parse(source, filename=relative)
100
+ except (SyntaxError, UnicodeError, LookupError) as error:
101
+ findings.append(
102
+ {
103
+ "category": "coverage",
104
+ "ruleId": "PY-PARSE-ERROR",
105
+ "subject": relative,
106
+ "status": "unassessed",
107
+ "summary": "Source could not be completely parsed",
108
+ "evidence": str(error),
109
+ "recommendation": "Resolve the syntax error and repeat the analysis.",
110
+ "file": relative,
111
+ }
112
+ )
113
+ continue
114
+ aliases: dict[str, str] = {}
115
+ for node in ast.walk(tree):
116
+ if isinstance(node, ast.Import):
117
+ for item in node.names:
118
+ aliases[item.asname or item.name.split(".")[0]] = (
119
+ item.name if item.asname else item.name.split(".")[0]
120
+ )
121
+ elif isinstance(node, ast.ImportFrom) and node.module:
122
+ for item in node.names:
123
+ if item.name != "*":
124
+ aliases[item.asname or item.name] = f"{node.module}.{item.name}"
125
+
126
+ def add(
127
+ node: ast.AST,
128
+ category: str,
129
+ rule: str,
130
+ summary: str,
131
+ evidence: str | None = None,
132
+ *,
133
+ relative: str = relative,
134
+ source: str = source,
135
+ ) -> None:
136
+ findings.append(
137
+ {
138
+ "category": category,
139
+ "ruleId": rule,
140
+ "subject": relative,
141
+ "status": "review",
142
+ "summary": summary,
143
+ "evidence": evidence
144
+ if evidence is not None
145
+ else (ast.get_source_segment(source, node) or "")[:300],
146
+ "recommendation": "Review the call and trace untrusted input before deciding whether it is exploitable."
147
+ if category == "security"
148
+ else "Consider simplifying the function and adding focused tests.",
149
+ "file": relative,
150
+ "line": node.lineno,
151
+ }
152
+ )
153
+
154
+ for node in ast.walk(tree):
155
+ if isinstance(node, ast.Call):
156
+ name = _qualified(node.func, aliases)
157
+ if name in ("eval", "exec", "builtins.eval", "builtins.exec"):
158
+ add(
159
+ node,
160
+ "security",
161
+ "PY-DYNAMIC-EXECUTION",
162
+ "Dynamic code execution requires review",
163
+ )
164
+ elif name in ("os.system", "os.popen"):
165
+ add(node, "security", "PY-OS-SHELL", "Shell command execution requires review")
166
+ elif name in {
167
+ f"subprocess.{method}"
168
+ for method in ("run", "Popen", "call", "check_call", "check_output")
169
+ } and any(
170
+ k.arg == "shell" and isinstance(k.value, ast.Constant) and k.value.value is True
171
+ for k in node.keywords
172
+ ):
173
+ add(
174
+ node,
175
+ "security",
176
+ "PY-SUBPROCESS-SHELL",
177
+ "subprocess shell=True requires review",
178
+ )
179
+ elif name in ("pickle.load", "pickle.loads"):
180
+ add(
181
+ node,
182
+ "security",
183
+ "PY-PICKLE",
184
+ "Pickle deserialization requires trusted data",
185
+ )
186
+ elif name == "yaml.load":
187
+ loaders = [
188
+ _qualified(k.value, aliases) for k in node.keywords if k.arg == "Loader"
189
+ ]
190
+ if len(node.args) > 1:
191
+ loaders.append(_qualified(node.args[1], aliases))
192
+ if not any(
193
+ loader in ("yaml.SafeLoader", "yaml.CSafeLoader") for loader in loaders
194
+ ):
195
+ add(
196
+ node,
197
+ "security",
198
+ "PY-YAML-LOAD",
199
+ "YAML load without an explicit safe loader requires review",
200
+ )
201
+ if isinstance(node, _FUNCTIONS):
202
+ complexity, depth = _complexity(node)
203
+ if complexity > 10 or depth > 4:
204
+ add(
205
+ node,
206
+ "quality",
207
+ "PY-COMPLEXITY",
208
+ "Function complexity exceeds the baseline",
209
+ f"cyclomatic={complexity}; nesting={depth}; thresholds=10,4",
210
+ )
211
+ return sorted(findings, key=lambda f: (f["file"], f.get("line", 0), f["ruleId"]))
Binary file
@@ -0,0 +1,92 @@
1
+ This Font Software is licensed under the SIL Open Font License,
2
+ Version 1.1.
3
+
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font
14
+ creation efforts of academic and linguistic communities, and to
15
+ provide a free and open framework in which fonts may be shared and
16
+ improved in partnership with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply to
25
+ any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software
36
+ components as distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to,
39
+ deleting, or substituting -- in part or in whole -- any of the
40
+ components of the Original Version, by changing formats or by porting
41
+ the Font Software to a new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION & CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed,
49
+ modify, redistribute, and sell modified and unmodified copies of the
50
+ Font Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components, in
53
+ Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the
64
+ corresponding Copyright Holder. This restriction only applies to the
65
+ primary font name as presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created using
77
+ the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
seculens/cli.py ADDED
@@ -0,0 +1,146 @@
1
+ """Native Python CLI. Syft is an optional external SBOM generator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from .analysis import analyze
12
+ from .core import scan_sbom, sha256
13
+ from .database import fetch_database, validate_database
14
+ from .sbom import parse_sbom
15
+ from .wizard import wizard
16
+ from .word import write_word_report
17
+
18
+
19
+ def _json(text: str):
20
+ return json.loads(text)
21
+
22
+
23
+ def main(argv: list[str] | None = None) -> int:
24
+ try:
25
+ return _main(argv)
26
+ except KeyboardInterrupt:
27
+ print("\nCancelled / 中止しました。", file=sys.stderr)
28
+ return 130
29
+
30
+
31
+ def _main(argv: list[str] | None = None) -> int:
32
+ parser = argparse.ArgumentParser(
33
+ prog="seculens", description="SBOM assessment and evidence-based customer reports"
34
+ )
35
+ parser.add_argument("--version", action="version", version="0.3.1")
36
+ commands = parser.add_subparsers(dest="command", required=True)
37
+ interactive = commands.add_parser("wizard", help="Interactive setup in English or Japanese")
38
+ interactive.add_argument("--lang", choices=("en", "ja"))
39
+ sbom = commands.add_parser("sbom", help="Generate CycloneDX or SPDX JSON using Syft")
40
+ sbom.add_argument("project", type=Path)
41
+ sbom.add_argument("--format", choices=("cyclonedx", "spdx"), default="cyclonedx")
42
+ sbom.add_argument("--syft", default="syft", help="Syft executable path")
43
+ sbom.add_argument("-o", "--output", required=True, type=Path)
44
+ scan = commands.add_parser("scan", help="Assess a JSON SBOM using OSV candidate records")
45
+ scan.add_argument("sbom", type=Path)
46
+ database = scan.add_mutually_exclusive_group(required=True)
47
+ database.add_argument("--db", type=Path)
48
+ database.add_argument(
49
+ "--fetch-osv", action="store_true", help="Send package names/ecosystems to OSV"
50
+ )
51
+ scan.add_argument("--policy", type=Path)
52
+ scan.add_argument("--source", type=Path, help="Run Python AST review rules")
53
+ scan.add_argument("--customer", default="Customer")
54
+ scan.add_argument("--target", help="Human-readable system or project name")
55
+ scan.add_argument("--report-style", choices=("standard", "customer"), default="standard")
56
+ scan.add_argument("--issuer", default="", help="Report preparer name for the customer cover")
57
+ scan.add_argument("--lang", choices=("en", "ja"), default="en")
58
+ scan.add_argument("-o", "--output", type=Path, default=Path("reports"))
59
+ scan.add_argument("--fail-on-findings", action="store_true")
60
+ args = list(sys.argv[1:] if argv is None else argv)
61
+ ui_language = "en"
62
+ if not args:
63
+ args, ui_language = wizard()
64
+ if args is None:
65
+ return 0
66
+ opts = parser.parse_args(args)
67
+ if opts.command == "wizard":
68
+ args, ui_language = wizard(opts.lang)
69
+ if args is None:
70
+ return 0
71
+ opts = parser.parse_args(args)
72
+ try:
73
+ if opts.command == "sbom":
74
+ if not opts.project.is_dir():
75
+ raise ValueError("Project must be a directory")
76
+ output_format = "cyclonedx-json" if opts.format == "cyclonedx" else "spdx-json"
77
+ result = subprocess.run(
78
+ [opts.syft, "scan", f"dir:{opts.project.resolve()}", "-o", output_format],
79
+ capture_output=True,
80
+ text=True,
81
+ check=True,
82
+ )
83
+ parse_sbom(_json(result.stdout))
84
+ opts.output.parent.mkdir(parents=True, exist_ok=True)
85
+ opts.output.write_text(result.stdout, encoding="utf-8")
86
+ print(
87
+ f"SBOMを保存しました: {opts.output}"
88
+ if ui_language == "ja"
89
+ else f"SBOM written to {opts.output}"
90
+ )
91
+ return 0
92
+ # Read every input before writing output evidence, even when paths overlap.
93
+ input_text = opts.sbom.read_text(encoding="utf-8")
94
+ parsed = parse_sbom(_json(input_text))
95
+ if opts.db:
96
+ database_text = opts.db.read_text(encoding="utf-8")
97
+ records = validate_database(_json(database_text))
98
+ else:
99
+ print(
100
+ "OSVから取得中: パッケージ名とエコシステムをapi.osv.devへ送信します。"
101
+ if ui_language == "ja"
102
+ else "Fetching OSV candidates: package names and ecosystems are sent to api.osv.dev.",
103
+ file=sys.stderr,
104
+ )
105
+ records = fetch_database(parsed["components"])
106
+ database_text = json.dumps({"records": records}, ensure_ascii=False, indent=2) + "\n"
107
+ policy = _json(opts.policy.read_text(encoding="utf-8")) if opts.policy else {}
108
+ report = scan_sbom(
109
+ input_text,
110
+ records,
111
+ customer=opts.customer,
112
+ target=opts.target or opts.sbom.name,
113
+ policy=policy,
114
+ database_source=opts.db.name if opts.db else "OSV API candidate snapshot",
115
+ database_hash=sha256(database_text),
116
+ )
117
+ if opts.source:
118
+ report["findings"].extend(analyze(opts.source))
119
+ report["sourceAnalysis"] = {"language": "Python", "target": opts.source.resolve().name}
120
+ opts.output.mkdir(parents=True, exist_ok=True)
121
+ (opts.output / "sbom.json").write_text(input_text, encoding="utf-8")
122
+ (opts.output / "database.json").write_text(database_text, encoding="utf-8")
123
+ (opts.output / "report.json").write_text(
124
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
125
+ )
126
+ write_word_report(
127
+ report,
128
+ opts.output / "report.docx",
129
+ opts.lang,
130
+ style=opts.report_style,
131
+ issuer=opts.issuer,
132
+ )
133
+ print(
134
+ f"構成部品 {len(parsed['components'])}件、指摘 {len(report['findings'])}件。レポート: {opts.output}"
135
+ if ui_language == "ja"
136
+ else f"{len(parsed['components'])} components; {len(report['findings'])} findings. Reports: {opts.output}"
137
+ )
138
+ if opts.fail_on_findings and any(
139
+ f["status"] in ("affected", "denied") or f["category"] == "security"
140
+ for f in report["findings"]
141
+ ):
142
+ return 1
143
+ return 2 if any(f["status"] == "unassessed" for f in report["findings"]) else 0
144
+ except Exception as error:
145
+ print(f"SecuLens: {error}", file=sys.stderr)
146
+ return 2
seculens/core.py ADDED
@@ -0,0 +1,164 @@
1
+ """Shared report contract, assessment checks and advisory alias consolidation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+
10
+ from .database import validate_database
11
+ from .licenses import license_findings, validate_policy
12
+ from .matcher import match_record, same_package, supported_version
13
+ from .sbom import parse_sbom
14
+ from .severity import merge_severity, record_severity
15
+
16
+ LIMITATIONS = [
17
+ "No match means no matching record in the supplied database snapshot, not absence of vulnerabilities.",
18
+ "License policy checks are not a legal compliance determination.",
19
+ "AST rules identify review candidates and complexity, not proven exploitability.",
20
+ "SBOM content and package identifiers are supplied by the generating tool.",
21
+ "Packagist matching supports stable numeric versions and SemVer prereleases only; Composer branches and other version forms may be unassessed.",
22
+ ]
23
+
24
+
25
+ def sha256(value: str | bytes) -> str:
26
+ return hashlib.sha256(value.encode("utf-8") if isinstance(value, str) else value).hexdigest()
27
+
28
+
29
+ def scan_sbom(
30
+ sbom_text: str,
31
+ records: list[dict[str, Any]],
32
+ *,
33
+ customer: str = "Customer",
34
+ target: str = "SBOM",
35
+ policy: dict[str, Any] | None = None,
36
+ database_source: str = "OSV snapshot",
37
+ database_hash: str | None = None,
38
+ created_at: str | None = None,
39
+ ) -> dict[str, Any]:
40
+ sbom = parse_sbom(json.loads(sbom_text))
41
+ validate_database(records)
42
+ policy = validate_policy({} if policy is None else policy)
43
+ report: dict[str, Any] = {
44
+ "schemaVersion": "1.1",
45
+ "tool": {"name": "SecuLens", "version": "0.3.1"},
46
+ "createdAt": created_at
47
+ or datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
48
+ "customer": customer,
49
+ "target": target,
50
+ "sbomSha256": sha256(sbom_text),
51
+ "database": {
52
+ "source": database_source,
53
+ "sha256": database_hash
54
+ or sha256(json.dumps(records, ensure_ascii=False, separators=(",", ":"))),
55
+ },
56
+ "sbom": sbom,
57
+ "checks": [],
58
+ "findings": [],
59
+ "limitations": list(LIMITATIONS),
60
+ }
61
+ for component in sbom["components"]:
62
+ report["findings"].extend(license_findings(component, policy))
63
+ if not supported_version(component):
64
+ reason = (
65
+ "Supported package URL required (npm, pypi or composer)"
66
+ if not component.get("ecosystem")
67
+ else "Package version is missing"
68
+ if not component.get("version")
69
+ else "Unsupported package version syntax"
70
+ )
71
+ report["checks"].append(
72
+ {
73
+ "componentId": component["id"],
74
+ "status": "unassessed",
75
+ "recordsChecked": 0,
76
+ "reason": reason,
77
+ }
78
+ )
79
+ report["findings"].append(
80
+ {
81
+ "category": "coverage",
82
+ "ruleId": "PACKAGE-IDENTITY",
83
+ "subject": component["id"],
84
+ "status": "unassessed",
85
+ "summary": "Component could not be assessed",
86
+ "evidence": reason,
87
+ "recommendation": "Regenerate the SBOM with complete package URLs and versions.",
88
+ }
89
+ )
90
+ continue
91
+ candidates = [
92
+ r for r in records if any(same_package(component, a["package"]) for a in r["affected"])
93
+ ]
94
+ matched, uncertain = False, False
95
+ for record in candidates:
96
+ result = match_record(component, record)
97
+ if result == "not-affected":
98
+ continue
99
+ if result == "unknown":
100
+ uncertain = True
101
+ report["findings"].append(
102
+ {
103
+ "category": "coverage",
104
+ "ruleId": record["id"],
105
+ "subject": component["id"],
106
+ "status": "unassessed",
107
+ "summary": "Advisory could not be fully evaluated",
108
+ "evidence": f"{component['name']}@{component['version']}; unsupported or incomplete version range",
109
+ "recommendation": "Review the advisory and package version manually.",
110
+ }
111
+ )
112
+ continue
113
+ matched = True
114
+ report["findings"].append(
115
+ {
116
+ "category": "vulnerability",
117
+ "ruleId": record["id"],
118
+ "subject": component["id"],
119
+ "status": "affected",
120
+ "summary": record.get("summary") or record["id"],
121
+ "evidence": f"{component['ecosystem']}:{component['name']}@{component['version']}; matched against affected versions/ranges in {record['id']}",
122
+ "recommendation": "Review the advisory references for a fixed version and validate the upgrade.",
123
+ "severity": record_severity(record, component),
124
+ "aliases": record.get("aliases", []),
125
+ "references": [ref["url"] for ref in record.get("references", [])],
126
+ }
127
+ )
128
+ check = {
129
+ "componentId": component["id"],
130
+ "status": "unassessed" if uncertain else "matched" if matched else "no-match",
131
+ "recordsChecked": len(candidates),
132
+ }
133
+ if uncertain:
134
+ check["reason"] = "One or more candidate records require manual review"
135
+ report["checks"].append(check)
136
+ groups: list[dict[str, Any]] = []
137
+ for finding in report["findings"]:
138
+ if finding["category"] != "vulnerability":
139
+ groups.append(finding)
140
+ continue
141
+ merged = dict(finding)
142
+ changed = True
143
+ while changed:
144
+ changed = False
145
+ for index in range(len(groups) - 1, -1, -1):
146
+ other = groups[index]
147
+ if other["category"] != "vulnerability" or other["subject"] != merged["subject"]:
148
+ continue
149
+ identities = {merged["ruleId"], *merged["aliases"]}
150
+ if not identities.intersection({other["ruleId"], *other["aliases"]}):
151
+ continue
152
+ all_ids = sorted(identities | {other["ruleId"], *other["aliases"]})
153
+ merged.update(
154
+ severity=merge_severity(merged["severity"], other["severity"]),
155
+ ruleId=all_ids[0],
156
+ aliases=all_ids[1:],
157
+ references=sorted(set(merged["references"] + other["references"])),
158
+ evidence=" | ".join(sorted([merged["evidence"], other["evidence"]])),
159
+ )
160
+ groups.pop(index)
161
+ changed = True
162
+ groups.append(merged)
163
+ report["findings"] = sorted(groups, key=lambda f: (f["category"], f["subject"], f["ruleId"]))
164
+ return report