Files
marqdo/scripts/check-dev-secrets.py
T
cflmy 23dd830571 fix: run the root governance gates on Windows
- read .gitmodules, AGENTS.md and JSON fixtures as UTF-8 instead of the locale codec
- materialize the credential pattern file before git grep so Windows file locking cannot skip the scan
- clear read-only Git object bits when fixture trees are removed
- probe symlink support and skip only the symlink-only negative fixtures, keeping the NFC checks
- add a small platform helper for the integration tests
2026-12-03 08:57:41 +08:00

259 lines
9.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Local credential guard for the Marqdo workspace.
The only place for local development credentials is the root repository's
git-ignored credential files (``.env.local`` or ``.secrets/*.env``). This
script proves two properties before a commit/push:
1. every credential file that exists in the workspace is ignored by git;
2. no credential value read from those files appears in the main repository or
in any initialized submodule (git index, tracked worktree files, untracked
files that are not ignored, git config or ``.gitmodules``).
It never prints a credential value. It is local-only: CI has no credential
file, so CI must keep using platform Secrets instead (see
docs/DEVELOPMENT-CREDENTIALS.md and marqdo#56 §8).
Usage:
python3 scripts/check-dev-secrets.py # exact-value scan (default)
python3 scripts/check-dev-secrets.py --generic # also warn about key-shaped text
python3 scripts/check-dev-secrets.py --strict # make generic warnings failures
"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# Credential files that are allowed to exist, but must be ignored by git.
CREDENTIAL_FILES = (
".env.local",
".env.local.sh",
".secrets/dev.env",
".secrets/git.env",
)
# Credential variable names inside those files.
SECRET_NAME_RE = re.compile(
r"(?:^|_)(?:API_?KEY|KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)(?:_|$)", re.IGNORECASE
)
# Shape-only heuristic used by --generic. Deliberately narrow to avoid noise.
GENERIC_PATTERNS = (
r"sk-[A-Za-z0-9_]{24,}",
r"ghp_[A-Za-z0-9]{30,}",
r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
)
# Documented fixtures that intentionally contain fake key-shaped strings.
GENERIC_ALLOWLIST = (
"packages/client/ui-secret-mask/tests/secret-rule.client.spec.ts",
"packages/credentials/credentials-local/tests/local.spec.ts",
"apps/web/tests/rich-text-quotes.e2e.ts",
"packages/session/message-quotes/tests/quote-user-text.client.spec.tsx",
)
MIN_VALUE_LEN = 16
def git(repo: Path, *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "-C", str(repo), *args],
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
def display(repo: Path) -> str:
try:
rel = repo.relative_to(ROOT)
return str(rel) if rel != Path(".") else "(main repo)"
except ValueError:
return str(repo)
def workspace_repos() -> list[Path]:
repos = [ROOT]
result = git(ROOT, "config", "--file", ".gitmodules", "--get-regexp", r"^submodule\..*\.path$")
if result.returncode == 0:
for line in result.stdout.splitlines():
_, _, path = line.partition(" ")
candidate = ROOT / path.strip()
if candidate.exists() and (candidate / ".git").exists():
repos.append(candidate)
return repos
def read_credentials() -> dict[str, str]:
"""Return {variable name: literal value} for local credential files."""
values: dict[str, str] = {}
for rel in CREDENTIAL_FILES:
path = ROOT / rel
if not path.is_file():
continue
for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, _, value = line.partition("=")
name = name.strip()
if name.startswith("export "):
name = name[len("export ") :].strip()
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
value = value[1:-1]
if not SECRET_NAME_RE.search(name):
continue
# ``CFLMY_API_KEY=$MARQDO_LLM_API_KEY`` is an alias, not a literal.
if value.startswith("$") or len(value) < MIN_VALUE_LEN:
continue
values[name] = value
return values
def check_ignored(repo: Path) -> list[str]:
problems: list[str] = []
for rel in CREDENTIAL_FILES:
path = repo / rel
if not path.is_file():
continue
ignored = git(repo, "check-ignore", "-q", "--", rel)
if ignored.returncode != 0:
problems.append(f"{display(repo)}: credential file {rel} exists but is NOT ignored")
return problems
def grep_patterns(repo: Path, patterns_file: Path) -> tuple[int, set[str]]:
"""Return (returncode, matching files) for a fixed-string multi-pattern grep.
The worktree pass includes untracked, non-ignored files; the index pass
covers staged content. ``--untracked`` and ``--cached`` cannot be combined.
"""
found: set[str] = set()
passes = (("--untracked",), ("--cached",))
for extra in passes:
result = git(repo, "grep", "-l", "-F", "-f", str(patterns_file), *extra)
if result.returncode not in (0, 1):
return result.returncode, found
for line in result.stdout.splitlines():
found.add(line)
return 0, found
def scan_repo(repo: Path, values: list[str], generic: bool) -> tuple[list[str], list[str]]:
leaks: list[str] = []
warnings: list[str] = []
# git config may embed credentials in remote URLs or extraheaders.
for git_dir_rel in (".git",):
marker = repo / git_dir_rel
config = marker / "config" if marker.is_dir() else None
if config is not None and config.is_file():
text = config.read_text(encoding="utf-8", errors="replace")
for value in values:
if value in text:
leaks.append(f"{display(repo)}: credential value in {git_dir_rel}/config")
if not values:
return leaks, warnings
# A delete-on-close temporary file stays locked against other processes on
# Windows, and ``git grep -f`` then fails with exit 128. Materialize the
# pattern file, close the descriptor and remove it once the scan is done.
descriptor, name = tempfile.mkstemp(prefix="mq-secret-", text=True)
os.close(descriptor)
patterns = Path(name)
try:
patterns.write_text("\n".join(values) + "\n", encoding="utf-8")
code, hits = grep_patterns(repo, patterns)
if code != 0:
warnings.append(f"{display(repo)}: git grep failed (exit {code}); result UNVERIFIED")
else:
for hit in sorted(hits):
leaks.append(f"{display(repo)}: credential value in {hit}")
finally:
patterns.unlink(missing_ok=True)
if generic:
for pattern in GENERIC_PATTERNS:
result = git(repo, "grep", "-l", "-E", "-e", pattern)
if result.returncode not in (0, 1):
warnings.append(f"{display(repo)}: generic scan failed (exit {result.returncode})")
continue
for hit in result.stdout.splitlines():
if any(hit.endswith(suffix) or suffix in hit for suffix in GENERIC_ALLOWLIST):
continue
warnings.append(f"{display(repo)}: key-shaped text in {hit}")
return leaks, warnings
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--generic", action="store_true", help="warn about key-shaped text")
parser.add_argument("--strict", action="store_true", help="treat generic warnings as failures")
parser.add_argument("--quiet", action="store_true")
args = parser.parse_args()
credentials = read_credentials()
repos = workspace_repos()
problems: list[str] = []
warnings: list[str] = []
for repo in repos:
problems.extend(check_ignored(repo))
if not credentials:
print("[WARN] no local credential file found; exact-value scan is vacuous", file=sys.stderr)
values = list(credentials.values())
for repo in repos:
leaks, repo_warnings = scan_repo(repo, values, args.generic)
problems.extend(leaks)
warnings.extend(repo_warnings)
# A credential value must never appear in a tracked .gitmodules either.
gitmodules = ROOT / ".gitmodules"
if gitmodules.is_file():
text = gitmodules.read_text(encoding="utf-8", errors="replace")
for value in values:
if value in text:
problems.append("(main repo): credential value in .gitmodules")
if problems:
print(f"[FAIL] credential guard found {len(problems)} problem(s):", file=sys.stderr)
for problem in problems:
print(f" - {problem}", file=sys.stderr)
print("Credential values are not printed. Rotate the credential if it reached a remote.",
file=sys.stderr)
return 1
for warning in warnings:
print(f"[WARN] {warning}", file=sys.stderr)
if warnings and args.strict:
print("[FAIL] --strict: generic warnings are failures", file=sys.stderr)
return 1
if not args.quiet:
names = ", ".join(sorted(credentials)) or "none"
print(
f"[PASS] {len(repos)} git repos scanned for {len(values)} credential value(s); "
f"no leak in index, worktree, config or .gitmodules; local credential files ignored."
)
print(f" credential variables considered: {names}")
return 0
if __name__ == "__main__":
raise SystemExit(main())