Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 75 additions & 5 deletions infra/worktree-reaper/bin/worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,71 @@ def run_git(repo, *args, timeout=GIT_TIMEOUT):
return 127, b"", str(exc)


class ConfigError(Exception):
"""A config file is unreadable, malformed, or fails validation.

The message always names the file. `main` turns this into the
clean `worktree-reaper: cannot load config ...` error instead of
a traceback (#6394).
"""


def _load_json_object(path):
"""Read `path` as JSON and require a top-level object (#6394)."""
try:
with open(path) as fh:
data = json.load(fh)
except OSError as exc:
raise ConfigError(f"{path}: cannot read file: {exc}") from exc
except json.JSONDecodeError as exc:
raise ConfigError(f"{path}: invalid JSON: {exc}") from exc
if not isinstance(data, dict):
raise ConfigError(
f"{path}: top level must be a JSON object, "
f"got {type(data).__name__}"
)
return data


def validate_config(data, path):
"""Validate one config file's contents against DEFAULT_CONFIG (#6394).

Unknown keys are refused: a typo'd `deny_*` key must never load
silently, because for a deletion tool that turns an explicit
"never reap this" into no protection at all. Types are taken
from the defaults: strings stay strings, the list keys stay
lists of strings, `fetch` stays a bool, and the numeric keys
stay numbers (never bools, never strings that explode mid-run).
"""
for key, val in data.items():
if key not in DEFAULT_CONFIG:
raise ConfigError(
f"{path}: unknown key {key!r} "
f"(valid keys: {', '.join(sorted(DEFAULT_CONFIG))})"
)
default = DEFAULT_CONFIG[key]
if isinstance(default, bool):
ok = isinstance(val, bool)
want = "a boolean"
elif isinstance(default, list):
ok = isinstance(val, list) and all(
isinstance(item, str) for item in val
)
want = "a list of strings"
elif isinstance(default, str):
ok = isinstance(val, str)
want = "a string"
else: # numeric defaults: quiet_hours, max_removals
ok = isinstance(val, (int, float)) and not isinstance(val, bool)
want = "a number"
if not ok:
raise ConfigError(
f"{path}: key {key!r} must be {want}, got {val!r}"
)
if key in ("quiet_hours", "max_removals") and val < 0:
raise ConfigError(f"{path}: key {key!r} must be >= 0, got {val!r}")


def load_config(script_dir, args):
cfg = dict(DEFAULT_CONFIG)
cfg_path = None
Expand All @@ -158,14 +223,15 @@ def load_config(script_dir, args):
cfg_path = cand
break
if cfg_path:
with open(cfg_path) as fh:
cfg.update(json.load(fh))
data = _load_json_object(cfg_path)
validate_config(data, cfg_path)
cfg.update(data)
cfg["_config_path"] = os.path.abspath(cfg_path)
state_dir = expand(args.state_dir or cfg["state_dir"])
overlay = os.path.join(state_dir, "config.local.json")
if os.path.isfile(overlay):
with open(overlay) as fh:
local = json.load(fh)
local = _load_json_object(overlay)
validate_config(local, overlay)
for key, val in local.items():
if key in ("deny_paths", "deny_prefixes", "deny_names") and isinstance(val, list):
cfg[key] = list(cfg.get(key, [])) + val
Expand Down Expand Up @@ -713,7 +779,11 @@ def main(argv=None):
args = ap.parse_args(argv)

script_dir = os.path.dirname(os.path.abspath(__file__))
cfg = load_config(script_dir, args)
try:
cfg = load_config(script_dir, args)
except ConfigError as exc:
print(f"worktree-reaper: cannot load config: {exc}")
return 2
state_dir = cfg["state_dir"]

if os.path.exists(os.path.join(state_dir, "DISABLED")):
Expand Down
100 changes: 100 additions & 0 deletions infra/worktree-reaper/tests/test_worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
Run on the laptop: python3 tests/test_worktree_reaper.py
"""

import argparse
import contextlib
import fcntl
import importlib.util
Expand Down Expand Up @@ -378,6 +379,105 @@ def test_walk_activity(self):
shutil.rmtree(root, ignore_errors=True)


class ConfigValidationTests(unittest.TestCase):
"""#6394: load_config validates both config files, naming the file.

Each invalid case from the issue must yield a clean ConfigError
(never a silent disarm, never a raw traceback): a typo'd deny
key, a string-typed deny list, a wrong-shaped top level,
malformed JSON, and a string-typed numeric. A valid config and
a valid overlay merge exactly as before.
"""

def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="reaper-config-test-")
self.addCleanup(shutil.rmtree, self.tmp, True)
self.state_dir = os.path.join(self.tmp, "state")
os.makedirs(self.state_dir)

def _args(self, config_path=None):
return argparse.Namespace(
config=config_path,
state_dir=self.state_dir,
quiet_hours=None,
max_removals=None,
no_fetch=False,
)

def _write(self, name, text):
path = os.path.join(self.tmp, name)
with open(path, "w") as fh:
fh.write(text)
return path

def _load(self, config_path=None):
return wr.load_config(self.tmp, self._args(config_path))

def test_typo_deny_key_is_refused_naming_the_file(self):
path = self._write("config.json", json.dumps({"deny_path": ["/x"]}))
with self.assertRaises(wr.ConfigError) as ctx:
self._load(path)
self.assertIn(path, str(ctx.exception))
self.assertIn("deny_path", str(ctx.exception))

def test_string_typed_deny_paths_is_refused(self):
path = self._write(
"config.json", json.dumps({"deny_paths": "/home/user/git/important"})
)
with self.assertRaises(wr.ConfigError) as ctx:
self._load(path)
self.assertIn("deny_paths", str(ctx.exception))

def test_top_level_list_is_refused_cleanly(self):
path = self._write("config.json", json.dumps(["deny_paths"]))
with self.assertRaises(wr.ConfigError) as ctx:
self._load(path)
self.assertIn("must be a JSON object", str(ctx.exception))

def test_malformed_json_is_refused_naming_the_file(self):
path = self._write("bad.json", "{oops")
with self.assertRaises(wr.ConfigError) as ctx:
self._load(path)
self.assertIn(path, str(ctx.exception))
self.assertIn("invalid JSON", str(ctx.exception))

def test_string_typed_quiet_hours_is_refused_at_load(self):
path = self._write("config.json", json.dumps({"quiet_hours": "6"}))
with self.assertRaises(wr.ConfigError) as ctx:
self._load(path)
self.assertIn("quiet_hours", str(ctx.exception))

def test_overlay_typo_key_is_refused_naming_the_overlay(self):
overlay = os.path.join(self.state_dir, "config.local.json")
with open(overlay, "w") as fh:
json.dump({"deny_path": ["/x"]}, fh)
with self.assertRaises(wr.ConfigError) as ctx:
self._load()
self.assertIn(overlay, str(ctx.exception))

def test_overlay_top_level_list_is_refused_cleanly(self):
overlay = os.path.join(self.state_dir, "config.local.json")
with open(overlay, "w") as fh:
json.dump(["x"], fh)
with self.assertRaises(wr.ConfigError) as ctx:
self._load()
self.assertIn(overlay, str(ctx.exception))

def test_valid_config_and_overlay_merge_unchanged(self):
path = self._write(
"config.json",
json.dumps({"quiet_hours": 2, "deny_paths": ["/a"], "fetch": False}),
)
overlay = os.path.join(self.state_dir, "config.local.json")
with open(overlay, "w") as fh:
json.dump({"deny_paths": ["/b"], "max_removals": 5}, fh)
cfg = self._load(path)
self.assertEqual(cfg["quiet_hours"], 2)
self.assertEqual(cfg["deny_paths"], ["/a", "/b"])
self.assertEqual(cfg["max_removals"], 5)
self.assertFalse(cfg["fetch"])


class ProcScanFailClosedTests(unittest.TestCase):
"""#5740: a /proc scan failure is UNKNOWN occupancy — fail closed."""

Expand Down
Loading