patchlint 0.1.0__tar.gz → 0.2.0__tar.gz

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.
Files changed (58) hide show
  1. {patchlint-0.1.0 → patchlint-0.2.0}/CHANGELOG.md +11 -1
  2. {patchlint-0.1.0 → patchlint-0.2.0}/PKG-INFO +12 -3
  3. {patchlint-0.1.0 → patchlint-0.2.0}/README.md +11 -2
  4. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/__init__.py +1 -1
  5. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/cli.py +2 -1
  6. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/core/model.py +5 -2
  7. patchlint-0.2.0/src/patchlint/core/registry.py +87 -0
  8. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/core/runner.py +18 -6
  9. patchlint-0.2.0/src/patchlint/parsers/compose.py +39 -0
  10. patchlint-0.2.0/src/patchlint/rules/compose/DC001_privileged_container.py +32 -0
  11. patchlint-0.2.0/src/patchlint/rules/compose/DC002_docker_socket_mounted.py +35 -0
  12. patchlint-0.2.0/src/patchlint/rules/github_actions/__init__.py +0 -0
  13. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/scaffold.py +23 -2
  14. patchlint-0.2.0/tests/fixtures/DC001/bad/compose.yml +4 -0
  15. patchlint-0.2.0/tests/fixtures/DC001/good/compose.yml +8 -0
  16. patchlint-0.2.0/tests/fixtures/DC002/bad/compose.yml +12 -0
  17. patchlint-0.2.0/tests/fixtures/DC002/good/compose.yml +10 -0
  18. patchlint-0.2.0/tests/test_compose.py +63 -0
  19. patchlint-0.2.0/tests/test_plugins.py +105 -0
  20. patchlint-0.1.0/src/patchlint/core/registry.py +0 -48
  21. {patchlint-0.1.0 → patchlint-0.2.0}/.gitignore +0 -0
  22. {patchlint-0.1.0 → patchlint-0.2.0}/LICENSE +0 -0
  23. {patchlint-0.1.0 → patchlint-0.2.0}/pyproject.toml +0 -0
  24. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/config.py +0 -0
  25. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/core/__init__.py +0 -0
  26. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/parsers/__init__.py +0 -0
  27. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/parsers/dockerfile.py +0 -0
  28. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/parsers/github_actions.py +0 -0
  29. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/__init__.py +0 -0
  30. {patchlint-0.1.0/src/patchlint/rules/dockerfile → patchlint-0.2.0/src/patchlint/rules/compose}/__init__.py +0 -0
  31. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/dockerfile/DL001_root_user.py +0 -0
  32. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/dockerfile/DL002_unpinned_base_image.py +0 -0
  33. {patchlint-0.1.0/src/patchlint/rules/github_actions → patchlint-0.2.0/src/patchlint/rules/dockerfile}/__init__.py +0 -0
  34. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/github_actions/GA001_unpinned_action.py +0 -0
  35. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/github_actions/GA002_script_injection.py +0 -0
  36. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/github_actions/GA003_missing_permissions.py +0 -0
  37. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/github_actions/GA004_pull_request_target_checkout.py +0 -0
  38. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/rules/github_actions/GA008_secrets_inherit.py +0 -0
  39. {patchlint-0.1.0 → patchlint-0.2.0}/src/patchlint/sarif.py +0 -0
  40. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/DL001/bad/Dockerfile +0 -0
  41. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/DL001/good/Dockerfile +0 -0
  42. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/DL002/bad/Dockerfile +0 -0
  43. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/DL002/good/Dockerfile +0 -0
  44. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA001/bad/workflow.yml +0 -0
  45. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA001/good/workflow.yml +0 -0
  46. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA002/bad/workflow.yml +0 -0
  47. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA002/good/workflow.yml +0 -0
  48. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA003/bad/workflow.yml +0 -0
  49. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA003/good/workflow.yml +0 -0
  50. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA004/bad/workflow.yml +0 -0
  51. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA004/good/workflow.yml +0 -0
  52. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA008/bad/workflow.yml +0 -0
  53. {patchlint-0.1.0 → patchlint-0.2.0}/tests/fixtures/GA008/good/workflow.yml +0 -0
  54. {patchlint-0.1.0 → patchlint-0.2.0}/tests/test_config.py +0 -0
  55. {patchlint-0.1.0 → patchlint-0.2.0}/tests/test_github_actions.py +0 -0
  56. {patchlint-0.1.0 → patchlint-0.2.0}/tests/test_parser_cli.py +0 -0
  57. {patchlint-0.1.0 → patchlint-0.2.0}/tests/test_rules.py +0 -0
  58. {patchlint-0.1.0 → patchlint-0.2.0}/tests/test_sarif.py +0 -0
@@ -4,6 +4,15 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.2.0] - 2026-11-25
8
+
9
+ ### Added
10
+ - **docker-compose support:** `compose.yml`, `docker-compose.yml` and variants like `docker-compose.prod.yml` are scanned anywhere in the tree.
11
+ - `DC001` service runs in privileged mode
12
+ - `DC002` Docker socket mounted into a service
13
+ - `patchlint new-rule DC0xx` scaffold and `iter_services()` / `volume_sources()` helpers for compose rules.
14
+ - **Rule plugins:** packages can add rules through the `patchlint.rules` entry point; `list-rules` marks them, and a broken or clashing plugin is skipped with a warning ([docs/plugins.md](docs/plugins.md)).
15
+
7
16
  ## [0.1.0] - 2026-11-25
8
17
 
9
18
  First public release.
@@ -22,5 +31,6 @@ First public release.
22
31
  - Configuration in `.patchlint.toml` or `[tool.patchlint]`: `disable`, `exclude` and per-rule `[severity]`, with strict validation.
23
32
  - `patchlint new-rule` scaffold for contributors; fixture-driven tests need no test code per rule.
24
33
 
25
- [Unreleased]: https://github.com/RubahAnomali/patchlint/compare/v0.1.0...HEAD
34
+ [Unreleased]: https://github.com/RubahAnomali/patchlint/compare/v0.2.0...HEAD
35
+ [0.2.0]: https://github.com/RubahAnomali/patchlint/compare/v0.1.0...v0.2.0
26
36
  [0.1.0]: https://github.com/RubahAnomali/patchlint/releases/tag/v0.1.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: patchlint
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: A beginner-friendly security linter for Dockerfiles and GitHub Actions workflows. Every finding explains why and how to fix it.
5
5
  Project-URL: Homepage, https://github.com/RubahAnomali/patchlint
6
6
  Project-URL: Issues, https://github.com/RubahAnomali/patchlint/issues
@@ -35,17 +35,20 @@ Description-Content-Type: text/markdown
35
35
 
36
36
  A small, beginner-friendly security linter for config files. Every finding tells you **why** it matters and **how to fix it**.
37
37
 
38
- > Status: early (v0.1 in progress). Supports **Dockerfiles** and **GitHub Actions workflows**; docker-compose is on the [roadmap](ROADMAP.md).
38
+ [![PyPI](https://img.shields.io/pypi/v/patchlint)](https://pypi.org/project/patchlint/) [![CI](https://github.com/RubahAnomali/patchlint/actions/workflows/ci.yml/badge.svg)](https://github.com/RubahAnomali/patchlint/actions/workflows/ci.yml)
39
+
40
+ > Status: early (v0.2.0). Supports **Dockerfiles**, **GitHub Actions workflows** and **docker-compose files**. See the [roadmap](ROADMAP.md).
39
41
 
40
42
  | Files | Found by a directory scan | Rule prefix |
41
43
  |---|---|---|
42
44
  | Dockerfiles | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `DL` |
43
45
  | GitHub Actions workflows | `.github/workflows/*.yml` / `*.yaml` | `GA` |
46
+ | docker-compose files | `compose.yml`, `docker-compose.yml`, `docker-compose.*.yml` (any folder) | `DC` |
44
47
 
45
48
  ## Install and try
46
49
 
47
50
  ```bash
48
- pip install patchlint # once published; for now: pip install -e ".[dev]"
51
+ pip install patchlint
49
52
  patchlint scan .
50
53
  patchlint list-rules
51
54
  patchlint explain DL001
@@ -119,6 +122,10 @@ jobs:
119
122
 
120
123
  Code scanning is free for public repositories. The actions are pinned to commit SHAs, which is what rule GA001 asks for.
121
124
 
125
+ ## Rule plugins
126
+
127
+ Company- or project-specific rules can live in their own package and are loaded automatically through the `patchlint.rules` entry point. See [docs/plugins.md](docs/plugins.md).
128
+
122
129
  ## Contribute in 30 minutes
123
130
 
124
131
  Each rule is one small file. Pick an issue labelled
@@ -128,6 +135,7 @@ Each rule is one small file. Pick an issue labelled
128
135
  pip install -e ".[dev]"
129
136
  patchlint new-rule DL003 add_instead_of_copy # Dockerfile rule + fixtures
130
137
  patchlint new-rule GA003 missing_permissions # GitHub Actions rule + fixtures
138
+ patchlint new-rule DC003 host_network # docker-compose rule + fixtures
131
139
  # edit the rule, edit the two fixtures, then:
132
140
  pytest
133
141
  ```
@@ -140,6 +148,7 @@ Full walkthrough: [CONTRIBUTING.md](CONTRIBUTING.md).
140
148
  src/patchlint/
141
149
  rules/dockerfile/ one file per Dockerfile rule (DL001_root_user.py ...)
142
150
  rules/github_actions/ one file per workflow rule (GA001_unpinned_action.py ...)
151
+ rules/compose/ one file per docker-compose rule (DC001_privileged_container.py ...)
143
152
  parsers/ file-format parsers
144
153
  core/ rule registry, runner, data types
145
154
  tests/fixtures/<ID>/{bad,good}/ one file in each; every rule needs both
@@ -2,17 +2,20 @@
2
2
 
3
3
  A small, beginner-friendly security linter for config files. Every finding tells you **why** it matters and **how to fix it**.
4
4
 
5
- > Status: early (v0.1 in progress). Supports **Dockerfiles** and **GitHub Actions workflows**; docker-compose is on the [roadmap](ROADMAP.md).
5
+ [![PyPI](https://img.shields.io/pypi/v/patchlint)](https://pypi.org/project/patchlint/) [![CI](https://github.com/RubahAnomali/patchlint/actions/workflows/ci.yml/badge.svg)](https://github.com/RubahAnomali/patchlint/actions/workflows/ci.yml)
6
+
7
+ > Status: early (v0.2.0). Supports **Dockerfiles**, **GitHub Actions workflows** and **docker-compose files**. See the [roadmap](ROADMAP.md).
6
8
 
7
9
  | Files | Found by a directory scan | Rule prefix |
8
10
  |---|---|---|
9
11
  | Dockerfiles | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `DL` |
10
12
  | GitHub Actions workflows | `.github/workflows/*.yml` / `*.yaml` | `GA` |
13
+ | docker-compose files | `compose.yml`, `docker-compose.yml`, `docker-compose.*.yml` (any folder) | `DC` |
11
14
 
12
15
  ## Install and try
13
16
 
14
17
  ```bash
15
- pip install patchlint # once published; for now: pip install -e ".[dev]"
18
+ pip install patchlint
16
19
  patchlint scan .
17
20
  patchlint list-rules
18
21
  patchlint explain DL001
@@ -86,6 +89,10 @@ jobs:
86
89
 
87
90
  Code scanning is free for public repositories. The actions are pinned to commit SHAs, which is what rule GA001 asks for.
88
91
 
92
+ ## Rule plugins
93
+
94
+ Company- or project-specific rules can live in their own package and are loaded automatically through the `patchlint.rules` entry point. See [docs/plugins.md](docs/plugins.md).
95
+
89
96
  ## Contribute in 30 minutes
90
97
 
91
98
  Each rule is one small file. Pick an issue labelled
@@ -95,6 +102,7 @@ Each rule is one small file. Pick an issue labelled
95
102
  pip install -e ".[dev]"
96
103
  patchlint new-rule DL003 add_instead_of_copy # Dockerfile rule + fixtures
97
104
  patchlint new-rule GA003 missing_permissions # GitHub Actions rule + fixtures
105
+ patchlint new-rule DC003 host_network # docker-compose rule + fixtures
98
106
  # edit the rule, edit the two fixtures, then:
99
107
  pytest
100
108
  ```
@@ -107,6 +115,7 @@ Full walkthrough: [CONTRIBUTING.md](CONTRIBUTING.md).
107
115
  src/patchlint/
108
116
  rules/dockerfile/ one file per Dockerfile rule (DL001_root_user.py ...)
109
117
  rules/github_actions/ one file per workflow rule (GA001_unpinned_action.py ...)
118
+ rules/compose/ one file per docker-compose rule (DC001_privileged_container.py ...)
110
119
  parsers/ file-format parsers
111
120
  core/ rule registry, runner, data types
112
121
  tests/fixtures/<ID>/{bad,good}/ one file in each; every rule needs both
@@ -1,3 +1,3 @@
1
1
  """patchlint: a beginner-friendly security linter for config files."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.2.0"
@@ -50,7 +50,8 @@ def main(argv: list[str] | None = None) -> int:
50
50
 
51
51
  if args.cmd == "list-rules":
52
52
  for r in load_rules().values():
53
- print(f"{r.id} {r.severity:<6} {r.title}")
53
+ source = "" if r.origin == "patchlint" else f" [plugin: {r.origin}]"
54
+ print(f"{r.id} {r.severity:<6} {r.title}{source}")
54
55
  return 0
55
56
 
56
57
  if args.cmd == "explain":
@@ -9,7 +9,7 @@ from pathlib import Path
9
9
  from patchlint.parsers.github_actions import YMap
10
10
 
11
11
  SEVERITIES = ("low", "medium", "high")
12
- FILETYPES = ("dockerfile", "workflow")
12
+ FILETYPES = ("dockerfile", "workflow", "compose")
13
13
 
14
14
 
15
15
  @dataclass(frozen=True)
@@ -35,13 +35,15 @@ class Finding:
35
35
  class Context:
36
36
  """What a rule's ``check`` function receives.
37
37
 
38
- Dockerfile rules use ``instructions``; workflow rules use ``workflow``.
38
+ Dockerfile rules use ``instructions``; workflow rules use ``workflow``;
39
+ docker-compose rules use ``compose``.
39
40
  ``lines`` is the raw file text, one entry per line.
40
41
  """
41
42
 
42
43
  path: Path
43
44
  instructions: tuple[Instruction, ...]
44
45
  workflow: YMap | None
46
+ compose: YMap | None
45
47
  lines: tuple[str, ...]
46
48
  _rule_id: str
47
49
  _severity: str
@@ -68,6 +70,7 @@ class Rule:
68
70
  cwe: int | None
69
71
  filetype: str
70
72
  check: CheckFn
73
+ origin: str = "patchlint" # the package that provides the rule (plugins set their own)
71
74
 
72
75
  @property
73
76
  def doc(self) -> str:
@@ -0,0 +1,87 @@
1
+ """Rule registry: the ``@rule`` decorator, built-in rule discovery and rule plugins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import importlib.metadata
7
+ import pkgutil
8
+ import sys
9
+ from collections.abc import Callable, Iterable
10
+ from dataclasses import replace
11
+ from typing import Any
12
+
13
+ from patchlint.core.model import SEVERITIES, CheckFn, Rule
14
+
15
+ RULES: dict[str, Rule] = {}
16
+
17
+ # The rule id prefix decides which files a rule runs on.
18
+ PREFIX_FILETYPES = {"DL": "dockerfile", "GA": "workflow", "DC": "compose"}
19
+
20
+ # Third-party packages register rule modules under this entry point group:
21
+ # [project.entry-points."patchlint.rules"]
22
+ # acme = "acme_patchlint_rules"
23
+ PLUGIN_GROUP = "patchlint.rules"
24
+ _plugins_loaded = False
25
+
26
+
27
+ def rule(
28
+ id: str, title: str, severity: str, cwe: int | None = None
29
+ ) -> Callable[[CheckFn], CheckFn]:
30
+ """Register a check function as a rule.
31
+
32
+ The function's docstring is the rule's documentation: explain *why* the
33
+ pattern is dangerous and *how* to fix it.
34
+ """
35
+ if severity not in SEVERITIES:
36
+ raise ValueError(f"severity must be one of {SEVERITIES}, got {severity!r}")
37
+ filetype = PREFIX_FILETYPES.get(id[:2])
38
+ if filetype is None:
39
+ raise ValueError(f"rule id {id!r} must start with one of {sorted(PREFIX_FILETYPES)}")
40
+
41
+ def decorator(fn: CheckFn) -> CheckFn:
42
+ if id in RULES:
43
+ raise ValueError(f"duplicate rule id {id}")
44
+ RULES[id] = Rule(
45
+ id=id, title=title, severity=severity, cwe=cwe, filetype=filetype, check=fn
46
+ )
47
+ return fn
48
+
49
+ return decorator
50
+
51
+
52
+ def _plugin_entry_points() -> Iterable[Any]:
53
+ return importlib.metadata.entry_points(group=PLUGIN_GROUP)
54
+
55
+
56
+ def _load_plugins() -> None:
57
+ """Import every installed rule plugin once.
58
+
59
+ A broken plugin prints a warning and is skipped, so it can never stop a scan
60
+ or replace a built-in rule.
61
+ """
62
+ for ep in _plugin_entry_points():
63
+ before = set(RULES)
64
+ try:
65
+ ep.load()
66
+ except Exception as exc: # any failure inside third-party code
67
+ for rule_id in set(RULES) - before:
68
+ del RULES[rule_id] # don't keep half a plugin
69
+ print(f"warning: rule plugin {ep.name!r} failed to load: {exc}", file=sys.stderr)
70
+ continue
71
+ dist = getattr(ep, "dist", None)
72
+ origin = getattr(dist, "name", None) or ep.name
73
+ for rule_id in set(RULES) - before:
74
+ RULES[rule_id] = replace(RULES[rule_id], origin=origin)
75
+
76
+
77
+ def load_rules() -> dict[str, Rule]:
78
+ """Import every built-in rule module, then installed plugins (once)."""
79
+ global _plugins_loaded
80
+ import patchlint.rules as rules_pkg
81
+
82
+ for mod in pkgutil.walk_packages(rules_pkg.__path__, prefix="patchlint.rules."):
83
+ importlib.import_module(mod.name)
84
+ if not _plugins_loaded:
85
+ _plugins_loaded = True
86
+ _load_plugins()
87
+ return RULES
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  import sys
6
7
  from collections.abc import Iterable, Iterator
7
8
  from pathlib import Path
@@ -23,17 +24,23 @@ NOT_DOCKERFILE = {
23
24
  ".md", ".rst", ".txt", ".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".lock",
24
25
  }
25
26
 
27
+ # compose.yml, docker-compose.yaml, docker-compose.prod.yml, compose.override.yaml ...
28
+ COMPOSE_NAME = re.compile(r"(docker-)?compose(\.[\w-]+)?\.ya?ml")
29
+
26
30
 
27
31
  def file_kind(path: Path, explicit: bool = False) -> str | None:
28
- """Return "dockerfile", "workflow" or None.
32
+ """Return "dockerfile", "workflow", "compose" or None.
29
33
 
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.
34
+ Compose files are recognised by name anywhere. Other YAML only counts inside
35
+ `.github/workflows/` in a directory scan; a YAML file named directly on the
36
+ command line is treated as a workflow.
32
37
  """
33
38
  name = path.name.lower()
34
39
  variant = name.startswith("dockerfile.") and path.suffix.lower() not in NOT_DOCKERFILE
35
40
  if name == "dockerfile" or variant or name.endswith(".dockerfile"):
36
41
  return "dockerfile"
42
+ if COMPOSE_NAME.fullmatch(name):
43
+ return "compose"
37
44
  if path.suffix.lower() in (".yml", ".yaml"):
38
45
  parts = [p.lower() for p in path.parts]
39
46
  in_workflows = len(parts) >= 3 and parts[-3] == ".github" and parts[-2] == "workflows"
@@ -75,22 +82,27 @@ def scan(
75
82
  text = path.read_text(encoding="utf-8", errors="replace")
76
83
  instructions: tuple[Instruction, ...] = ()
77
84
  workflow: YMap | None = None
85
+ compose: YMap | None = None
78
86
  if kind == "dockerfile":
79
87
  instructions = dockerfile.parse(text)
80
88
  else:
81
89
  try:
82
- workflow = github_actions.parse(text)
90
+ document = github_actions.parse(text) # line-aware safe YAML
83
91
  except yaml.YAMLError as exc:
84
92
  print(f"warning: skipping {path}: invalid YAML ({exc})", file=sys.stderr)
85
93
  continue
86
- if workflow is None:
94
+ if document is None:
87
95
  continue
96
+ if kind == "workflow":
97
+ workflow = document
98
+ else:
99
+ compose = document
88
100
  lines = tuple(text.splitlines())
89
101
  for r in rules.values():
90
102
  if r.id not in selected or r.filetype != kind:
91
103
  continue
92
104
  severity = config.severity.get(r.id, r.severity)
93
- ctx = Context(path, instructions, workflow, lines, r.id, severity)
105
+ ctx = Context(path, instructions, workflow, compose, lines, r.id, severity)
94
106
  findings.extend(r.check(ctx))
95
107
  findings.sort(key=lambda f: (f.path, f.line, f.rule_id))
96
108
  return findings
@@ -0,0 +1,39 @@
1
+ """docker-compose helpers. Files are parsed by the same line-aware safe YAML loader
2
+ as workflows (see `github_actions.parse`); this module adds compose-specific helpers."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Iterator
7
+
8
+ from patchlint.parsers.github_actions import YList, YMap
9
+
10
+
11
+ def iter_services(compose: YMap) -> Iterator[tuple[str, YMap]]:
12
+ """Yield (service_name, service) for every service in a compose file."""
13
+ services = compose.get("services")
14
+ if isinstance(services, YMap):
15
+ for name, service in services.items():
16
+ if isinstance(service, YMap):
17
+ yield name, service
18
+
19
+
20
+ def volume_sources(service: YMap) -> Iterator[str]:
21
+ """Yield the host side of every volume, for both short and long syntax.
22
+
23
+ Short: `- /var/run/docker.sock:/var/run/docker.sock:ro` -> `/var/run/docker.sock`
24
+ Long: `- {type: bind, source: ./data, target: /data}` -> `./data`
25
+ """
26
+ volumes = service.get("volumes")
27
+ if not isinstance(volumes, YList):
28
+ return
29
+ for entry in volumes:
30
+ if isinstance(entry, str):
31
+ # Split on ":" but keep Windows drive letters like C:\\data intact.
32
+ head, sep, _rest = entry.partition(":")
33
+ if sep and len(head) == 1 and head.isalpha():
34
+ drive_rest = _rest.partition(":")[0]
35
+ yield f"{head}:{drive_rest}"
36
+ elif sep:
37
+ yield head
38
+ elif isinstance(entry, YMap) and isinstance(entry.get("source"), str):
39
+ yield entry["source"]
@@ -0,0 +1,32 @@
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.compose import iter_services
8
+
9
+
10
+ @rule(id="DC001", title="Service runs in privileged mode", severity="high", cwe=250)
11
+ def check(ctx: Context) -> Iterable[Finding]:
12
+ """A compose service sets `privileged: true`.
13
+
14
+ Why it matters: a privileged container gets every Linux capability and access
15
+ to the host's devices. Code that breaks out of the app (or is injected into it)
16
+ effectively has root on the host, so container isolation is gone.
17
+
18
+ Fix: remove `privileged: true` and add only the specific capability the
19
+ service needs, if any:
20
+
21
+ cap_add:
22
+ - NET_ADMIN
23
+ """
24
+ if ctx.compose is None:
25
+ return
26
+ for name, service in iter_services(ctx.compose):
27
+ if service.get("privileged") is True:
28
+ yield ctx.finding(
29
+ service.key_lines["privileged"],
30
+ f"Service `{name}` runs privileged, with full access to the host.",
31
+ "Remove `privileged: true`; use `cap_add` for the one capability you need.",
32
+ )
@@ -0,0 +1,35 @@
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.compose import iter_services, volume_sources
8
+
9
+ SOCKETS = ("/var/run/docker.sock", "/run/docker.sock", "//./pipe/docker_engine")
10
+
11
+
12
+ @rule(id="DC002", title="Docker socket mounted into a service", severity="high", cwe=250)
13
+ def check(ctx: Context) -> Iterable[Finding]:
14
+ """A compose service mounts the Docker socket (`/var/run/docker.sock`).
15
+
16
+ Why it matters: whoever can talk to the Docker socket controls the Docker
17
+ daemon, and can start a privileged container that mounts the host's root
18
+ filesystem. Mounting it, even read-only, gives the service root on the host.
19
+
20
+ Fix: don't mount the socket. If a tool truly needs the Docker API, put a
21
+ filtering proxy (for example a socket proxy that only allows the API calls it
22
+ needs) in between, and never expose it to an internet-facing service.
23
+ """
24
+ if ctx.compose is None:
25
+ return
26
+ for name, service in iter_services(ctx.compose):
27
+ start = service.key_lines.get("volumes", service.line)
28
+ for source in volume_sources(service):
29
+ if source.rstrip("/") in SOCKETS:
30
+ yield ctx.finding(
31
+ ctx.line_of("docker", start) if "docker" in source else start,
32
+ f"Service `{name}` mounts the Docker socket `{source}`, "
33
+ "which gives it control of the host.",
34
+ "Remove the socket mount, or use a filtering socket proxy instead.",
35
+ )
@@ -44,6 +44,19 @@ def check(ctx: Context) -> Iterable[Finding]:
44
44
  yield ctx.finding(step.line, "What is wrong.", "How to fix it.")
45
45
  '''
46
46
 
47
+ COMPOSE_BODY = '''from patchlint.parsers.compose import iter_services
48
+
49
+
50
+ @rule(id="{id}", title="{title}", severity="medium", cwe=None)
51
+ def check(ctx: Context) -> Iterable[Finding]:
52
+ {doc}
53
+ if ctx.compose is None:
54
+ return
55
+ for _name, service in iter_services(ctx.compose):
56
+ if False: # TODO: replace with your real condition
57
+ yield ctx.finding(service.line, "What is wrong.", "How to fix it.")
58
+ '''
59
+
47
60
 
48
61
  @dataclass(frozen=True)
49
62
  class Kind:
@@ -62,12 +75,20 @@ KINDS = {
62
75
  " steps:\n - run: echo hello\n",
63
76
  WORKFLOW_BODY,
64
77
  ),
78
+ "DC": Kind(
79
+ "compose",
80
+ "compose.yml",
81
+ "services:\n web:\n image: nginx:1.27\n",
82
+ COMPOSE_BODY,
83
+ ),
65
84
  }
66
85
 
67
86
 
68
87
  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)")
88
+ if not re.fullmatch(r"(DL|GA|DC)\d{3}", rule_id):
89
+ raise ValueError(
90
+ "rule id must look like DL003 (Dockerfile), GA003 (GitHub Actions) or DC003 (compose)"
91
+ )
71
92
  if not re.fullmatch(r"[a-z0-9_]+", slug):
72
93
  raise ValueError("name must be lower_snake_case, e.g. add_instead_of_copy")
73
94
  kind = KINDS[rule_id[:2]]
@@ -0,0 +1,4 @@
1
+ services:
2
+ monitor:
3
+ image: example/monitor:2.1
4
+ privileged: true
@@ -0,0 +1,8 @@
1
+ services:
2
+ monitor:
3
+ image: example/monitor:2.1
4
+ privileged: false
5
+ cap_add:
6
+ - NET_ADMIN
7
+ web:
8
+ image: nginx:1.27
@@ -0,0 +1,12 @@
1
+ services:
2
+ dashboard:
3
+ image: example/dashboard:1.0
4
+ volumes:
5
+ - ./config:/config:ro
6
+ - /var/run/docker.sock:/var/run/docker.sock:ro
7
+ agent:
8
+ image: example/agent:1.0
9
+ volumes:
10
+ - type: bind
11
+ source: /var/run/docker.sock
12
+ target: /var/run/docker.sock
@@ -0,0 +1,10 @@
1
+ services:
2
+ app:
3
+ image: example/app:1.0
4
+ volumes:
5
+ - ./data:/data
6
+ - type: volume
7
+ source: cache
8
+ target: /cache
9
+ volumes:
10
+ cache: {}
@@ -0,0 +1,63 @@
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+ from patchlint.cli import main
6
+ from patchlint.core.runner import file_kind, scan
7
+ from patchlint.parsers.compose import iter_services, volume_sources
8
+ from patchlint.parsers.github_actions import parse
9
+
10
+ FIXTURES = Path(__file__).parent / "fixtures"
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ "name",
15
+ ["compose.yml", "compose.yaml", "docker-compose.yml", "docker-compose.prod.yaml",
16
+ "compose.override.yml", "Docker-Compose.YML"],
17
+ )
18
+ def test_compose_files_are_detected_anywhere(name: str) -> None:
19
+ assert file_kind(Path("any/folder") / name) == "compose"
20
+
21
+
22
+ @pytest.mark.parametrize("name", ["composer.yml", "my-compose.yml", "compose.json"])
23
+ def test_other_files_are_not_compose(name: str) -> None:
24
+ assert file_kind(Path("any/folder") / name) != "compose"
25
+
26
+
27
+ def test_volume_sources_short_long_and_windows() -> None:
28
+ doc = parse(
29
+ "services:\n a:\n volumes:\n"
30
+ " - /var/run/docker.sock:/var/run/docker.sock:ro\n"
31
+ " - C:\\data:/data\n"
32
+ " - named_volume_only\n"
33
+ " - type: bind\n source: ./src\n target: /app\n"
34
+ )
35
+ assert doc is not None
36
+ (_, service), = iter_services(doc)
37
+ assert list(volume_sources(service)) == ["/var/run/docker.sock", "C:\\data", "./src"]
38
+
39
+
40
+ def test_dc002_flags_short_and_long_syntax_on_the_right_lines() -> None:
41
+ findings = scan(FIXTURES / "DC002" / "bad" / "compose.yml", only=["DC002"])
42
+ assert [(f.line, "dashboard" in f.message) for f in findings] == [(6, True), (11, False)]
43
+
44
+
45
+ def test_dc001_points_at_privileged_line() -> None:
46
+ (finding,) = scan(FIXTURES / "DC001" / "bad" / "compose.yml", only=["DC001"])
47
+ assert finding.line == 4
48
+
49
+
50
+ def test_directory_scan_finds_compose_files(tmp_path: Path) -> None:
51
+ (tmp_path / "deploy").mkdir()
52
+ (tmp_path / "deploy" / "docker-compose.prod.yml").write_text(
53
+ "services:\n x:\n image: a:1\n privileged: true\n", encoding="utf-8"
54
+ )
55
+ assert [f.rule_id for f in scan(tmp_path)] == ["DC001"]
56
+
57
+
58
+ def test_new_compose_rule_scaffold(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
59
+ monkeypatch.chdir(tmp_path)
60
+ assert main(["new-rule", "DC999", "demo_rule"]) == 0
61
+ rule_file = tmp_path / "src/patchlint/rules/compose/DC999_demo_rule.py"
62
+ assert "iter_services" in rule_file.read_text(encoding="utf-8")
63
+ assert (tmp_path / "tests/fixtures/DC999/good/compose.yml").is_file()
@@ -0,0 +1,105 @@
1
+ """Rule plugins: packages that add rules through the `patchlint.rules` entry point."""
2
+
3
+ from collections.abc import Callable, Iterable, Iterator
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ from typing import Any
7
+
8
+ import pytest
9
+
10
+ from patchlint.cli import main
11
+ from patchlint.core import registry
12
+ from patchlint.core.model import Context, Finding
13
+ from patchlint.core.registry import load_rules, rule
14
+ from patchlint.core.runner import scan
15
+
16
+
17
+ class FakeEntryPoint:
18
+ def __init__(self, name: str, loader: Callable[[], None], dist: str | None = None) -> None:
19
+ self.name = name
20
+ self._loader = loader
21
+ self.dist = SimpleNamespace(name=dist) if dist else None
22
+
23
+ def load(self) -> None:
24
+ self._loader()
25
+
26
+
27
+ @pytest.fixture
28
+ def plugins(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[..., None]]:
29
+ """Install fake plugins for one test, then restore the registry."""
30
+ load_rules() # built-ins first
31
+ saved = dict(registry.RULES)
32
+
33
+ def install(*eps: Any) -> None:
34
+ monkeypatch.setattr(registry, "_plugin_entry_points", lambda: list(eps))
35
+ monkeypatch.setattr(registry, "_plugins_loaded", False)
36
+
37
+ yield install
38
+ registry.RULES.clear()
39
+ registry.RULES.update(saved)
40
+ registry._plugins_loaded = True
41
+
42
+
43
+ def acme_rules() -> None:
44
+ @rule(id="DL-acme-1", title="No EXPOSE 8080", severity="low")
45
+ def check(ctx: Context) -> Iterable[Finding]:
46
+ """Flags EXPOSE 8080.
47
+
48
+ Why it matters: example plugin rule.
49
+
50
+ Fix: use another port.
51
+ """
52
+ for ins in ctx.instructions:
53
+ if ins.cmd == "EXPOSE" and "8080" in ins.args:
54
+ yield ctx.finding(ins.line, "Port 8080 exposed.", "Use another port.")
55
+
56
+
57
+ def test_plugin_rules_load_and_run(plugins: Callable[..., None], tmp_path: Path) -> None:
58
+ plugins(FakeEntryPoint("acme", acme_rules, dist="acme-patchlint-rules"))
59
+ rules = load_rules()
60
+ assert rules["DL-acme-1"].origin == "acme-patchlint-rules"
61
+ assert rules["DL001"].origin == "patchlint"
62
+ dockerfile = tmp_path / "Dockerfile"
63
+ dockerfile.write_text("FROM python:3.12-slim\nUSER app\nEXPOSE 8080\n", encoding="utf-8")
64
+ assert [f.rule_id for f in scan(dockerfile)] == ["DL-acme-1"]
65
+
66
+
67
+ def test_list_rules_marks_plugin_rules(
68
+ plugins: Callable[..., None], capsys: pytest.CaptureFixture[str]
69
+ ) -> None:
70
+ plugins(FakeEntryPoint("acme", acme_rules, dist="acme-patchlint-rules"))
71
+ assert main(["list-rules"]) == 0
72
+ out = capsys.readouterr().out
73
+ assert "DL-acme-1" in out and "[plugin: acme-patchlint-rules]" in out
74
+
75
+
76
+ def test_broken_plugin_is_skipped_with_warning(
77
+ plugins: Callable[..., None], capsys: pytest.CaptureFixture[str]
78
+ ) -> None:
79
+ def broken() -> None:
80
+ @rule(id="DL-broken-1", title="Half registered", severity="low")
81
+ def check(ctx: Context) -> Iterable[Finding]:
82
+ return []
83
+
84
+ raise ImportError("missing dependency")
85
+
86
+ plugins(FakeEntryPoint("broken", broken), FakeEntryPoint("acme", acme_rules))
87
+ rules = load_rules()
88
+ assert "DL-broken-1" not in rules # no half-loaded plugin
89
+ assert "DL-acme-1" in rules # other plugins still load
90
+ assert "rule plugin 'broken' failed to load: missing dependency" in capsys.readouterr().err
91
+
92
+
93
+ def test_plugin_cannot_replace_a_builtin_rule(
94
+ plugins: Callable[..., None], capsys: pytest.CaptureFixture[str]
95
+ ) -> None:
96
+ def hijack() -> None:
97
+ @rule(id="DL001", title="Fake", severity="low")
98
+ def check(ctx: Context) -> Iterable[Finding]:
99
+ return []
100
+
101
+ plugins(FakeEntryPoint("hijack", hijack))
102
+ rules = load_rules()
103
+ assert rules["DL001"].title == "Container runs as root"
104
+ assert rules["DL001"].origin == "patchlint"
105
+ assert "duplicate rule id DL001" in capsys.readouterr().err
@@ -1,48 +0,0 @@
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
File without changes
File without changes
File without changes
File without changes
File without changes