|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn |
| 4 | +"""What uses a credential? Local, read-only dependents search (GH#34719). |
| 5 | +
|
| 6 | +Searches registered repos and their linked worktrees, custom agents, local |
| 7 | +aidevops configs, scheduler definitions and the user crontab for a secret |
| 8 | +name and its aliases. Reads no secret values, makes no network calls, and |
| 9 | +reports `complete: false` whenever coverage is unproven (dynamic name |
| 10 | +construction, timeouts, truncation or unreadable sources), so a result |
| 11 | +never claims "unused" without evidence. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import json |
| 17 | +import subprocess # nosec B404 -- exception classes only; commands run via credential_inventory_scan.run_tool |
| 18 | +from concurrent.futures import ThreadPoolExecutor |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +import credential_inventory_scan as scan |
| 23 | + |
| 24 | +GREP_TIMEOUT = 30 |
| 25 | +MAX_WORKERS = 8 |
| 26 | +CONFIG_SUFFIXES = {".json", ".conf", ".toml", ".yaml", ".yml"} |
| 27 | +REGISTRY_FILE = "credential-inventory.json" |
| 28 | + |
| 29 | + |
| 30 | +def registered_repos(home: Path) -> list[tuple[str, Path]]: |
| 31 | + """(label, path) for each existing repo in repos.json.""" |
| 32 | + try: |
| 33 | + data = json.loads((home / ".config" / "aidevops" / "repos.json").read_text(encoding="utf-8")) |
| 34 | + except (OSError, ValueError): |
| 35 | + return [] |
| 36 | + entries = data.get("initialized_repos", []) if isinstance(data, dict) else [] |
| 37 | + repos = [] |
| 38 | + for entry in entries if isinstance(entries, list) else []: |
| 39 | + path = Path(str((entry or {}).get("path", ""))).expanduser() |
| 40 | + if str(path) != "." and path.is_dir(): |
| 41 | + repos.append((str(entry.get("slug") or path.name), path)) |
| 42 | + return repos |
| 43 | + |
| 44 | + |
| 45 | +def worktrees(repo: Path) -> list[Path]: |
| 46 | + """Existing worktree paths (main checkout included) for a repo.""" |
| 47 | + try: |
| 48 | + result = scan.run_tool("git", ["-C", str(repo), "worktree", "list", "--porcelain"], GREP_TIMEOUT) |
| 49 | + except (OSError, subprocess.SubprocessError): |
| 50 | + return [repo] |
| 51 | + paths = [Path(line[9:]) for line in result.stdout.splitlines() if line.startswith("worktree ")] |
| 52 | + return [path for path in paths if path.is_dir()] or [repo] |
| 53 | + |
| 54 | + |
| 55 | +def local_files(home: Path) -> dict[str, list[Path]]: |
| 56 | + """Config and scheduler files to scan, grouped by source.""" |
| 57 | + config_dir = home / ".config" / "aidevops" |
| 58 | + configs = sorted( |
| 59 | + path for path in config_dir.glob("*") |
| 60 | + if path.is_file() and path.suffix in CONFIG_SUFFIXES and path.name != REGISTRY_FILE |
| 61 | + ) if config_dir.is_dir() else [] |
| 62 | + schedulers = sorted((home / "Library" / "LaunchAgents").glob("*.plist")) |
| 63 | + systemd = home / ".config" / "systemd" / "user" |
| 64 | + schedulers += sorted(path for path in systemd.glob("*") if path.suffix in {".service", ".timer"}) |
| 65 | + return {"config": configs, "scheduler": schedulers} |
| 66 | + |
| 67 | + |
| 68 | +def crontab_hits(needles: scan.Needles) -> tuple[list[dict], str | None]: |
| 69 | + """Scan `crontab -l`; no crontab is an empty result, not a gap.""" |
| 70 | + try: |
| 71 | + result = scan.run_tool("crontab", ["-l"], 10) |
| 72 | + except FileNotFoundError: |
| 73 | + return [], None |
| 74 | + except (OSError, subprocess.SubprocessError): |
| 75 | + return [], "crontab unreadable" |
| 76 | + if result.returncode != 0: |
| 77 | + return [], None |
| 78 | + return [{"path": "crontab", **hit} for hit in scan.scan_lines(result.stdout.splitlines(), needles)], None |
| 79 | + |
| 80 | + |
| 81 | +class Report: |
| 82 | + """Accumulates hits, skipped sources and coverage counts.""" |
| 83 | + |
| 84 | + def __init__(self, names: list[str]) -> None: |
| 85 | + self.names = names |
| 86 | + self.hits: list[dict] = [] |
| 87 | + self.skipped: list[dict] = [] |
| 88 | + self.scanned: dict[str, int] = {} |
| 89 | + |
| 90 | + def add(self, source: str, location: str, hits: list[dict], reason: str | None = None) -> None: |
| 91 | + self.hits += [{"source": source, "location": location, **hit} for hit in hits] |
| 92 | + if reason: |
| 93 | + self.skipped.append({"source": source, "location": location, "reason": reason}) |
| 94 | + self.scanned[source] = self.scanned.get(source, 0) + 1 |
| 95 | + |
| 96 | + def result(self) -> dict[str, Any]: |
| 97 | + literal = [hit for hit in self.hits if hit["kind"] == "literal"] |
| 98 | + dynamic = [hit for hit in self.hits if hit["kind"] == "possible-dynamic"] |
| 99 | + return { |
| 100 | + "name": self.names[0], |
| 101 | + "aliases": self.names[1:], |
| 102 | + "literal": literal, |
| 103 | + "possible_dynamic": dynamic, |
| 104 | + "skipped": self.skipped, |
| 105 | + "scanned": self.scanned, |
| 106 | + "complete": not dynamic and not self.skipped, |
| 107 | + } |
| 108 | + |
| 109 | + |
| 110 | +def scan_repos(report: Report, home: Path, needles: scan.Needles) -> None: |
| 111 | + """git grep every worktree of every registered repo, in parallel.""" |
| 112 | + targets = [(label, tree) for label, repo in registered_repos(home) for tree in worktrees(repo)] |
| 113 | + targets = list({str(tree): (label, tree) for label, tree in targets}.values()) |
| 114 | + with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: |
| 115 | + results = pool.map(lambda target: scan.grep_worktree(target[1], needles, GREP_TIMEOUT), targets) |
| 116 | + for (label, tree), (hits, reason) in zip(targets, results): |
| 117 | + report.add("repo", str(tree), [{"repo": label, **hit} for hit in hits], reason) |
| 118 | + |
| 119 | + |
| 120 | +def scan_local(report: Report, home: Path, needles: scan.Needles) -> None: |
| 121 | + """Custom agents, aidevops configs, schedulers and crontab.""" |
| 122 | + custom, capped = scan.tree_files(home / ".aidevops" / "agents" / "custom") |
| 123 | + groups = {"custom-agents": custom, **local_files(home)} |
| 124 | + for source, paths in groups.items(): |
| 125 | + hits, skipped = scan.scan_files(paths, needles) |
| 126 | + report.add(source, source, hits, "file limit reached" if source == "custom-agents" and capped else None) |
| 127 | + report.scanned[source] = len(paths) |
| 128 | + for path in skipped: |
| 129 | + report.skipped.append({"source": source, "location": path, "reason": "unreadable or too large"}) |
| 130 | + hits, reason = crontab_hits(needles) |
| 131 | + report.add("crontab", "crontab", hits, reason) |
| 132 | + |
| 133 | + |
| 134 | +def find_dependents(names: list[str], home: Path | None = None) -> dict[str, Any]: |
| 135 | + """Search all local sources for `names` (canonical first, then aliases).""" |
| 136 | + home = home or Path.home() |
| 137 | + needles = scan.build_needles(names) |
| 138 | + report = Report(names) |
| 139 | + scan_repos(report, home, needles) |
| 140 | + scan_local(report, home, needles) |
| 141 | + return report.result() |
| 142 | + |
| 143 | + |
| 144 | +def render(result: dict[str, Any]) -> str: |
| 145 | + """Human-readable report; never states 'unused' when incomplete.""" |
| 146 | + aliases = f" (aliases: {', '.join(result['aliases'])})" if result["aliases"] else "" |
| 147 | + lines = [f"Dependents of {result['name']}{aliases}"] |
| 148 | + for label, key in (("literal", "literal"), ("possible-dynamic", "possible_dynamic")): |
| 149 | + for hit in result[key]: |
| 150 | + lines.append(f" {label:16} {hit['location']} {hit['path']}:{hit['line']} [{hit['matched']}]") |
| 151 | + for skip in result["skipped"]: |
| 152 | + lines.append(f" skipped {skip['location']} ({skip['reason']})") |
| 153 | + scanned = ", ".join(f"{source} {count}" for source, count in sorted(result["scanned"].items())) |
| 154 | + lines.append(f"Scanned: {scanned}") |
| 155 | + if not result["complete"]: |
| 156 | + lines.append("INCOMPLETE: dynamic name construction or skipped sources; do not treat this name as unused.") |
| 157 | + elif not result["literal"]: |
| 158 | + lines.append("No references found in the scanned sources.") |
| 159 | + return "\n".join(lines) |
0 commit comments