Coverage for scripts/scorecard_pins.py: 100%
216 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""The Scorecard's Pinned-Dependencies rule, offline (V6.6.7, #361): every install in the repo is pinned by hash.
3OpenSSF Scorecard scans every workflow `run:` step, every `*Dockerfile*` and every shell script, and scores the share of
4pinned commands per ecosystem. This mirrors its rules (checks/raw/shell_download_validate.go and the Dockerfile and
5workflow parsers) so a regression fails in CI's fast guards instead of a week later on the Scorecard:
7- pip (`pip`, `pip3`, `python -m pip`, any path ending in them) `install` is pinned with `--require-hashes`, with only
8 `*.whl` arguments, or as `--no-deps -e <local path or git+...@<40 hex>>`; anything else is not;
9- npm: `npm ci` is pinned, `npm install|i|update|install-test` is not;
10- `curl`/`wget` piped into a shell is not;
11- `uses:` must name a 40-hex commit (or `./local`, or `docker://...@sha256:`);
12- `FROM` must carry `@sha256:<64 hex>` (ARG defaults resolved; `scratch` and earlier stage names are fine).
14 python scripts/scorecard_pins.py # exit 1 with one line per unpinned command
15"""
17from __future__ import annotations
19import itertools
20import re
21import shlex
22import subprocess
23import sys
24from collections.abc import Iterable, Sequence
25from dataclasses import dataclass
26from pathlib import Path, PurePosixPath
28import yaml
30ROOT = Path(__file__).resolve().parents[1]
31_FLAG = re.compile(r"^(--?\w+)+$")
32_SHA40 = re.compile(r"^[0-9a-f]{40}$")
33_DIGEST = re.compile(r"@sha256:([0-9a-f]{64}|\$\{.*\})")
34_GIT_EDITABLE = re.compile(r"^git(\+(https?|ssh|git))?://.*(\.git)?@[a-fA-F0-9]{40}(#egg=.*)?$")
35_SEPARATORS = {"&&", "||", ";", "|", "&", "(", ")", "{", "}", "then", "do", "else", "!"}
36_SHELLS = {"sh", "bash", "mksh", "zsh", "dash"}
39@dataclass(frozen=True)
40class Finding:
41 path: str
42 line: int
43 kind: str
44 text: str
46 def __str__(self) -> str:
47 return f"{self.path}:{self.line}: {self.kind}: {self.text}"
50def join_continuations(text: str) -> list[tuple[int, str]]:
51 """Logical lines: a trailing backslash joins the next physical line; the number is the first line's."""
52 out: list[tuple[int, str]] = []
53 buffer, start = "", 0
54 for number, raw in enumerate(text.splitlines(), start=1):
55 if not buffer:
56 start = number
57 stripped = raw.rstrip()
58 if stripped.endswith("\\"):
59 buffer += stripped[:-1] + " "
60 continue
61 out.append((start, buffer + raw))
62 buffer = ""
63 if buffer:
64 out.append((start, buffer))
65 return out
68def _tokens(line: str) -> list[str]:
69 code = line.split(" #", 1)[0] if not line.lstrip().startswith("#") else ""
70 for operator in ("&&", "||", ";", "|", "(", ")"):
71 code = code.replace(operator, f" {operator} ")
72 try:
73 return shlex.split(code, posix=True)
74 except ValueError:
75 return code.split()
78def commands(line: str) -> list[list[str]]:
79 """Simple commands on one logical line, split at shell operators; `sudo`, `env` and `VAR=x` prefixes dropped."""
80 out: list[list[str]] = []
81 current: list[str] = []
82 for token in _tokens(line) + [";"]:
83 if token in _SEPARATORS:
84 if current:
85 out.append(current)
86 current = []
87 continue
88 if not current and (token in {"sudo", "env", "exec", "RUN"} or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", token)):
89 continue
90 current.append(token)
91 return out
94def _base(word: str) -> str:
95 return PurePosixPath(word.replace("\\", "/")).name
98def pip_install_args(argv: Sequence[str]) -> list[str] | None:
99 """The arguments after `install` when `argv` is a pip install, else None."""
100 if not argv:
101 return None
102 head = _base(argv[0])
103 if head in {"pip", "pip3"} and len(argv) > 1 and argv[1] == "install":
104 return list(argv[2:])
105 if re.fullmatch(r"python(3(\.\d+)?|2\.7)?(\.exe)?", head) and list(argv[1:4]) == ["-m", "pip", "install"]:
106 return list(argv[4:])
107 return None
110def is_pinned_pip(args: Sequence[str]) -> bool:
111 """Scorecard's isUnpinnedPipInstall, negated, over the arguments after `install`."""
112 has_require_hashes = has_additional = has_wheel = has_no_deps = False
113 editable_pinned: bool | None = None
114 index = 0
115 while index < len(args):
116 arg = args[index]
117 if arg == "--require-hashes":
118 has_require_hashes = True
119 break
120 if arg == "--no-deps":
121 has_no_deps = True
122 elif arg in {"-e", "--editable"}:
123 source = args[index + 1] if index + 1 < len(args) else ""
124 editable_pinned = bool(source) and ("://" not in source or bool(_GIT_EDITABLE.match(source)))
125 index += 2
126 continue
127 elif _FLAG.match(arg):
128 pass
129 elif arg.endswith(".whl"):
130 has_wheel = True
131 else:
132 has_additional = True
133 index += 1
134 if editable_pinned is not None:
135 return has_no_deps and editable_pinned and not has_additional
136 if has_require_hashes:
137 return True
138 if has_additional:
139 return False
140 return has_wheel
143def is_pinned_npm(argv: Sequence[str]) -> bool | None:
144 """None when `argv` is no npm download; True for `npm ci`; False for install, i, update and install-test."""
145 if len(argv) < 2 or _base(argv[0]) != "npm":
146 return None
147 verb = argv[1]
148 if verb == "ci":
149 return True
150 if verb in {"install", "i", "install-test", "update"}:
151 return False
152 return None
155def shell_findings(path: str, text: str) -> list[Finding]:
156 found: list[Finding] = []
157 for number, line in join_continuations(text):
158 parts = commands(line)
159 for argv in parts:
160 pip_args = pip_install_args(argv)
161 if pip_args is not None and not is_pinned_pip(pip_args):
162 found.append(Finding(path, number, "pip", " ".join(argv)))
163 if is_pinned_npm(argv) is False:
164 found.append(Finding(path, number, "npm", " ".join(argv)))
165 found += _pipe_to_shell(path, number, line)
166 return found
169def _pipe_to_shell(path: str, number: int, line: str) -> list[Finding]:
170 segments = [segment.split() for segment in re.split(r"(?<!\|)\|(?!\|)", line)]
171 for left, right in itertools.pairwise(segments):
172 fetches = bool(left) and _base(left[0]) in {"curl", "wget"}
173 runs = [word for word in right if word != "sudo"][:1]
174 if fetches and runs and _base(runs[0]) in _SHELLS:
175 return [Finding(path, number, "download-pipe-shell", line.strip())]
176 return []
179def workflow_findings(path: str, text: str) -> list[Finding]:
180 found: list[Finding] = []
181 lines = text.splitlines()
182 for number, line in enumerate(lines, start=1):
183 match = re.match(r"^\s*-?\s*uses:\s*['\"]?([^'\"\s#]+)", line)
184 if not match:
185 continue
186 ref = match.group(1)
187 if ref.startswith("./") or (ref.startswith("docker://") and _DIGEST.search(ref)):
188 continue
189 if "@" not in ref or not _SHA40.match(ref.rsplit("@", 1)[1]):
190 found.append(Finding(path, number, "action", ref))
191 document = yaml.safe_load(text) or {}
192 for job in (document.get("jobs") or {}).values():
193 for step in (job or {}).get("steps") or []:
194 run = (step or {}).get("run")
195 if not isinstance(run, str):
196 continue
197 offset = _line_of(lines, run)
198 found += [Finding(path, offset + item.line - 1, item.kind, item.text) for item in shell_findings(path, run)]
199 return found
202def _line_of(lines: list[str], run: str) -> int:
203 first = next((line.strip() for line in run.splitlines() if line.strip()), "")
204 return next((number for number, line in enumerate(lines, start=1) if first and first in line), 1)
207def dockerfile_findings(path: str, text: str) -> list[Finding]:
208 found: list[Finding] = []
209 args: dict[str, str] = {}
210 stages: set[str] = set()
211 for number, line in join_continuations(text):
212 words = line.split()
213 if not words or words[0].startswith("#"):
214 continue
215 keyword = words[0].upper()
216 if keyword == "ARG" and len(words) > 1 and "=" in words[1]:
217 name, value = words[1].split("=", 1)
218 args[name] = value.strip("\"'")
219 elif keyword == "FROM":
220 rest = [word for word in words[1:] if not word.startswith("--")]
221 image = re.sub(r"\$\{?(\w+)\}?", lambda m: args.get(m.group(1), m.group(0)), rest[0]) if rest else ""
222 if len(rest) >= 3 and rest[1].upper() == "AS":
223 stages.add(rest[2].lower())
224 if image.lower() != "scratch" and image.lower() not in stages and not _DIGEST.search(image):
225 found.append(Finding(path, number, "image", image))
226 elif keyword == "RUN":
227 found += [Finding(path, number, item.kind, item.text) for item in shell_findings(path, " ".join(words[1:]))]
228 return found
231def is_shell_script(path: str, first_line: str) -> bool:
232 if PurePosixPath(path).suffix in {".sh", ".bash", ".mksh"}:
233 return True
234 match = re.match(r"^#!\s*(\S+)(?:\s+(\S+))?", first_line)
235 if not match:
236 return False
237 interpreter = _base(match.group(1))
238 if interpreter == "env" and match.group(2):
239 interpreter = _base(match.group(2))
240 return interpreter in {"sh", "bash", "mksh"}
243def is_dockerfile(path: str) -> bool:
244 name = PurePosixPath(path).name.lower()
245 return "dockerfile" in name and PurePosixPath(path).suffix not in {".py", ".sh", ".md", ".yml", ".yaml", ".json", ".txt"}
248def tracked(root: Path = ROOT) -> list[str]:
249 """Every file git would commit: tracked, plus new files not ignored (so a pin is checked before its first commit)."""
250 output = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard"], cwd=root, capture_output=True, text=True, check=True, timeout=60).stdout
251 return [line for line in output.splitlines() if line]
254def scan(root: Path = ROOT, paths: Iterable[str] | None = None) -> list[Finding]:
255 found: list[Finding] = []
256 for path in paths if paths is not None else tracked(root):
257 full = root / path
258 if not full.is_file() or full.stat().st_size > 2_000_000:
259 continue
260 posix = PurePosixPath(path)
261 if posix.parts[:2] == (".github", "workflows") and posix.suffix in {".yml", ".yaml"}:
262 found += workflow_findings(path, full.read_text(encoding="utf-8"))
263 elif is_dockerfile(path):
264 found += dockerfile_findings(path, full.read_text(encoding="utf-8"))
265 elif posix.suffix in {"", ".sh", ".bash", ".mksh"}:
266 text = full.read_text(encoding="utf-8", errors="replace")
267 if is_shell_script(path, text.split("\n", 1)[0]):
268 found += shell_findings(path, text)
269 return found
272def main(argv: Sequence[str] | None = None) -> int:
273 findings = scan()
274 for finding in findings:
275 print(finding)
276 print(f"{len(findings)} unpinned dependency command(s)", file=sys.stderr if findings else sys.stdout)
277 return 1 if findings else 0
280if __name__ == "__main__":
281 raise SystemExit(main(sys.argv[1:]))