| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569 |
- """Read-only inventory and archive comparison for CPLD-related C-drive paths."""
- from __future__ import annotations
- import argparse
- import ctypes
- import hashlib
- import json
- import os
- import re
- import stat
- import subprocess
- import sys
- import zipfile
- from dataclasses import dataclass, field
- from datetime import datetime, timezone
- from functools import lru_cache
- from pathlib import Path, PurePosixPath
- from typing import Any, Iterable, Iterator, Mapping, Sequence
- SCHEMA = "cpld-c-drive-audit-v1"
- CONFIG_SCHEMA = "cpld-c-drive-audit-config-v1"
- DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "config" / "cpld_c_drive_audit.json"
- MAX_MEMBER_BYTES = 8 * 1024 * 1024 * 1024
- REPARSE_ATTRIBUTE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
- DEFAULT_CANDIDATE_PATTERNS = (
- "cpld",
- "p4",
- "prod2u",
- "temperature",
- "normal",
- "handoff",
- "analysis",
- "board",
- "ct7428",
- "fpga",
- )
- DEFAULT_PROTECTED_PATTERNS = (
- "release",
- "source",
- "firmware",
- "final-gate",
- "rc1",
- "sha256sums",
- "license",
- r"\.lic$",
- "private",
- "original",
- r"hardware[-_ ]evidence",
- )
- @dataclass(frozen=True)
- class AuditConfig:
- candidate_patterns: tuple[str, ...] = DEFAULT_CANDIDATE_PATTERNS
- excluded_patterns: tuple[str, ...] = ()
- protected_patterns: tuple[str, ...] = DEFAULT_PROTECTED_PATTERNS
- max_files: int = 100_000
- root_scopes: Mapping[str, str] = field(default_factory=dict)
- @classmethod
- def from_mapping(cls, payload: Mapping[str, Any]) -> "AuditConfig":
- if payload.get("schema") not in (None, CONFIG_SCHEMA):
- raise ValueError(f"unsupported audit config schema: {payload.get('schema')!r}")
- roots = payload.get("scan_roots", [])
- scopes = {
- str(Path(item["path"]).resolve()): str(item.get("scope", "configured_root"))
- for item in roots
- if isinstance(item, Mapping) and item.get("path")
- }
- return cls(
- candidate_patterns=tuple(str(item) for item in payload.get("candidate_patterns", DEFAULT_CANDIDATE_PATTERNS)),
- excluded_patterns=tuple(str(item) for item in payload.get("excluded_patterns", ())),
- protected_patterns=tuple(str(item) for item in payload.get("protected_patterns", DEFAULT_PROTECTED_PATTERNS)),
- max_files=max(1, int(payload.get("max_files", 100_000))),
- root_scopes=scopes,
- )
- def _now() -> str:
- return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
- def _matches(value: str, patterns: Sequence[str]) -> bool:
- for pattern in patterns:
- try:
- if re.search(pattern, value, flags=re.IGNORECASE):
- return True
- except re.error:
- if pattern.casefold() in value.casefold():
- return True
- return False
- def _is_reparse(path: Path, file_stat: os.stat_result | None = None) -> bool:
- if path.is_symlink():
- return True
- try:
- value = file_stat if file_stat is not None else path.stat(follow_symlinks=False)
- return bool(getattr(value, "st_file_attributes", 0) & REPARSE_ATTRIBUTE)
- except OSError:
- return False
- def _safe_resolve(path: Path) -> Path:
- try:
- return path.resolve(strict=False)
- except OSError:
- return Path(os.path.abspath(os.fspath(path)))
- def _absolute_path(path: Path) -> Path:
- raw = os.fspath(path)
- if not os.path.isabs(raw):
- raw = os.path.abspath(raw)
- if os.name != "nt":
- return Path(raw)
- buffer = ctypes.create_unicode_buffer(32768)
- length = ctypes.windll.kernel32.GetFullPathNameW(raw, len(buffer), buffer, None)
- if not length:
- return Path(raw)
- full = buffer.value[:length]
- long_buffer = ctypes.create_unicode_buffer(32768)
- long_length = ctypes.windll.kernel32.GetLongPathNameW(full, long_buffer, len(long_buffer))
- return Path(long_buffer.value[:long_length] if long_length else full)
- def _sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def _git_anchor(path: Path) -> Path | None:
- current = path if path.is_dir() else path.parent
- for candidate in (current, *current.parents):
- try:
- if (candidate / ".git").exists() or (candidate / ".git").is_file():
- return candidate
- except OSError:
- continue
- return None
- @lru_cache(maxsize=256)
- def _git_context_for_anchor(anchor_value: str) -> tuple[str | None, bool, list[str]]:
- anchor = Path(anchor_value)
- if not anchor.exists():
- return None, False, []
- try:
- top = subprocess.run(
- ["git", "-C", str(anchor), "rev-parse", "--show-toplevel"],
- check=True,
- capture_output=True,
- text=True,
- timeout=10,
- ).stdout.strip()
- common_raw = subprocess.run(
- ["git", "-C", str(anchor), "rev-parse", "--git-common-dir"],
- check=True,
- capture_output=True,
- text=True,
- timeout=10,
- ).stdout.strip()
- common = _safe_resolve(Path(common_raw) if os.path.isabs(common_raw) else Path(top) / common_raw)
- status = subprocess.run(
- ["git", "-C", str(anchor), "status", "--porcelain", "--untracked-files=all"],
- check=True,
- capture_output=True,
- text=True,
- timeout=20,
- ).stdout
- except (OSError, subprocess.SubprocessError):
- return None, False, ["git_probe_failed"]
- return str(common), bool(status.strip()), [f"git_worktree:{top}", f"git_common_dir:{common}"]
- def _git_context(path: Path) -> tuple[str | None, bool, list[str]]:
- anchor = _git_anchor(path)
- return _git_context_for_anchor(str(anchor)) if anchor is not None else (None, False, [])
- def _base_record(path: Path | None, *, size: int | None, sha256: str | None, classification: str,
- recommended_action: str, reason: str, reparse_point: bool = False,
- comparison_target: str | None = None, comparison_result: str = "not_compared",
- ownership_evidence: Iterable[str] = ()) -> dict[str, Any]:
- resolved_path = _safe_resolve(path) if path is not None else None
- absolute = str(_absolute_path(path)) if path is not None else None
- resolved = str(resolved_path) if resolved_path is not None else None
- git_common_dir, dirty, git_evidence = _git_context(path) if path is not None else (None, False, [])
- evidence = list(dict.fromkeys([*ownership_evidence, *git_evidence]))
- return {
- "absolute_path": absolute,
- "resolved_path": resolved,
- "size": size,
- "git_common_dir": git_common_dir,
- "worktree_dirty": dirty,
- "reparse_point": reparse_point,
- "ownership_evidence": evidence,
- "sha256": sha256,
- "comparison_target": comparison_target,
- "comparison_result": comparison_result,
- "classification": classification,
- "recommended_action": recommended_action,
- "reason": reason,
- }
- def _iter_files(root: Path, config: AuditConfig) -> Iterator[tuple[Path, os.stat_result, bool]]:
- pending = [root]
- while pending:
- current = pending.pop()
- try:
- entries = list(os.scandir(current))
- except OSError:
- continue
- for entry in sorted(entries, key=lambda item: item.name.casefold()):
- path = Path(entry.path)
- try:
- file_stat = entry.stat(follow_symlinks=False)
- except OSError:
- continue
- if _matches(str(path), config.excluded_patterns):
- continue
- reparse = _is_reparse(path, file_stat)
- if entry.is_dir(follow_symlinks=False):
- if reparse:
- yield path, file_stat, True
- else:
- pending.append(path)
- continue
- yield path, file_stat, reparse
- def _record_file(
- path: Path,
- file_stat: os.stat_result,
- reparse: bool,
- config: AuditConfig,
- *,
- force_include: bool = False,
- ) -> dict[str, Any] | None:
- text = str(path)
- if not force_include and not _matches(text, config.candidate_patterns):
- return None
- evidence = ["configured_root_scope" if force_include else "candidate_name_match"]
- protected = _matches(text, config.protected_patterns)
- if reparse:
- return _base_record(
- path,
- size=int(file_stat.st_size),
- sha256=None,
- classification="reparse_point",
- recommended_action="retain_and_review",
- reason="reparse point was not followed or hashed",
- reparse_point=True,
- ownership_evidence=evidence,
- )
- try:
- digest = _sha256(path)
- except OSError as exc:
- return _base_record(
- path,
- size=int(file_stat.st_size),
- sha256=None,
- classification="unreadable_cpld_related_file",
- recommended_action="retain_and_review",
- reason=f"sha256 failed: {exc}",
- ownership_evidence=evidence,
- )
- if protected:
- classification = "protected_asset"
- action = "retain"
- reason = "release/source/original/license/private or hardware evidence path"
- elif path.suffix.casefold() in {".zip", ".7z", ".rar"}:
- classification = "archive_candidate"
- action = "review_with_compare_archives"
- reason = "archive requires independent member/hash comparison before any disposal"
- else:
- classification = "cpld_related_file"
- action = "review"
- reason = "under a configured CPLD scope" if force_include else "matched configured CPLD/P4 name or path pattern"
- return _base_record(
- path,
- size=int(file_stat.st_size),
- sha256=digest,
- classification=classification,
- recommended_action=action,
- reason=reason,
- ownership_evidence=evidence,
- )
- def scan_paths(paths: Sequence[Path], *, config: AuditConfig) -> dict[str, Any]:
- records: list[dict[str, Any]] = []
- visited = 0
- root_names = [str(_safe_resolve(Path(path))) for path in paths]
- for root_value in paths:
- root = Path(root_value)
- if not root.exists():
- continue
- root_scope = config.root_scopes.get(str(_safe_resolve(root)))
- force_include = root_scope in {"cpld_workspace", "named_cpld_path"}
- for path, file_stat, reparse in _iter_files(root, config):
- visited += 1
- if visited > config.max_files:
- records.append(_base_record(
- root,
- size=None,
- sha256=None,
- classification="scan_limit",
- recommended_action="retain_and_review",
- reason=f"scan stopped after max_files={config.max_files}",
- ownership_evidence=("scan_limit",),
- ))
- break
- record = _record_file(path, file_stat, reparse, config, force_include=force_include)
- if record is not None:
- records.append(record)
- records.sort(key=lambda item: str(item["absolute_path"]).casefold())
- return {
- "schema": SCHEMA,
- "command": "scan",
- "generated_at": _now(),
- "roots": root_names,
- "records": records,
- }
- def _normalize_member(name: str) -> str | None:
- normalized = name.replace("\\", "/")
- path = PurePosixPath(normalized)
- if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
- return None
- if any(part in {"", ".", ".."} for part in path.parts):
- return None
- return "/".join(path.parts)
- def _directory_files(root: Path) -> dict[str, Path]:
- files: dict[str, Path] = {}
- for path in root.rglob("*"):
- if not path.is_file() or _is_reparse(path):
- continue
- relative = "/".join(path.relative_to(root).parts).casefold()
- files[relative] = path
- return files
- def _archive_member_hash(handle: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[int, str]:
- if info.file_size > MAX_MEMBER_BYTES:
- raise ValueError("archive member exceeds audit size budget")
- digest = hashlib.sha256()
- size = 0
- with handle.open(info, "r") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- size += len(chunk)
- digest.update(chunk)
- return size, digest.hexdigest()
- def compare_archive(archive: Path, directory: Path, *, config: AuditConfig | None = None) -> dict[str, Any]:
- config = config or AuditConfig()
- archive = Path(archive)
- directory = Path(directory)
- archive_record = _base_record(
- archive,
- size=archive.stat().st_size if archive.is_file() else None,
- sha256=_sha256(archive) if archive.is_file() else None,
- classification="protected_archive" if _matches(str(archive), config.protected_patterns) else "archive_candidate",
- recommended_action="retain",
- reason="archive under independent comparison",
- ownership_evidence=("archive_input",),
- )
- directory_record = _base_record(
- directory,
- size=None,
- sha256=None,
- classification="comparison_directory",
- recommended_action="retain",
- reason="directory used as independent archive comparison target",
- ownership_evidence=("comparison_input",),
- )
- members: list[dict[str, Any]] = []
- unsafe = False
- target_files = _directory_files(directory) if directory.is_dir() else {}
- seen: set[str] = set()
- try:
- with zipfile.ZipFile(archive) as handle:
- for info in handle.infolist():
- normalized = _normalize_member(info.filename)
- if normalized is None or normalized.casefold() in seen:
- unsafe = True
- members.append({
- **_base_record(
- None,
- size=info.file_size,
- sha256=None,
- classification="unsafe_archive_member",
- recommended_action="retain",
- reason="absolute, traversal, empty, or duplicate archive member path",
- ownership_evidence=("zip_member_path_rejected",),
- comparison_result="unsafe_member",
- ),
- "member_path": info.filename,
- "target_size": None,
- })
- continue
- seen.add(normalized.casefold())
- if info.is_dir() or info.filename.endswith(("/", "\\")):
- members.append({
- **_base_record(
- directory / normalized,
- size=0,
- sha256=None,
- classification="archive_directory_member",
- recommended_action="review",
- reason="directory entry does not require file hash coverage",
- comparison_result="directory_entry",
- ownership_evidence=("zip_directory_member",),
- ),
- "member_path": info.filename,
- "target_size": None,
- })
- continue
- try:
- member_size, member_hash = _archive_member_hash(handle, info)
- except (OSError, ValueError, zipfile.BadZipFile) as exc:
- unsafe = True
- members.append({
- **_base_record(
- None,
- size=info.file_size,
- sha256=None,
- classification="unsafe_archive_member",
- recommended_action="retain",
- reason=f"archive member could not be independently hashed: {exc}",
- ownership_evidence=("zip_member_hash_failed",),
- comparison_result="unsafe_member",
- ),
- "member_path": info.filename,
- "target_size": None,
- })
- continue
- target = target_files.get(normalized.casefold())
- if target is None:
- result = "missing"
- target_size = None
- target_path = None
- else:
- target_size = target.stat().st_size
- target_path = target
- if target_size != member_size:
- result = "size_mismatch"
- elif _sha256(target) != member_hash:
- result = "sha256_mismatch"
- else:
- result = "covered_match"
- if result != "covered_match":
- unsafe = False if result in {"missing", "size_mismatch", "sha256_mismatch"} else unsafe
- members.append({
- **_base_record(
- target_path,
- size=member_size,
- sha256=member_hash,
- classification="archive_member",
- recommended_action="review",
- reason="member compared by normalized path, size, and SHA-256",
- comparison_target=str(target_path.resolve()) if target_path is not None else None,
- comparison_result=result,
- ownership_evidence=("zip_member_hash",),
- ),
- "member_path": info.filename,
- "target_size": int(target_size) if target_size is not None else None,
- })
- except (OSError, zipfile.BadZipFile) as exc:
- unsafe = True
- members.append({
- **_base_record(
- archive,
- size=archive_record["size"],
- sha256=archive_record["sha256"],
- classification="unreadable_archive",
- recommended_action="retain",
- reason=f"archive could not be read: {exc}",
- comparison_result="unsafe_member",
- ownership_evidence=("zip_open_failed",),
- ),
- "member_path": "",
- "target_size": None,
- })
- all_match = bool(members) and all(item["comparison_result"] in {"covered_match", "directory_entry"} for item in members)
- protected = _matches(str(archive), config.protected_patterns)
- if unsafe:
- status = "unsafe"
- action = "retain"
- elif all_match and protected:
- status = "full_coverage"
- action = "retain_protected_archive"
- elif all_match:
- status = "full_coverage"
- action = "delete_archive_after_verification"
- else:
- status = "mismatch"
- action = "retain"
- archive_record["comparison_target"] = str(directory.resolve())
- archive_record["comparison_result"] = status
- archive_record["recommended_action"] = action
- return {
- "schema": SCHEMA,
- "command": "compare-archives",
- "generated_at": _now(),
- "archive": archive_record,
- "directory": directory_record,
- "comparison": {"status": status, "recommended_action": action, "members": members},
- }
- def load_config(path: Path) -> tuple[AuditConfig, list[Path]]:
- payload = json.loads(Path(path).read_text(encoding="utf-8"))
- config = AuditConfig.from_mapping(payload)
- roots = [Path(str(item["path"])) for item in payload.get("scan_roots", []) if isinstance(item, Mapping) and item.get("path")]
- return config, roots
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Read-only CPLD C-drive audit")
- subparsers = parser.add_subparsers(dest="command", required=True)
- scan = subparsers.add_parser("scan", help="scan configured roots and emit JSON inventory")
- scan.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
- scan.add_argument("--root", action="append", type=Path, help="override configured scan roots; repeatable")
- scan.add_argument("--output", type=Path, help="write JSON report to this path")
- compare = subparsers.add_parser("compare-archives", help="compare ZIP members with an extracted directory")
- compare.add_argument("--archive", type=Path, required=True)
- compare.add_argument("--directory", type=Path, required=True)
- compare.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
- compare.add_argument("--output", type=Path, help="write JSON report to this path")
- return parser
- def _emit(payload: Mapping[str, Any], output: Path | None) -> None:
- encoded = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
- if output is None:
- sys.stdout.write(encoded)
- else:
- output.parent.mkdir(parents=True, exist_ok=True)
- output.write_text(encoded, encoding="utf-8", newline="\n")
- def main(argv: Sequence[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- try:
- config, configured_roots = load_config(args.config)
- if args.command == "scan":
- roots = args.root if args.root else configured_roots
- _emit(scan_paths(roots, config=config), args.output)
- else:
- _emit(compare_archive(args.archive, args.directory, config=config), args.output)
- except (OSError, ValueError, json.JSONDecodeError) as exc:
- print(f"cpld-c-drive-audit: fail: {exc}", file=sys.stderr)
- return 2
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|