config-central/tools/check_powershell.py

118 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Dependency-free structural checks for PowerShell on non-PowerShell CI workers."""
from __future__ import annotations
import json
import pathlib
import re
import sys
ROOT = pathlib.Path(__file__).resolve().parents[1]
POWERSHELL = sorted((*ROOT.rglob("*.ps1"), *ROOT.rglob("*.psm1")))
def check_balanced(path: pathlib.Path) -> list[str]:
text = path.read_text(encoding="utf-8-sig")
errors: list[str] = []
stack: list[tuple[str, int]] = []
pairs = {"(": ")", "[": "]", "{": "}"}
closing = set(pairs.values())
quote: str | None = None
escaped = False
line = 1
index = 0
while index < len(text):
char = text[index]
if char == "\n":
line += 1
if quote is None:
escaped = False
index += 1
continue
if quote:
if quote == '"' and char == "`" and not escaped:
escaped = True
index += 1
continue
if char == quote and not escaped:
if quote == "'" and index + 1 < len(text) and text[index + 1] == "'":
index += 2
continue
quote = None
escaped = False
index += 1
continue
if char == "#":
newline = text.find("\n", index)
index = len(text) if newline < 0 else newline
continue
if char in ("'", '"'):
quote = char
elif char in pairs:
stack.append((char, line))
elif char in closing:
if not stack or pairs[stack[-1][0]] != char:
errors.append(f"{path.relative_to(ROOT)}:{line}: unexpected {char}")
else:
stack.pop()
index += 1
if quote:
errors.append(f"{path.relative_to(ROOT)}:{line}: unterminated string")
for opener, opener_line in stack:
errors.append(f"{path.relative_to(ROOT)}:{opener_line}: unclosed {opener}")
return errors
def main() -> int:
errors: list[str] = []
if not POWERSHELL:
errors.append("No PowerShell source files found.")
for path in POWERSHELL:
errors.extend(check_balanced(path))
source = path.read_text(encoding="utf-8-sig")
if path.parent.name in {"src", "tools"} and "Set-StrictMode" not in source:
errors.append(f"{path.relative_to(ROOT)}: missing Set-StrictMode")
for relative in ("schemas/profile.schema.json", "schemas/machine.schema.json"):
path = ROOT / relative
try:
document = json.loads(path.read_text(encoding="utf-8"))
if document.get("$schema") != "https://json-schema.org/draft/2020-12/schema":
errors.append(f"{relative}: unexpected JSON Schema dialect")
except (OSError, json.JSONDecodeError) as exc:
errors.append(f"{relative}: {exc}")
for path in sorted((*ROOT.glob("profiles/*.json"), *ROOT.glob("machines/*.json"))):
try:
document = json.loads(path.read_text(encoding="utf-8"))
if document.get("schemaVersion") != 1:
errors.append(f"{path.relative_to(ROOT)}: schemaVersion must be 1")
except json.JSONDecodeError as exc:
errors.append(f"{path.relative_to(ROOT)}: {exc}")
required_cli_markers = ("doctor", "plan", "apply", "sync", "status", "configs", "restore", "schedule", "unschedule", "menu")
cli = (ROOT / "cc.ps1").read_text(encoding="utf-8-sig")
for marker in required_cli_markers:
if not re.search(rf"['\"]{re.escape(marker)}['\"]", cli):
errors.append(f"cc.ps1: missing command marker {marker}")
forbidden = ("DisableAntiSpyware", "Set-MpPreference -DisableRealtimeMonitoring", "--ignore-security-hash")
for path in POWERSHELL:
source = path.read_text(encoding="utf-8-sig")
for marker in forbidden:
if marker.lower() in source.lower():
errors.append(f"{path.relative_to(ROOT)}: forbidden security bypass marker {marker}")
if errors:
print("PowerShell structural validation failed:", file=sys.stderr)
for error in errors:
print(f" ERROR: {error}", file=sys.stderr)
return 1
print(f"Validated {len(POWERSHELL)} PowerShell files, JSON schemas, manifests, and CLI markers.")
return 0
if __name__ == "__main__":
raise SystemExit(main())