lockly 0.1.0__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.
lockly/cli.py ADDED
@@ -0,0 +1,330 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import inspect
7
+ import os
8
+ import re
9
+ import shutil
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from . import __version__, git, parsers
14
+ from .diff import FAIL_ON_CHOICES, Diff, compare_lockfiles, find
15
+ from .model import LockfileError
16
+ from .render import to_json, to_markdown, to_text, use_colour
17
+
18
+ # Exit codes: 0 clean (or nothing gated), 1 a --fail-on category was hit,
19
+ # 2 bad usage, or a lockfile or git ref that can't be read.
20
+ EXIT_OK, EXIT_GATED, EXIT_ERROR = 0, 1, 2
21
+ OFFLINE_ENV = "LOCKLY_OFFLINE"
22
+ REPO = "https://github.com/fullstackspectrum/lockly"
23
+
24
+
25
+ def _fail_on(value: str) -> set[str]:
26
+ kinds = {v.strip().lower() for v in value.split(",") if v.strip()}
27
+ unknown = kinds - set(FAIL_ON_CHOICES)
28
+ if unknown:
29
+ raise argparse.ArgumentTypeError(
30
+ f"unknown category {', '.join(sorted(unknown))} (choose from {', '.join(FAIL_ON_CHOICES)})"
31
+ )
32
+ return kinds
33
+
34
+
35
+ def _days(value: str) -> float:
36
+ try:
37
+ n = float(value)
38
+ except ValueError:
39
+ raise argparse.ArgumentTypeError(f"'{value}' isn't a number of days") from None
40
+ if n < 0:
41
+ raise argparse.ArgumentTypeError("days can't be negative")
42
+ return n
43
+
44
+
45
+ # ── Help ──────────────────────────────────────────────────────────────
46
+
47
+ DIFF_EPILOG = f"""lockfiles:
48
+ package-lock.json npm (also npm-shrinkwrap.json)
49
+ yarn.lock Yarn classic and Berry (reads package.json for direct deps)
50
+ pnpm-lock.yaml pnpm 5.4 to 9
51
+ uv.lock uv
52
+ poetry.lock Poetry (reads pyproject.toml for direct deps)
53
+ Pipfile.lock Pipenv (reads Pipfile for direct deps)
54
+ go.mod Go modules (reads go.sum for hashes); go.sum alone also works
55
+ Cargo.lock Cargo
56
+
57
+ fail-on categories:
58
+ hash same version, different contents: rebuilt, republished or tampered with
59
+ install-script a package now runs a script when it's installed
60
+ publisher published by an account new to the package, or no longer by trusted publishing
61
+ provenance the previous release had a provenance attestation; this one doesn't
62
+ source comes from git, a URL or another registry, or from somewhere new
63
+ new-package the package itself is only days old (--new-package-days)
64
+ young this version is only days old (--min-age)
65
+ vulnerable the new version has known vulnerabilities (OSV)
66
+ deprecated deprecated or yanked
67
+ copyleft brings in copyleft licence terms
68
+ license the licence changed between copyleft and permissive terms
69
+ any all of the above
70
+
71
+ exit codes:
72
+ 0 passed, or nothing in --fail-on occurred
73
+ 1 a --fail-on category occurred
74
+ 2 bad usage, or a lockfile or git ref that can't be read
75
+
76
+ examples:
77
+ $ lockly diff old/package-lock.json package-lock.json
78
+ $ lockly diff --base origin/main # every lockfile changed on this branch
79
+ $ lockly diff --base main --markdown comment.md --html report.html
80
+ $ lockly diff --base main --fail-on install-script,publisher,hash
81
+ $ lockly diff --base main --offline # only what the lockfiles say
82
+ """
83
+
84
+ ROOT_EPILOG = f"""examples:
85
+ $ lockly diff --base origin/main
86
+ $ lockly diff old/uv.lock uv.lock
87
+ $ lockly diff --help # every option for diff
88
+
89
+ docs:
90
+ {REPO}
91
+ """
92
+
93
+ # Brand colours as terminal codes: flags take blue-soft (keys in code),
94
+ # placeholders yellow (strings), headings the // eyebrow.
95
+ _HELP_STYLES = {"flag": "94", "meta": "33", "dim": "2", "bold": "1", "red": "31"}
96
+
97
+
98
+ def _style(code: str, text: str) -> str:
99
+ return f"\033[{_HELP_STYLES[code]}m{text}\033[0m"
100
+
101
+
102
+ def _colourise_help(text: str) -> str:
103
+ out = []
104
+ section = ""
105
+ for line in text.splitlines():
106
+ heading = re.fullmatch(r"([a-z][a-z -]*):", line)
107
+ if heading:
108
+ section = heading.group(1)
109
+ out.append(f"{_style('dim', '//')} {_style('bold', section)}")
110
+ continue
111
+ if line.startswith("usage:"):
112
+ out.append(f"{_style('dim', '//')} {_style('bold', 'usage')}")
113
+ out.append(" " + re.sub(r"\b(lockly(?: diff)?)\b", lambda m: _style("red", m.group(1)),
114
+ line[7:], count=1))
115
+ continue
116
+ if section == "examples" and line.lstrip().startswith("$"):
117
+ cmd, _, comment = line.partition("#")
118
+ cmd = cmd.replace("$", _style("dim", "$"), 1)
119
+ out.append(cmd + (_style("dim", "#" + comment) if comment else ""))
120
+ continue
121
+ if section == "docs":
122
+ out.append(_style("flag", line))
123
+ continue
124
+ m = re.match(r"^( )(\S.*?)(\s{2,}\S.*)?$", line)
125
+ if m and section not in ("", "usage"):
126
+ term = re.sub(r"(?<![\w-])(--?[\w-]+)", lambda x: _style("flag", x.group(1)), m.group(2))
127
+ term = re.sub(r"(?<![\w-])([A-Z]+)\b", lambda x: _style("meta", x.group(1)), term)
128
+ if section in ("fail-on categories", "commands", "exit codes", "lockfiles"):
129
+ term = _style("flag", m.group(2))
130
+ out.append(m.group(1) + term + (m.group(3) or ""))
131
+ continue
132
+ out.append(line)
133
+ return "\n".join(out) + "\n"
134
+
135
+
136
+ class _HelpFormatter(argparse.RawDescriptionHelpFormatter):
137
+ def __init__(self, prog: str) -> None:
138
+ width = min(shutil.get_terminal_size((100, 24)).columns, 100)
139
+ super().__init__(prog, max_help_position=24, width=width)
140
+ # Pin the help column at 24 in every section, so options and the
141
+ # hand-written reference sections in the epilog line up.
142
+ self._action_max_length = 22
143
+
144
+ def _format_action(self, action: argparse.Action) -> str:
145
+ # List subcommands directly under "commands:", without argparse's
146
+ # extra "COMMAND" line above them.
147
+ if isinstance(action, argparse._SubParsersAction):
148
+ return "".join(self._format_action(a) for a in action._get_subactions())
149
+ return super()._format_action(action)
150
+
151
+ def _format_action_invocation(self, action: argparse.Action) -> str:
152
+ # "-p, --platform P" rather than argparse's "-p P, --platform P".
153
+ if not action.option_strings or action.nargs == 0:
154
+ return super()._format_action_invocation(action)
155
+ metavar = self._format_args(action, self._get_default_metavar_for_optional(action))
156
+ return f"{', '.join(action.option_strings)} {metavar}"
157
+
158
+
159
+ class _Parser(argparse.ArgumentParser):
160
+ """ArgumentParser whose help is grouped, wrapped to the terminal and, on a
161
+ colour terminal, styled in the Full-Stack-Spectrum palette."""
162
+
163
+ def __init__(self, *args, **kwargs) -> None:
164
+ kwargs.setdefault("formatter_class", _HelpFormatter)
165
+ kwargs.setdefault("add_help", False)
166
+ # Python 3.14 colours help itself; this parser does its own.
167
+ if "color" in inspect.signature(argparse.ArgumentParser.__init__).parameters:
168
+ kwargs.setdefault("color", False)
169
+ super().__init__(*args, **kwargs)
170
+
171
+ def format_help(self) -> str:
172
+ text = super().format_help()
173
+ return _colourise_help(text) if use_colour() else text
174
+
175
+
176
+ def _help_flag(group) -> None:
177
+ group.add_argument("-h", "--help", action="help", help="show this help and exit")
178
+
179
+
180
+ def build_parser() -> argparse.ArgumentParser:
181
+ parser = _Parser(
182
+ prog="lockly",
183
+ usage="lockly COMMAND [options]",
184
+ description=f"lockly {__version__}: what changed in a lockfile, and what deserves a closer look.",
185
+ epilog=ROOT_EPILOG,
186
+ )
187
+ sub = parser.add_subparsers(dest="command", title="commands", metavar="COMMAND", parser_class=_Parser)
188
+ general = parser.add_argument_group("options")
189
+ _help_flag(general)
190
+ general.add_argument("--version", action="version", version=f"lockly {__version__}",
191
+ help="print the version and exit")
192
+
193
+ d = sub.add_parser(
194
+ "diff",
195
+ help="compare lockfiles: two files, or every lockfile changed since a git ref",
196
+ usage="lockly diff OLD NEW [options]\n lockly diff --base REF [--head REF] [PATH...] [options]",
197
+ description=(
198
+ "Compare two versions of a lockfile: what was added, removed, upgraded or downgraded,\n"
199
+ "and which changes deserve a reviewer's attention: new install scripts, a new publisher,\n"
200
+ "packages days old, changed contents or sources, known vulnerabilities, licence changes.\n"
201
+ "Registry and OSV lookups add the checks a lockfile can't answer alone; --offline skips them."
202
+ ),
203
+ epilog=DIFF_EPILOG,
204
+ )
205
+ inputs = d.add_argument_group("arguments")
206
+ inputs.add_argument("paths", metavar="PATH", nargs="*",
207
+ help="two lockfiles (old, new); with --base, paths to limit the search to")
208
+ inputs.add_argument("-b", "--base", metavar="REF",
209
+ help="compare every lockfile changed since REF (its merge base with --head)")
210
+ inputs.add_argument("--head", metavar="REF",
211
+ help="with --base: the other side (default: the working tree)")
212
+ inputs.add_argument("-t", "--type", metavar="TYPE", default="", choices=parsers.KINDS,
213
+ help=f"lockfile type, for files with other names: {', '.join(parsers.KINDS)}")
214
+
215
+ checks = d.add_argument_group("checks")
216
+ checks.add_argument("--offline", action="store_true",
217
+ help=f"no registry or OSV lookups, only what the lockfiles say (or set {OFFLINE_ENV}=1)")
218
+ checks.add_argument("--min-age", metavar="DAYS", type=_days, default=3.0,
219
+ help="flag versions published less than DAYS ago (default: 3)")
220
+ checks.add_argument("--new-package-days", metavar="DAYS", type=_days, default=30.0,
221
+ help="flag added packages first published less than DAYS ago (default: 30)")
222
+ checks.add_argument("--no-cache", action="store_true",
223
+ help="don't read or write the lookup cache in ~/.cache/lockly")
224
+
225
+ output = d.add_argument_group("output")
226
+ output.add_argument("-f", "--format", choices=("text", "markdown", "json"), default="text",
227
+ metavar="FORMAT", help="what to print: text (default), markdown or json")
228
+ output.add_argument("--html", metavar="FILE", type=Path,
229
+ help="write a self-contained HTML report that works offline")
230
+ output.add_argument("--markdown", metavar="FILE", type=Path,
231
+ help="write Markdown sized for a pull request comment")
232
+ output.add_argument("--json", metavar="FILE", type=Path, help="write everything as JSON")
233
+ output.add_argument("-q", "--quiet", action="store_true", help="print nothing to stdout")
234
+
235
+ gate = d.add_argument_group("ci gating")
236
+ gate.add_argument("--fail-on", metavar="LIST", type=_fail_on, default=set(),
237
+ help="exit 1 if any of these comma-separated categories occur (see below)")
238
+
239
+ display = d.add_argument_group("display")
240
+ display.add_argument("--title", default="", metavar="TEXT", help="title for the HTML and Markdown reports")
241
+ display.add_argument("--theme", choices=("dark", "light"), default="dark", metavar="THEME",
242
+ help="HTML report theme: dark (default) or light")
243
+ display.add_argument("--limit", type=int, default=100, metavar="N",
244
+ help="rows per section in text and Markdown output (default: 100)")
245
+ display.add_argument("--no-color", action="store_true",
246
+ help="plain terminal output; NO_COLOR and FORCE_COLOR are respected too")
247
+ _help_flag(display)
248
+ return parser
249
+
250
+
251
+ def _write(path: Path, content: str) -> None:
252
+ try:
253
+ path.parent.mkdir(parents=True, exist_ok=True)
254
+ path.write_text(content, encoding="utf-8")
255
+ except OSError as exc:
256
+ raise LockfileError(f"{path}: can't write ({exc.strerror})") from None
257
+
258
+
259
+ def _load(args: argparse.Namespace) -> Diff:
260
+ if args.base:
261
+ repo = git.root()
262
+ base = git.merge_base(args.base, args.head, repo)
263
+ cwd = os.path.relpath(os.getcwd(), repo)
264
+ scope = [os.path.normpath(os.path.join(cwd, p)) for p in args.paths] or ([cwd] if cwd != "." else [])
265
+ paths = git.changed_lockfiles(base, args.head, scope, repo)
266
+ return Diff([compare_lockfiles(*git.load_pair(p, base, args.head, repo, args.type)) for p in paths])
267
+ if args.head:
268
+ raise LockfileError("--head needs --base")
269
+ if len(args.paths) != 2:
270
+ raise LockfileError("give two lockfiles to compare, or --base REF to compare against git")
271
+ old, new = (git.load_file(p, args.type) for p in args.paths)
272
+ if old.kind != new.kind:
273
+ raise LockfileError(f"{args.paths[0]} is a {old.kind} lockfile but {args.paths[1]} is a {new.kind} one")
274
+ new.path = args.paths[1]
275
+ return Diff([compare_lockfiles(old, new)])
276
+
277
+
278
+ def run(args: argparse.Namespace) -> int:
279
+ result = _load(args)
280
+ offline = args.offline or bool(os.environ.get(OFFLINE_ENV, "").strip())
281
+ if not offline and result.changes:
282
+ from . import enrich # only pay for the import when looking things up
283
+
284
+ enrich.enrich(result, cache=not args.no_cache)
285
+ elif offline:
286
+ result.notes.append("Registry and OSV lookups were off (--offline): publisher, age, deprecation "
287
+ "and vulnerability checks didn't run.")
288
+ for fd in result.files:
289
+ find(fd, min_age_days=args.min_age, new_package_days=args.new_package_days)
290
+
291
+ colour = use_colour() and not args.no_color
292
+ if args.html:
293
+ from .html import to_html # only pay for loading the fonts when asked
294
+
295
+ _write(args.html, to_html(result, theme=args.theme, title=args.title))
296
+ if args.markdown:
297
+ _write(args.markdown, to_markdown(result, limit=args.limit, title=args.title))
298
+ if args.json:
299
+ _write(args.json, to_json(result, args.fail_on))
300
+
301
+ if not args.quiet:
302
+ if args.format == "json":
303
+ sys.stdout.write(to_json(result, args.fail_on))
304
+ elif args.format == "markdown":
305
+ sys.stdout.write(to_markdown(result, limit=args.limit, title=args.title))
306
+ else:
307
+ sys.stdout.write(to_text(result, colour=colour, limit=args.limit))
308
+
309
+ hits = result.triggered(args.fail_on)
310
+ if hits:
311
+ summary = ", ".join(f"{kind} ({n})" for kind, n in hits.items())
312
+ sys.stdout.flush() # keep the report above the verdict in a terminal
313
+ print(f"lockly: failing because of {summary}", file=sys.stderr)
314
+ return EXIT_GATED
315
+ return EXIT_OK
316
+
317
+
318
+ def main(argv: list[str] | None = None) -> None:
319
+ parser = build_parser()
320
+ args = parser.parse_args(argv)
321
+ if args.command != "diff":
322
+ parser.print_help()
323
+ sys.exit(EXIT_ERROR)
324
+ try:
325
+ sys.exit(run(args))
326
+ except LockfileError as exc:
327
+ print(f"lockly: {exc}", file=sys.stderr)
328
+ sys.exit(EXIT_ERROR)
329
+ except KeyboardInterrupt:
330
+ sys.exit(130)
lockly/cvss.py ADDED
@@ -0,0 +1,229 @@
1
+ """CVSS base scores from a vector string, per the FIRST specifications.
2
+
3
+ 3.x uses the spec's formula. 4.0 is a port of FIRST's reference calculator
4
+ (https://github.com/FIRSTdotorg/cvss-v4-calculator), which scores a vector by
5
+ its MacroVector's looked-up score, adjusted by how far the vector sits below
6
+ that MacroVector's most severe vectors. The port keeps the reference's control
7
+ flow, quirks included, so scores match it exactly.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ from .cvss4_data import LOOKUP, MAX_COMPOSED, MAX_SEVERITY
15
+
16
+ _AV = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}
17
+ _AC = {"L": 0.77, "H": 0.44}
18
+ _PR_UNCHANGED = {"N": 0.85, "L": 0.62, "H": 0.27}
19
+ _PR_CHANGED = {"N": 0.85, "L": 0.68, "H": 0.5}
20
+ _UI = {"N": 0.85, "R": 0.62}
21
+ _CIA = {"H": 0.56, "L": 0.22, "N": 0.0}
22
+
23
+
24
+ def _roundup(value: float) -> float:
25
+ # The spec's Roundup, which avoids floating point surprises like 4.0000001.
26
+ whole = round(value * 100000)
27
+ return whole / 100000.0 if whole % 10000 == 0 else (math.floor(whole / 10000) + 1) / 10.0
28
+
29
+
30
+ def base_score(vector: str) -> float | None:
31
+ if not vector.startswith("CVSS:3."):
32
+ return None
33
+ try:
34
+ m = dict(part.split(":", 1) for part in vector.split("/")[1:])
35
+ changed = m["S"] == "C"
36
+ iss = 1 - (1 - _CIA[m["C"]]) * (1 - _CIA[m["I"]]) * (1 - _CIA[m["A"]])
37
+ impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss
38
+ pr = (_PR_CHANGED if changed else _PR_UNCHANGED)[m["PR"]]
39
+ exploitability = 8.22 * _AV[m["AV"]] * _AC[m["AC"]] * pr * _UI[m["UI"]]
40
+ except (KeyError, ValueError):
41
+ return None
42
+ if impact <= 0:
43
+ return 0.0
44
+ if changed:
45
+ return _roundup(min(1.08 * (impact + exploitability), 10))
46
+ return _roundup(min(impact + exploitability, 10))
47
+
48
+
49
+ def score(vector: str) -> float | None:
50
+ """Base score for a CVSS 3.x or 4.0 vector, or None if it can't be read."""
51
+ if vector.startswith("CVSS:4.0/"):
52
+ return base_score_v4(vector)
53
+ return base_score(vector)
54
+
55
+
56
+ # ── CVSS 4.0 ─────────────────────────────────────────────────────────
57
+
58
+ _V4_REQUIRED = ("AV", "AC", "AT", "PR", "UI", "VC", "VI", "VA", "SC", "SI", "SA")
59
+ _V4_LEVELS = {
60
+ "AV": {"N": 0.0, "A": 0.1, "L": 0.2, "P": 0.3},
61
+ "PR": {"N": 0.0, "L": 0.1, "H": 0.2},
62
+ "UI": {"N": 0.0, "P": 0.1, "A": 0.2},
63
+ "AC": {"L": 0.0, "H": 0.1},
64
+ "AT": {"N": 0.0, "P": 0.1},
65
+ "VC": {"H": 0.0, "L": 0.1, "N": 0.2},
66
+ "VI": {"H": 0.0, "L": 0.1, "N": 0.2},
67
+ "VA": {"H": 0.0, "L": 0.1, "N": 0.2},
68
+ "SC": {"H": 0.1, "L": 0.2, "N": 0.3},
69
+ "SI": {"S": 0.0, "H": 0.1, "L": 0.2, "N": 0.3},
70
+ "SA": {"S": 0.0, "H": 0.1, "L": 0.2, "N": 0.3},
71
+ "CR": {"H": 0.0, "M": 0.1, "L": 0.2},
72
+ "IR": {"H": 0.0, "M": 0.1, "L": 0.2},
73
+ "AR": {"H": 0.0, "M": 0.1, "L": 0.2},
74
+ }
75
+ _DISTANCE_ORDER = ("AV", "PR", "UI", "AC", "AT", "VC", "VI", "VA", "SC", "SI", "SA", "CR", "IR", "AR")
76
+
77
+
78
+ def _v4_metric(selected: dict[str, str], metric: str) -> str:
79
+ value = selected.get(metric, "X")
80
+ # Unset threat and requirement metrics default to the worst case.
81
+ if metric == "E" and value == "X":
82
+ return "A"
83
+ if metric in ("CR", "IR", "AR") and value == "X":
84
+ return "H"
85
+ # Environmental M* metrics override the base value when set.
86
+ modified = selected.get("M" + metric, "X")
87
+ if modified != "X":
88
+ return modified
89
+ return value
90
+
91
+
92
+ def _v4_macro_vector(sel: dict[str, str]) -> str:
93
+ m = lambda k: _v4_metric(sel, k) # noqa: E731
94
+
95
+ if m("AV") == "N" and m("PR") == "N" and m("UI") == "N":
96
+ eq1 = "0"
97
+ elif (m("AV") == "N" or m("PR") == "N" or m("UI") == "N") and m("AV") != "P":
98
+ eq1 = "1"
99
+ else:
100
+ eq1 = "2"
101
+
102
+ eq2 = "0" if m("AC") == "L" and m("AT") == "N" else "1"
103
+
104
+ if m("VC") == "H" and m("VI") == "H":
105
+ eq3 = "0"
106
+ elif m("VC") == "H" or m("VI") == "H" or m("VA") == "H":
107
+ eq3 = "1"
108
+ else:
109
+ eq3 = "2"
110
+
111
+ if m("MSI") == "S" or m("MSA") == "S":
112
+ eq4 = "0"
113
+ elif m("SC") == "H" or m("SI") == "H" or m("SA") == "H":
114
+ eq4 = "1"
115
+ else:
116
+ eq4 = "2"
117
+
118
+ eq5 = {"A": "0", "P": "1", "U": "2"}[m("E")]
119
+
120
+ high = ((m("CR") == "H" and m("VC") == "H") or (m("IR") == "H" and m("VI") == "H")
121
+ or (m("AR") == "H" and m("VA") == "H"))
122
+ eq6 = "0" if high else "1"
123
+ return eq1 + eq2 + eq3 + eq4 + eq5 + eq6
124
+
125
+
126
+ def _extract(metric: str, partial: str) -> str:
127
+ rest = partial[partial.index(metric) + len(metric) + 1:]
128
+ return rest.split("/", 1)[0]
129
+
130
+
131
+ def base_score_v4(vector: str) -> float | None:
132
+ try:
133
+ parts = vector.split("/")
134
+ if parts[0] != "CVSS:4.0":
135
+ return None
136
+ sel = dict(p.split(":", 1) for p in parts[1:])
137
+ if any(k not in sel for k in _V4_REQUIRED):
138
+ return None
139
+ macro = _v4_macro_vector(sel)
140
+ except (ValueError, KeyError):
141
+ return None
142
+ if any(_v4_metric(sel, k) not in _V4_LEVELS[k] for k in _DISTANCE_ORDER):
143
+ return None
144
+
145
+ if all(_v4_metric(sel, k) == "N" for k in ("VC", "VI", "VA", "SC", "SI", "SA")):
146
+ return 0.0
147
+
148
+ value = LOOKUP.get(macro)
149
+ if value is None:
150
+ return None
151
+ eq1, eq2, eq3, eq4, eq5, eq6 = (int(c) for c in macro)
152
+
153
+ def at(*digits: int) -> float | None:
154
+ return LOOKUP.get("".join(str(d) for d in digits))
155
+
156
+ lower_eq1 = at(eq1 + 1, eq2, eq3, eq4, eq5, eq6)
157
+ lower_eq2 = at(eq1, eq2 + 1, eq3, eq4, eq5, eq6)
158
+ if eq3 == 1 and eq6 == 1:
159
+ lower_eq3eq6 = at(eq1, eq2, eq3 + 1, eq4, eq5, eq6)
160
+ elif eq3 == 0 and eq6 == 1:
161
+ lower_eq3eq6 = at(eq1, eq2, eq3 + 1, eq4, eq5, eq6)
162
+ elif eq3 == 1 and eq6 == 0:
163
+ lower_eq3eq6 = at(eq1, eq2, eq3, eq4, eq5, eq6 + 1)
164
+ elif eq3 == 0 and eq6 == 0:
165
+ # Two ways down; take the higher score. A missing one loses, as in JS.
166
+ left, right = at(eq1, eq2, eq3, eq4, eq5, eq6 + 1), at(eq1, eq2, eq3 + 1, eq4, eq5, eq6)
167
+ lower_eq3eq6 = left if (left is not None and right is not None and left > right) else right
168
+ else:
169
+ lower_eq3eq6 = at(eq1, eq2, eq3 + 1, eq4, eq5, eq6 + 1)
170
+ lower_eq4 = at(eq1, eq2, eq3, eq4 + 1, eq5, eq6)
171
+ lower_eq5 = at(eq1, eq2, eq3, eq4, eq5 + 1, eq6)
172
+
173
+ maxes = [a + b + c + d + e
174
+ for a in MAX_COMPOSED["eq1"][eq1]
175
+ for b in MAX_COMPOSED["eq2"][eq2]
176
+ for c in MAX_COMPOSED["eq3"][eq3][str(eq6)]
177
+ for d in MAX_COMPOSED["eq4"][eq4]
178
+ for e in MAX_COMPOSED["eq5"][eq5]]
179
+
180
+ distance: dict[str, float] = {}
181
+ for max_vector in maxes:
182
+ distance = {k: _V4_LEVELS[k][_v4_metric(sel, k)] - _V4_LEVELS[k][_extract(k, max_vector)]
183
+ for k in _DISTANCE_ORDER}
184
+ # The first max vector the scored vector doesn't exceed anywhere. If
185
+ # none qualifies, the reference keeps the last one's distances.
186
+ if all(d >= 0 for d in distance.values()):
187
+ break
188
+
189
+ current = {
190
+ "eq1": distance["AV"] + distance["PR"] + distance["UI"],
191
+ "eq2": distance["AC"] + distance["AT"],
192
+ "eq3eq6": (distance["VC"] + distance["VI"] + distance["VA"]
193
+ + distance["CR"] + distance["IR"] + distance["AR"]),
194
+ "eq4": distance["SC"] + distance["SI"] + distance["SA"],
195
+ }
196
+ step = 0.1
197
+ depth = {
198
+ "eq1": MAX_SEVERITY["eq1"][eq1] * step,
199
+ "eq2": MAX_SEVERITY["eq2"][eq2] * step,
200
+ "eq3eq6": MAX_SEVERITY["eq3eq6"][eq3][eq6] * step,
201
+ "eq4": MAX_SEVERITY["eq4"][eq4] * step,
202
+ }
203
+
204
+ total, existing = 0.0, 0
205
+ for name, lower in (("eq1", lower_eq1), ("eq2", lower_eq2), ("eq3eq6", lower_eq3eq6), ("eq4", lower_eq4)):
206
+ if lower is not None:
207
+ existing += 1
208
+ total += (value - lower) * (current[name] / depth[name])
209
+ if lower_eq5 is not None:
210
+ existing += 1 # EQ5's proportion is always 0, but it still counts
211
+
212
+ mean = total / existing if existing else 0.0
213
+ value = min(max(value - mean, 0.0), 10.0)
214
+ # JS Math.round: halves round up, unlike Python's round().
215
+ return math.floor(value * 10 + 0.5) / 10
216
+
217
+
218
+ def severity(score: float | None) -> str:
219
+ if score is None:
220
+ return "unknown"
221
+ if score >= 9.0:
222
+ return "critical"
223
+ if score >= 7.0:
224
+ return "high"
225
+ if score >= 4.0:
226
+ return "medium"
227
+ if score > 0:
228
+ return "low"
229
+ return "unknown"
lockly/cvss4_data.py ADDED
@@ -0,0 +1,101 @@
1
+ """Data tables for CVSS 4.0 scoring, from FIRST's reference calculator
2
+ (https://github.com/FIRSTdotorg/cvss-v4-calculator: cvss_lookup.js,
3
+ max_composed.js and max_severity.js).
4
+
5
+ Copyright (c) 2023 FIRST.ORG, Inc., Red Hat, and contributors
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are met:
9
+
10
+ 1. Redistributions of source code must retain the above copyright notice, this
11
+ list of conditions and the following disclaimer.
12
+
13
+ 2. Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+ """
28
+
29
+ # Score of the highest-severity vector in each MacroVector (EQ1..EQ6).
30
+ LOOKUP: dict[str, float] = {
31
+ "000000": 10, "000001": 9.9, "000010": 9.8, "000011": 9.5, "000020": 9.5, "000021": 9.2,
32
+ "000100": 10, "000101": 9.6, "000110": 9.3, "000111": 8.7, "000120": 9.1, "000121": 8.1,
33
+ "000200": 9.3, "000201": 9, "000210": 8.9, "000211": 8, "000220": 8.1, "000221": 6.8,
34
+ "001000": 9.8, "001001": 9.5, "001010": 9.5, "001011": 9.2, "001020": 9, "001021": 8.4,
35
+ "001100": 9.3, "001101": 9.2, "001110": 8.9, "001111": 8.1, "001120": 8.1, "001121": 6.5,
36
+ "001200": 8.8, "001201": 8, "001210": 7.8, "001211": 7, "001220": 6.9, "001221": 4.8,
37
+ "002001": 9.2, "002011": 8.2, "002021": 7.2, "002101": 7.9, "002111": 6.9, "002121": 5,
38
+ "002201": 6.9, "002211": 5.5, "002221": 2.7, "010000": 9.9, "010001": 9.7, "010010": 9.5,
39
+ "010011": 9.2, "010020": 9.2, "010021": 8.5, "010100": 9.5, "010101": 9.1, "010110": 9,
40
+ "010111": 8.3, "010120": 8.4, "010121": 7.1, "010200": 9.2, "010201": 8.1, "010210": 8.2,
41
+ "010211": 7.1, "010220": 7.2, "010221": 5.3, "011000": 9.5, "011001": 9.3, "011010": 9.2,
42
+ "011011": 8.5, "011020": 8.5, "011021": 7.3, "011100": 9.2, "011101": 8.2, "011110": 8,
43
+ "011111": 7.2, "011120": 7, "011121": 5.9, "011200": 8.4, "011201": 7, "011210": 7.1,
44
+ "011211": 5.2, "011220": 5, "011221": 3, "012001": 8.6, "012011": 7.5, "012021": 5.2,
45
+ "012101": 7.1, "012111": 5.2, "012121": 2.9, "012201": 6.3, "012211": 2.9, "012221": 1.7,
46
+ "100000": 9.8, "100001": 9.5, "100010": 9.4, "100011": 8.7, "100020": 9.1, "100021": 8.1,
47
+ "100100": 9.4, "100101": 8.9, "100110": 8.6, "100111": 7.4, "100120": 7.7, "100121": 6.4,
48
+ "100200": 8.7, "100201": 7.5, "100210": 7.4, "100211": 6.3, "100220": 6.3, "100221": 4.9,
49
+ "101000": 9.4, "101001": 8.9, "101010": 8.8, "101011": 7.7, "101020": 7.6, "101021": 6.7,
50
+ "101100": 8.6, "101101": 7.6, "101110": 7.4, "101111": 5.8, "101120": 5.9, "101121": 5,
51
+ "101200": 7.2, "101201": 5.7, "101210": 5.7, "101211": 5.2, "101220": 5.2, "101221": 2.5,
52
+ "102001": 8.3, "102011": 7, "102021": 5.4, "102101": 6.5, "102111": 5.8, "102121": 2.6,
53
+ "102201": 5.3, "102211": 2.1, "102221": 1.3, "110000": 9.5, "110001": 9, "110010": 8.8,
54
+ "110011": 7.6, "110020": 7.6, "110021": 7, "110100": 9, "110101": 7.7, "110110": 7.5,
55
+ "110111": 6.2, "110120": 6.1, "110121": 5.3, "110200": 7.7, "110201": 6.6, "110210": 6.8,
56
+ "110211": 5.9, "110220": 5.2, "110221": 3, "111000": 8.9, "111001": 7.8, "111010": 7.6,
57
+ "111011": 6.7, "111020": 6.2, "111021": 5.8, "111100": 7.4, "111101": 5.9, "111110": 5.7,
58
+ "111111": 5.7, "111120": 4.7, "111121": 2.3, "111200": 6.1, "111201": 5.2, "111210": 5.7,
59
+ "111211": 2.9, "111220": 2.4, "111221": 1.6, "112001": 7.1, "112011": 5.9, "112021": 3,
60
+ "112101": 5.8, "112111": 2.6, "112121": 1.5, "112201": 2.3, "112211": 1.3, "112221": 0.6,
61
+ "200000": 9.3, "200001": 8.7, "200010": 8.6, "200011": 7.2, "200020": 7.5, "200021": 5.8,
62
+ "200100": 8.6, "200101": 7.4, "200110": 7.4, "200111": 6.1, "200120": 5.6, "200121": 3.4,
63
+ "200200": 7, "200201": 5.4, "200210": 5.2, "200211": 4, "200220": 4, "200221": 2.2,
64
+ "201000": 8.5, "201001": 7.5, "201010": 7.4, "201011": 5.5, "201020": 6.2, "201021": 5.1,
65
+ "201100": 7.2, "201101": 5.7, "201110": 5.5, "201111": 4.1, "201120": 4.6, "201121": 1.9,
66
+ "201200": 5.3, "201201": 3.6, "201210": 3.4, "201211": 1.9, "201220": 1.9, "201221": 0.8,
67
+ "202001": 6.4, "202011": 5.1, "202021": 2, "202101": 4.7, "202111": 2.1, "202121": 1.1,
68
+ "202201": 2.4, "202211": 0.9, "202221": 0.4, "210000": 8.8, "210001": 7.5, "210010": 7.3,
69
+ "210011": 5.3, "210020": 6, "210021": 5, "210100": 7.3, "210101": 5.5, "210110": 5.9,
70
+ "210111": 4, "210120": 4.1, "210121": 2, "210200": 5.4, "210201": 4.3, "210210": 4.5,
71
+ "210211": 2.2, "210220": 2, "210221": 1.1, "211000": 7.5, "211001": 5.5, "211010": 5.8,
72
+ "211011": 4.5, "211020": 4, "211021": 2.1, "211100": 6.1, "211101": 5.1, "211110": 4.8,
73
+ "211111": 1.8, "211120": 2, "211121": 0.9, "211200": 4.6, "211201": 1.8, "211210": 1.7,
74
+ "211211": 0.7, "211220": 0.8, "211221": 0.2, "212001": 5.3, "212011": 2.4, "212021": 1.4,
75
+ "212101": 2.4, "212111": 1.2, "212121": 0.5, "212201": 1, "212211": 0.3, "212221": 0.1,
76
+ }
77
+
78
+ # The highest-severity vectors within each EQ level, as partial vector strings.
79
+ MAX_COMPOSED: dict = {
80
+ "eq1": {0: ["AV:N/PR:N/UI:N/"],
81
+ 1: ["AV:A/PR:N/UI:N/", "AV:N/PR:L/UI:N/", "AV:N/PR:N/UI:P/"],
82
+ 2: ["AV:P/PR:N/UI:N/", "AV:A/PR:L/UI:P/"]},
83
+ "eq2": {0: ["AC:L/AT:N/"], 1: ["AC:H/AT:N/", "AC:L/AT:P/"]},
84
+ "eq3": {0: {"0": ["VC:H/VI:H/VA:H/CR:H/IR:H/AR:H/"],
85
+ "1": ["VC:H/VI:H/VA:L/CR:M/IR:M/AR:H/", "VC:H/VI:H/VA:H/CR:M/IR:M/AR:M/"]},
86
+ 1: {"0": ["VC:L/VI:H/VA:H/CR:H/IR:H/AR:H/", "VC:H/VI:L/VA:H/CR:H/IR:H/AR:H/"],
87
+ "1": ["VC:L/VI:H/VA:L/CR:H/IR:M/AR:H/", "VC:L/VI:H/VA:H/CR:H/IR:M/AR:M/",
88
+ "VC:H/VI:L/VA:H/CR:M/IR:H/AR:M/", "VC:H/VI:L/VA:L/CR:M/IR:H/AR:H/",
89
+ "VC:L/VI:L/VA:H/CR:H/IR:H/AR:M/"]},
90
+ 2: {"1": ["VC:L/VI:L/VA:L/CR:H/IR:H/AR:H/"]}},
91
+ "eq4": {0: ["SC:H/SI:S/SA:S/"], 1: ["SC:H/SI:H/SA:H/"], 2: ["SC:L/SI:L/SA:L/"]},
92
+ "eq5": {0: ["E:A/"], 1: ["E:P/"], 2: ["E:U/"]},
93
+ }
94
+
95
+ # Severity depth of each EQ level, plus one.
96
+ MAX_SEVERITY: dict = {
97
+ "eq1": {0: 1, 1: 4, 2: 5},
98
+ "eq2": {0: 1, 1: 2},
99
+ "eq3eq6": {0: {0: 7, 1: 6}, 1: {0: 8, 1: 8}, 2: {1: 10}},
100
+ "eq4": {0: 6, 1: 5, 2: 4},
101
+ }