coldrun 0.1.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 (72) hide show
  1. coldrun-0.1.0/.gitignore +21 -0
  2. coldrun-0.1.0/CHANGELOG.md +37 -0
  3. coldrun-0.1.0/LICENSE +21 -0
  4. coldrun-0.1.0/PKG-INFO +53 -0
  5. coldrun-0.1.0/README.md +23 -0
  6. coldrun-0.1.0/packaging/README.md +1 -0
  7. coldrun-0.1.0/pyproject.toml +151 -0
  8. coldrun-0.1.0/rules/README.md +1 -0
  9. coldrun-0.1.0/src/coldrun/__init__.py +12 -0
  10. coldrun-0.1.0/src/coldrun/cli.py +53 -0
  11. coldrun-0.1.0/src/coldrun/config.py +29 -0
  12. coldrun-0.1.0/src/coldrun/detect.py +223 -0
  13. coldrun-0.1.0/src/coldrun/doctor.py +208 -0
  14. coldrun-0.1.0/src/coldrun/fetch/__init__.py +82 -0
  15. coldrun-0.1.0/src/coldrun/fetch/base.py +137 -0
  16. coldrun-0.1.0/src/coldrun/fetch/local.py +46 -0
  17. coldrun-0.1.0/src/coldrun/fetch/url.py +136 -0
  18. coldrun-0.1.0/src/coldrun/pipeline.py +1 -0
  19. coldrun-0.1.0/src/coldrun/py.typed +0 -0
  20. coldrun-0.1.0/src/coldrun/report.py +195 -0
  21. coldrun-0.1.0/src/coldrun/runners/__init__.py +15 -0
  22. coldrun-0.1.0/src/coldrun/runners/base.py +97 -0
  23. coldrun-0.1.0/src/coldrun/runners/registry.py +125 -0
  24. coldrun-0.1.0/src/coldrun/sandbox/__init__.py +29 -0
  25. coldrun-0.1.0/src/coldrun/sandbox/base.py +219 -0
  26. coldrun-0.1.0/src/coldrun/sandbox/bwrap.py +226 -0
  27. coldrun-0.1.0/src/coldrun/vet/__init__.py +1 -0
  28. coldrun-0.1.0/src/coldrun/vet/findings.py +66 -0
  29. coldrun-0.1.0/tests/__init__.py +0 -0
  30. coldrun-0.1.0/tests/fixtures/README.md +1 -0
  31. coldrun-0.1.0/tests/fixtures/detect/empty +0 -0
  32. coldrun-0.1.0/tests/fixtures/detect/env_s.py +4 -0
  33. coldrun-0.1.0/tests/fixtures/detect/fake.exe +1 -0
  34. coldrun-0.1.0/tests/fixtures/detect/fake.gz +1 -0
  35. coldrun-0.1.0/tests/fixtures/detect/fake.zip +1 -0
  36. coldrun-0.1.0/tests/fixtures/detect/fake_elf.bin +0 -0
  37. coldrun-0.1.0/tests/fixtures/detect/hello.c +2 -0
  38. coldrun-0.1.0/tests/fixtures/detect/hello.go +2 -0
  39. coldrun-0.1.0/tests/fixtures/detect/hello.js +2 -0
  40. coldrun-0.1.0/tests/fixtures/detect/hello.php +1 -0
  41. coldrun-0.1.0/tests/fixtures/detect/hello.pl +2 -0
  42. coldrun-0.1.0/tests/fixtures/detect/hello.ps1 +1 -0
  43. coldrun-0.1.0/tests/fixtures/detect/hello.py +4 -0
  44. coldrun-0.1.0/tests/fixtures/detect/hello.rb +2 -0
  45. coldrun-0.1.0/tests/fixtures/detect/hello.sh +2 -0
  46. coldrun-0.1.0/tests/fixtures/detect/noshebang.py +3 -0
  47. coldrun-0.1.0/tests/fixtures/detect/random.bin +3 -0
  48. coldrun-0.1.0/tests/fixtures/detect/shebang_only +1 -0
  49. coldrun-0.1.0/tests/fixtures/detect/utf8.txt +1 -0
  50. coldrun-0.1.0/tests/fixtures/sh/hello.sh +2 -0
  51. coldrun-0.1.0/tests/integration/__init__.py +0 -0
  52. coldrun-0.1.0/tests/integration/test_bwrap_backend.py +142 -0
  53. coldrun-0.1.0/tests/integration/test_bwrap_smoke.py +80 -0
  54. coldrun-0.1.0/tests/unit/__init__.py +0 -0
  55. coldrun-0.1.0/tests/unit/fetch/__init__.py +0 -0
  56. coldrun-0.1.0/tests/unit/fetch/conftest.py +63 -0
  57. coldrun-0.1.0/tests/unit/fetch/test_local.py +140 -0
  58. coldrun-0.1.0/tests/unit/fetch/test_url.py +113 -0
  59. coldrun-0.1.0/tests/unit/runners/__init__.py +0 -0
  60. coldrun-0.1.0/tests/unit/runners/contract.py +91 -0
  61. coldrun-0.1.0/tests/unit/runners/fake_runner.py +57 -0
  62. coldrun-0.1.0/tests/unit/runners/test_fake_runner_contract.py +19 -0
  63. coldrun-0.1.0/tests/unit/runners/test_registry.py +97 -0
  64. coldrun-0.1.0/tests/unit/sandbox/__init__.py +0 -0
  65. coldrun-0.1.0/tests/unit/sandbox/test_bwrap_command.py +244 -0
  66. coldrun-0.1.0/tests/unit/sandbox/test_policy.py +119 -0
  67. coldrun-0.1.0/tests/unit/test_cli.py +27 -0
  68. coldrun-0.1.0/tests/unit/test_config.py +23 -0
  69. coldrun-0.1.0/tests/unit/test_detect.py +187 -0
  70. coldrun-0.1.0/tests/unit/test_doctor.py +113 -0
  71. coldrun-0.1.0/tests/unit/test_findings.py +49 -0
  72. coldrun-0.1.0/tests/unit/test_report.py +160 -0
@@ -0,0 +1,21 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ .python-version
9
+
10
+ # Tooling
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+ .pytest_cache/
14
+ .coverage
15
+ .coverage.*
16
+ coverage.xml
17
+ htmlcov/
18
+ site/
19
+
20
+ # coldrun
21
+ coldrun-out/
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ - `coldrun doctor`: checks Python, bubblewrap, unprivileged user namespaces, TIOCSTI, podman, uv and the cache directory, prints pass/warn/fail with the exact fix, exits 1 on failures (#14).
13
+ - Report layer: `Report` model filled in as the pipeline advances, a Rich summary of source, runner, dependencies, findings by severity, sandbox and network policy, what was blocked, files written and the exit code; errors always print what failed and `next:` what to try; `ExitCode` 100/101/102 (#13).
14
+ - Bubblewrap sandbox backend and the policy model behind every backend: new user, PID, mount, IPC, UTS and network namespaces, no capabilities, `no_new_privs`, read-only `/usr`, private tmpfs `/tmp` and `/run`, scratch directory at `/work`, script mounted read-only, synthetic `/etc/passwd`, resolver and CA files only when network is allowed, environment cleared to an allowlist, `--rw` refused for `/`, `$HOME` and credential directories, TIOCSTI-aware TTY passthrough, and a probe that reports bubblewrap's own error with a `coldrun doctor` hint (#12).
15
+ - Type detection: shared shebang, extension and file-magic signals (`detect.py`), every registered runner scores the file, the best above 0.5 wins, ties and low confidence produce an error naming the candidates and `--lang`; `--lang` forces a runner (#10).
16
+ - Fetch step: local file and http(s) URL fetchers place the source in a private 0700 quarantine directory under `~/.cache/coldrun/quarantine/` with a `source.json` (origin, SHA-256, size, time). 64 MiB size cap, redirects limited to http(s), GitHub `blob` URLs rewritten to raw. XDG-aware config and cache paths in `config.py` (#9).
17
+ - `Runner` protocol, `DepSet` and `Finding` models, and an entry-point registry (`coldrun.runners` group) that loads built-in and third-party runners, skips broken plugins with a logged reason, and a shared contract test suite in `tests/unit/runners/contract.py` (#11).
18
+
19
+ ### Changed
20
+
21
+ - **Breaking:** the project is renamed from `muzzle` to `coldrun`: package, console script, entry-point group `coldrun.runners`, config path `~/.config/coldrun/` and cache path `~/.cache/coldrun/` (#50). The PyPI name `muzzle` belongs to another maintainer; `coldrun` is free everywhere.
22
+
23
+ ## [0.1.0] - 2026-11-12
24
+
25
+ Foundation release (published under the former name `muzzle`): an empty `muzzle --version` that passes every check on a pull request. No fetching, vetting or sandboxing yet; that starts in M1.
26
+
27
+ ### Added
28
+
29
+ - Package scaffold with the spec layout and `muzzle --version` (#1, #2).
30
+ - Ruff lint and format, mypy strict and pre-commit hooks including a secrets scan and a Conventional Commits check (#3).
31
+ - GitHub Actions workflows: CI (ruff, mypy, pytest 3.10 to 3.13, coverage, wheel build), integration (bubblewrap and Podman on the runner), CodeQL, security (pip-audit, gitleaks, Semgrep), PR lint, release and docs; Dependabot for uv and Actions (#5).
32
+ - Bubblewrap smoke test in `tests/integration` proving user namespaces work on the runner (#5).
33
+ - Issue templates (bug, feature, new runner, false positive), pull request template, CODEOWNERS, CONTRIBUTING, SECURITY and CODE_OF_CONDUCT (#4).
34
+ - CLAUDE.md with the repo workflow, branch protection, code quality bar and the hard security rules for agents and contributors (#8).
35
+
36
+ [Unreleased]: https://github.com/rj-karan/coldrun/compare/v0.0.1...HEAD
37
+ [0.0.1]: https://github.com/rj-karan/coldrun/releases/tag/v0.0.1
coldrun-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KARAN RJ
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.
coldrun-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: coldrun
3
+ Version: 0.1.0
4
+ Summary: Fetch, vet and sandbox any downloaded script in one command
5
+ Project-URL: Homepage, https://github.com/rj-karan/coldrun
6
+ Project-URL: Repository, https://github.com/rj-karan/coldrun
7
+ Project-URL: Issues, https://github.com/rj-karan/coldrun/issues
8
+ Project-URL: Changelog, https://github.com/rj-karan/coldrun/blob/main/CHANGELOG.md
9
+ Author: KARAN RJ
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: bubblewrap,cli,sandbox,scripts,security
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Information Technology
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Security
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: rich>=13.7
28
+ Requires-Dist: typer>=0.12
29
+ Description-Content-Type: text/markdown
30
+
31
+ # coldrun
32
+
33
+ [![CI](https://github.com/rj-karan/coldrun/actions/workflows/ci.yml/badge.svg)](https://github.com/rj-karan/coldrun/actions/workflows/ci.yml)
34
+ [![Coverage](https://codecov.io/gh/rj-karan/coldrun/graph/badge.svg)](https://codecov.io/gh/rj-karan/coldrun)
35
+ [![PyPI](https://img.shields.io/pypi/v/coldrun?label=pypi)](https://pypi.org/project/coldrun/)
36
+ [![Licence: MIT](https://img.shields.io/badge/licence-MIT-blue.svg)](LICENSE)
37
+
38
+ Fetch, vet and sandbox any downloaded script in one command.
39
+
40
+ ```
41
+ coldrun run https://github.com/someone/tool/blob/main/script.py -- --target 10.10.11.5
42
+ ```
43
+
44
+ coldrun takes a script from a file, URL, GitHub repo, gist or exploit-db ID,
45
+ works out what it needs, checks it for behaviour aimed at your machine, and runs
46
+ it inside a sandbox with no network and no access to your home directory.
47
+
48
+ The project is under construction. The full specification is in
49
+ [docs/SPEC.md](docs/SPEC.md).
50
+
51
+ ## Licence
52
+
53
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,23 @@
1
+ # coldrun
2
+
3
+ [![CI](https://github.com/rj-karan/coldrun/actions/workflows/ci.yml/badge.svg)](https://github.com/rj-karan/coldrun/actions/workflows/ci.yml)
4
+ [![Coverage](https://codecov.io/gh/rj-karan/coldrun/graph/badge.svg)](https://codecov.io/gh/rj-karan/coldrun)
5
+ [![PyPI](https://img.shields.io/pypi/v/coldrun?label=pypi)](https://pypi.org/project/coldrun/)
6
+ [![Licence: MIT](https://img.shields.io/badge/licence-MIT-blue.svg)](LICENSE)
7
+
8
+ Fetch, vet and sandbox any downloaded script in one command.
9
+
10
+ ```
11
+ coldrun run https://github.com/someone/tool/blob/main/script.py -- --target 10.10.11.5
12
+ ```
13
+
14
+ coldrun takes a script from a file, URL, GitHub repo, gist or exploit-db ID,
15
+ works out what it needs, checks it for behaviour aimed at your machine, and runs
16
+ it inside a sandbox with no network and no access to your home directory.
17
+
18
+ The project is under construction. The full specification is in
19
+ [docs/SPEC.md](docs/SPEC.md).
20
+
21
+ ## Licence
22
+
23
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1 @@
1
+ # AUR and Debian packaging land here in M5 (issues #37 and #38).
@@ -0,0 +1,151 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.33.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "coldrun"
7
+ version = "0.1.0"
8
+ description = "Fetch, vet and sandbox any downloaded script in one command"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "KARAN RJ" }]
13
+ requires-python = ">=3.10"
14
+ keywords = ["sandbox", "bubblewrap", "security", "scripts", "cli"]
15
+ classifiers = [
16
+ "Development Status :: 2 - Pre-Alpha",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Information Technology",
20
+ "Operating System :: POSIX :: Linux",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Security",
27
+ "Topic :: System :: Systems Administration",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = [
31
+ "typer>=0.12",
32
+ "rich>=13.7",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/rj-karan/coldrun"
37
+ Repository = "https://github.com/rj-karan/coldrun"
38
+ Issues = "https://github.com/rj-karan/coldrun/issues"
39
+ Changelog = "https://github.com/rj-karan/coldrun/blob/main/CHANGELOG.md"
40
+
41
+ [project.scripts]
42
+ coldrun = "coldrun.cli:app"
43
+
44
+ # Third-party runners register here; see docs/writing-a-runner.md (M5).
45
+ [project.entry-points."coldrun.runners"]
46
+
47
+ [dependency-groups]
48
+ dev = [
49
+ "pytest>=8.3",
50
+ "pytest-cov>=6.0",
51
+ "ruff>=0.8",
52
+ "mypy>=1.13",
53
+ "pre-commit>=4.0",
54
+ ]
55
+
56
+ [tool.hatch.build.targets.wheel]
57
+ packages = ["src/coldrun"]
58
+
59
+ [tool.hatch.build.targets.sdist]
60
+ include = ["src/coldrun", "tests", "rules", "LICENSE", "README.md", "CHANGELOG.md"]
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["tests"]
64
+ markers = [
65
+ "sandbox: needs bubblewrap or podman; proves the sandbox holds",
66
+ "e2e: full coldrun run on a fixture; installs dependencies",
67
+ ]
68
+ addopts = "-ra --strict-markers"
69
+
70
+ [tool.coverage.run]
71
+ source = ["coldrun"]
72
+ branch = true
73
+
74
+ [tool.coverage.report]
75
+ fail_under = 85
76
+ show_missing = true
77
+ exclude_also = ["if TYPE_CHECKING:", "\\.\\.\\.$"]
78
+
79
+ [tool.ruff]
80
+ target-version = "py310"
81
+ line-length = 100
82
+ src = ["src", "tests"]
83
+ extend-exclude = ["docs", "tests/fixtures"]
84
+
85
+ [tool.ruff.lint]
86
+ select = [
87
+ "E", "W", # pycodestyle
88
+ "F", # pyflakes
89
+ "I", # isort
90
+ "UP", # pyupgrade
91
+ "B", # bugbear
92
+ "S", # bandit: flags shell=True, eval, tempfile misuse
93
+ "N", # naming
94
+ "D", # docstrings on public objects
95
+ "ANN", # type annotations everywhere
96
+ "C4", # comprehensions
97
+ "SIM", # simplify
98
+ "PTH", # pathlib over os.path
99
+ "RUF", # ruff-specific
100
+ "T20", # no stray print
101
+ "ISC", # implicit string concatenation
102
+ "PIE",
103
+ "RET",
104
+ "ARG", # unused arguments
105
+ "TC", # type-checking imports
106
+ "PGH", # blanket noqa / type: ignore
107
+ "PERF",
108
+ "FURB",
109
+ "LOG", "G", # logging
110
+ "ERA", # commented-out code
111
+ "PL", # pylint subset
112
+ ]
113
+ ignore = [
114
+ "D105", # magic methods need no docstring
115
+ "D107", # __init__ documented on the class
116
+ "D203", # conflicts with D211
117
+ "D213", # conflicts with D212
118
+ "PLR0913", # argument counts are reviewed, not counted
119
+ "ISC001", # conflicts with the formatter
120
+ ]
121
+
122
+ [tool.ruff.lint.per-file-ignores]
123
+ "tests/**" = [
124
+ "S101", # assert is the test idiom
125
+ "D", # test names are the documentation
126
+ "ANN", # fixtures and test functions stay light
127
+ "PLR2004",# magic values in assertions are fine
128
+ "ARG", # fixtures are injected by name
129
+ "TC", # type-checking blocks add noise in tests
130
+ ]
131
+
132
+ [tool.ruff.lint.pydocstyle]
133
+ convention = "google"
134
+
135
+ [tool.ruff.lint.isort]
136
+ known-first-party = ["coldrun"]
137
+ required-imports = ["from __future__ import annotations"]
138
+
139
+ [tool.ruff.format]
140
+ docstring-code-format = true
141
+
142
+ [tool.mypy]
143
+ python_version = "3.10"
144
+ files = ["src", "tests"]
145
+ exclude = ["^tests/fixtures/"]
146
+ strict = true
147
+ warn_unreachable = true
148
+ warn_unused_ignores = true
149
+ enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"]
150
+ pretty = true
151
+ show_error_codes = true
@@ -0,0 +1 @@
1
+ # Semgrep and YARA rules land here in M3 (issue #22).
@@ -0,0 +1,12 @@
1
+ """coldrun: fetch, vet and sandbox any downloaded script in one command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ try:
8
+ __version__ = version("coldrun")
9
+ except PackageNotFoundError: # pragma: no cover - only when run from a bare checkout
10
+ __version__ = "0.0.0+unknown"
11
+
12
+ __all__ = ["__version__"]
@@ -0,0 +1,53 @@
1
+ """Typer application for the ``coldrun`` command.
2
+
3
+ This module wires command-line options to the pipeline and holds no logic of
4
+ its own. Commands are added here as the milestones land.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import typer
10
+ from rich.console import Console
11
+
12
+ from coldrun import __version__
13
+ from coldrun import doctor as doctor_mod
14
+
15
+ app = typer.Typer(
16
+ name="coldrun",
17
+ help="Fetch, vet and sandbox any downloaded script in one command.",
18
+ no_args_is_help=True,
19
+ add_completion=False,
20
+ rich_markup_mode="rich",
21
+ )
22
+
23
+
24
+ def _version_callback(value: bool) -> None:
25
+ if value:
26
+ typer.echo(f"coldrun {__version__}")
27
+ raise typer.Exit()
28
+
29
+
30
+ @app.callback()
31
+ def main(
32
+ version: bool = typer.Option(
33
+ False,
34
+ "--version",
35
+ "-V",
36
+ help="Show the version and exit.",
37
+ callback=_version_callback,
38
+ is_eager=True,
39
+ ),
40
+ ) -> None:
41
+ """Fetch, vet and sandbox any downloaded script in one command."""
42
+
43
+
44
+ @app.command()
45
+ def doctor() -> None:
46
+ """Check bwrap, podman, uv and kernel support, and say how to fix what is missing."""
47
+ results = doctor_mod.run_checks()
48
+ doctor_mod.render(results, Console(highlight=False))
49
+ raise typer.Exit(code=1 if doctor_mod.has_failures(results) else 0)
50
+
51
+
52
+ if __name__ == "__main__": # pragma: no cover
53
+ app()
@@ -0,0 +1,29 @@
1
+ """Where coldrun keeps its files on the host.
2
+
3
+ Only paths live here for now; the TOML config file arrives when there are
4
+ settings worth persisting. Both directories honour the XDG variables.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ APP = "coldrun"
13
+
14
+
15
+ def config_dir() -> Path:
16
+ """``$XDG_CONFIG_HOME/coldrun`` or ``~/.config/coldrun``."""
17
+ base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
18
+ return Path(base) / APP
19
+
20
+
21
+ def cache_dir() -> Path:
22
+ """``$XDG_CACHE_HOME/coldrun`` or ``~/.cache/coldrun``."""
23
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
24
+ return Path(base) / APP
25
+
26
+
27
+ def quarantine_root() -> Path:
28
+ """Parent of every quarantine directory, under the cache."""
29
+ return cache_dir() / "quarantine"
@@ -0,0 +1,223 @@
1
+ """Pick a runner from shebang, extension and file magic.
2
+
3
+ The language knowledge lives in the runners: each one scores a file through
4
+ ``Runner.detect``. This module supplies the cheap, shared signals runners
5
+ build on, asks every registered runner, and turns the scores into one choice
6
+ or one clear error. Only bytes are inspected; nothing is executed or imported.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import shlex
12
+ from dataclasses import dataclass, field
13
+ from enum import Enum
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING
16
+
17
+ if TYPE_CHECKING:
18
+ from coldrun.runners.base import Runner
19
+ from coldrun.runners.registry import Registry
20
+
21
+ #: A runner must be at least this sure before coldrun runs anything.
22
+ THRESHOLD = 0.5
23
+ _SNIFF_BYTES = 512
24
+ _SHEBANG_MAX = 256
25
+
26
+
27
+ class FileKind(str, Enum):
28
+ """Coarse shape of a file, from its first bytes."""
29
+
30
+ SCRIPT = "script" # has a shebang
31
+ TEXT = "text" # readable text without a shebang
32
+ ELF = "elf"
33
+ PE = "pe"
34
+ MACHO = "macho"
35
+ ZIP = "zip"
36
+ GZIP = "gzip"
37
+ XZ = "xz"
38
+ BZIP2 = "bzip2"
39
+ ZSTD = "zstd"
40
+ BINARY = "binary" # other non-text
41
+ EMPTY = "empty"
42
+
43
+
44
+ _MAGIC: tuple[tuple[bytes, FileKind], ...] = (
45
+ (b"\x7fELF", FileKind.ELF),
46
+ (b"MZ", FileKind.PE),
47
+ (b"\xcf\xfa\xed\xfe", FileKind.MACHO),
48
+ (b"\xfe\xed\xfa\xcf", FileKind.MACHO),
49
+ (b"\xca\xfe\xba\xbe", FileKind.MACHO),
50
+ (b"PK\x03\x04", FileKind.ZIP),
51
+ (b"\x1f\x8b", FileKind.GZIP),
52
+ (b"\xfd7zXZ\x00", FileKind.XZ),
53
+ (b"BZh", FileKind.BZIP2),
54
+ (b"\x28\xb5\x2f\xfd", FileKind.ZSTD),
55
+ )
56
+ _TEXT_BYTES = bytes(range(0x20, 0x7F)) + b"\t\n\r\x0b\x0c\x1b"
57
+ _ASCII_LIMIT = 0x80
58
+ _BINARY_RATIO = 0.1
59
+
60
+
61
+ class DetectError(Exception):
62
+ """No runner could be chosen.
63
+
64
+ Args:
65
+ what: Why, in one sentence.
66
+ hint: What the user can do, usually ``--lang``.
67
+ candidates: Runner names and scores that were considered.
68
+ """
69
+
70
+ def __init__(self, what: str, hint: str, candidates: list[tuple[str, float]]) -> None:
71
+ """Keep the parts separate for the report."""
72
+ super().__init__(f"{what} {hint}")
73
+ self.what = what
74
+ self.hint = hint
75
+ self.candidates = candidates
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class Signals:
80
+ """The shared evidence about one file."""
81
+
82
+ kind: FileKind
83
+ shebang: str | None
84
+ interpreter: str | None
85
+ extension: str
86
+
87
+ @property
88
+ def is_text(self) -> bool:
89
+ """True for scripts and plain text."""
90
+ return self.kind in {FileKind.SCRIPT, FileKind.TEXT}
91
+
92
+
93
+ @dataclass(frozen=True, slots=True)
94
+ class Detection:
95
+ """The chosen runner and why."""
96
+
97
+ runner: Runner
98
+ confidence: float
99
+ signals: Signals
100
+ forced: bool = False
101
+ candidates: list[tuple[str, float]] = field(default_factory=list)
102
+
103
+ @property
104
+ def reasons(self) -> list[str]:
105
+ """Human-readable evidence for the report."""
106
+ out: list[str] = []
107
+ if self.forced:
108
+ out.append(f"--lang {self.runner.name}")
109
+ if self.signals.shebang:
110
+ out.append(f"shebang {self.signals.shebang}")
111
+ if self.signals.extension:
112
+ out.append(f"extension {self.signals.extension}")
113
+ if not self.signals.is_text:
114
+ out.append(f"magic {self.signals.kind.value}")
115
+ return out
116
+
117
+
118
+ def sniff_kind(path: Path) -> FileKind:
119
+ """Classify a file from its first bytes."""
120
+ with path.open("rb") as fh:
121
+ head = fh.read(_SNIFF_BYTES)
122
+ if not head:
123
+ return FileKind.EMPTY
124
+ for magic, kind in _MAGIC:
125
+ if head.startswith(magic):
126
+ return kind
127
+ if head.startswith(b"#!"):
128
+ return FileKind.SCRIPT
129
+ if b"\x00" in head:
130
+ return FileKind.BINARY
131
+ sample = head.translate(None, _TEXT_BYTES)
132
+ # Allow UTF-8 multibyte sequences; anything with lots of control bytes is binary.
133
+ control = sum(1 for b in sample if b < _ASCII_LIMIT)
134
+ return FileKind.BINARY if control > len(head) * _BINARY_RATIO else FileKind.TEXT
135
+
136
+
137
+ def read_shebang(path: Path) -> str | None:
138
+ """Return the shebang line without ``#!`` and trailing whitespace, or ``None``."""
139
+ with path.open("rb") as fh:
140
+ head = fh.read(_SHEBANG_MAX)
141
+ if not head.startswith(b"#!"):
142
+ return None
143
+ line = head[2:].split(b"\n", 1)[0].strip()
144
+ try:
145
+ return line.decode("utf-8")
146
+ except UnicodeDecodeError:
147
+ return None
148
+
149
+
150
+ def interpreter_from_shebang(shebang: str) -> str | None:
151
+ """Name of the interpreter a shebang asks for, such as ``python3`` or ``bash``.
152
+
153
+ Handles ``/usr/bin/env name``, ``/usr/bin/env -S name args`` and plain
154
+ ``/bin/name``. Returns ``None`` for an unparsable line.
155
+ """
156
+ try:
157
+ parts = shlex.split(shebang)
158
+ except ValueError:
159
+ return None
160
+ if not parts:
161
+ return None
162
+ if Path(parts[0]).name == "env":
163
+ rest = [p for p in parts[1:] if not p.startswith("-") and "=" not in p]
164
+ return Path(rest[0]).name if rest else None
165
+ return Path(parts[0]).name
166
+
167
+
168
+ def signals_for(path: Path) -> Signals:
169
+ """Gather the shared evidence for ``path``."""
170
+ kind = sniff_kind(path)
171
+ shebang = read_shebang(path) if kind == FileKind.SCRIPT else None
172
+ return Signals(
173
+ kind=kind,
174
+ shebang=shebang,
175
+ interpreter=interpreter_from_shebang(shebang) if shebang else None,
176
+ extension=path.suffix.lower(),
177
+ )
178
+
179
+
180
+ def detect(path: Path, registry: Registry, lang: str | None = None) -> Detection:
181
+ """Choose the runner for ``path``.
182
+
183
+ Args:
184
+ path: The quarantined file.
185
+ registry: Where runners come from.
186
+ lang: ``--lang`` override; skips scoring and takes that runner.
187
+
188
+ Raises:
189
+ DetectError: When nothing is confident enough, or ``lang`` is unknown.
190
+ """
191
+ signals = signals_for(path)
192
+ if lang is not None:
193
+ try:
194
+ runner = registry.get(lang)
195
+ except LookupError as exc:
196
+ raise DetectError(
197
+ str(exc) + ".",
198
+ "Pick one of the available runners with --lang.",
199
+ [],
200
+ ) from exc
201
+ return Detection(runner=runner, confidence=1.0, signals=signals, forced=True)
202
+
203
+ scored: list[tuple[float, Runner]] = []
204
+ for runner in registry.all():
205
+ score = float(runner.detect(path))
206
+ scored.append((min(max(score, 0.0), 1.0), runner))
207
+ scored.sort(key=lambda s: s[0], reverse=True)
208
+ candidates = [(r.name, s) for s, r in scored]
209
+ if not scored or scored[0][0] < THRESHOLD:
210
+ what = f"Could not tell what kind of script {path.name} is ({signals.kind.value}"
211
+ what += f", shebang {signals.shebang}" if signals.shebang else ""
212
+ what += ")."
213
+ names = ", ".join(registry.names()) or "none installed"
214
+ raise DetectError(what, f"Force a runner with --lang NAME. Available: {names}.", candidates)
215
+ best, runner = scored[0]
216
+ if len(scored) > 1 and scored[1][0] == best:
217
+ tied = ", ".join(r.name for s, r in scored if s == best)
218
+ raise DetectError(
219
+ f"{path.name} matches more than one runner equally ({tied}).",
220
+ "Choose one with --lang NAME.",
221
+ candidates,
222
+ )
223
+ return Detection(runner=runner, confidence=best, signals=signals, candidates=candidates)