From 5aad9155b489f90210f6bcc008e47bc64aea0510 Mon Sep 17 00:00:00 2001 From: Sacha Tousignant <5469965+stousignant@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:30:57 -0400 Subject: [PATCH 1/2] ci: add documentation checks and secret-scanner backstop --- .github/workflows/ci.yml | 59 +++++ README.md | 13 ++ scripts/check_docs.py | 485 +++++++++++++++++++++++++++++++++++++++ scripts/check_secrets.py | 196 ++++++++++++++++ tests/test_checks.py | 299 ++++++++++++++++++++++++ 5 files changed, 1052 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 scripts/check_docs.py create mode 100644 scripts/check_secrets.py create mode 100644 tests/test_checks.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e44508e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: Documentation CI + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: documentation-ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - name: Check out full history + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Download and verify Gitleaks + shell: bash + run: | + set -euo pipefail + archive="$RUNNER_TEMP/gitleaks_8.30.1_linux_x64.tar.gz" + binary="$RUNNER_TEMP/gitleaks" + curl --fail --location --silent --show-error --proto '=https' --proto-redir '=https' --tlsv1.2 \ + --output "$archive" \ + https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz + printf '%s %s\n' \ + '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb' \ + "$archive" | sha256sum --check + tar -xzOf "$archive" gitleaks > "$binary" + chmod 0755 "$binary" + test -x "$binary" + + - name: Run standard-library tests and native scanner canaries + env: + GITLEAKS_BINARY: ${{ runner.temp }}/gitleaks + TMPDIR: ${{ runner.temp }} + run: python3 -m unittest discover -s tests -v + + - name: Validate documentation + run: python3 scripts/check_docs.py + + - name: Scan working-tree files + env: + GITLEAKS_BINARY: ${{ runner.temp }}/gitleaks + run: python3 scripts/check_secrets.py --working-tree + + - name: Scan all fetched Git history + env: + GITLEAKS_BINARY: ${{ runner.temp }}/gitleaks + run: python3 scripts/check_secrets.py --history diff --git a/README.md b/README.md index c51f41c..684386c 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,19 @@ blueprints/ Each recipe follows the same seven sections: Purpose, Inputs, Flow, Boundaries, Outputs, Adaptation, and Verification. Worked examples illustrate the design; they are not claims of an installed system or measured performance. +## Contributor validation + +Run these checks from the repository root with Python 3.10+ and the Gitleaks 8.30.1 binary available locally: + +```sh +python3 scripts/check_docs.py +GITLEAKS_BINARY=/path/to/gitleaks python3 scripts/check_secrets.py --working-tree +GITLEAKS_BINARY=/path/to/gitleaks python3 scripts/check_secrets.py --history +GITLEAKS_BINARY=/path/to/gitleaks python3 -m unittest discover -s tests -v +``` + +The documentation check enforces the [catalog's authoring contract](blueprints/README.md), catalog coverage, and local file links. It supports inline and explicit reference links, fenced/inline code, and public-looking HTTPS targets; ambiguous or unsupported syntax fails. Local anchor fragments are unsupported and rejected rather than treated as verified. HTTPS targets are syntax-checked, not fetched. Gitleaks uses its default pattern rules on working-tree files and locally fetched Git history; it does not verify credentials with live services, certify owner-private disclosure safety, or guarantee detection of every secret. Hosted CI runs after upload and cannot replace a pre-publication review. These checks are repository validation tooling, not an installer or runtime integration. + ## Scope The current kit is documentation-only. It does not include an installer, runtime integrations, credentials, scheduler configuration, or automated deployment. Choose those bindings in the environment that owns the work, and keep its privacy and approval rules intact. diff --git a/scripts/check_docs.py b/scripts/check_docs.py new file mode 100644 index 0000000..f87113b --- /dev/null +++ b/scripts/check_docs.py @@ -0,0 +1,485 @@ +#!/usr/bin/env python3 +"""Validate the repository's documented Markdown subset.""" + +from __future__ import annotations + +import argparse +import ipaddress +import os +import posixpath +import re +import subprocess +import sys +from pathlib import Path +from urllib.parse import unquote, urlsplit + +REPO_ROOT = Path(__file__).resolve().parents[1] +CORPUS_ROOT = Path("blueprints") +PLACEHOLDERS = {"", "", ""} +RECIPE_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*\.md$") +ENTITY_RE = re.compile(r"&(?:[A-Za-z][A-Za-z0-9]*|#(?:[0-9]+|[xX][0-9A-Fa-f]+));") +ANGLE_RE = re.compile(r"<([^<>\r\n]*)>") +INLINE_LINK_RE = re.compile(r"(!?)\[([^\[\]\n]+)\]\((<[^<>\s]+>|[^()\s]+)\)") +REFERENCE_LINK_RE = re.compile(r"(!?)\[([^\[\]\n]+)\]\[([^\[\]\n]*)\]") +REFERENCE_DEF_RE = re.compile(r"^ {0,3}\[([^\[\]\n]+)\]:[ \t]*(<[^<>\s]+>|[^\s]+)[ \t]*$") +DOUBLE_ENCODING_RE = re.compile(r"%[0-9A-Fa-f]{2}") +BARE_LINK_RE = re.compile(r"(?i)(? str: + text = raw.decode("utf-8") + if any(ord(char) not in (9, 10) and not 32 <= ord(char) <= 126 for char in text): + raise ValueError("unsupported Markdown character") + return text + + +def _mask_code(text: str) -> tuple[str, bool]: + chars = list(text) + offset = 0 + in_fence: tuple[str, int] | None = None + for line in text.splitlines(keepends=True): + body = line.rstrip("\n") + match = re.match(r"^ {0,3}(`{3,}|~{3,})(.*)$", body) + if in_fence is None and match: + marker = match.group(1) + if marker[0] == "`" and "`" in match.group(2): + return "".join(chars), False + in_fence = (marker[0], len(marker)) + elif in_fence is not None: + marker, length = in_fence + if re.match(rf"^ {{0,3}}{re.escape(marker)}{{{length},}}[ \t]*$", body): + in_fence = None + if in_fence is not None or match: + for index in range(offset, offset + len(line)): + if chars[index] != "\n": + chars[index] = " " + offset += len(line) + if in_fence is not None: + return "".join(chars), False + + masked = "".join(chars) + chars = list(masked) + index = 0 + while index < len(chars): + if chars[index] != "`": + index += 1 + continue + if index > 0 and chars[index - 1] == "\\": + return "".join(chars), False + end = index + 1 + while end < len(chars) and chars[end] == "`": + end += 1 + delimiter = masked[index:end] + closing = end + while True: + closing = masked.find(delimiter, closing) + if closing < 0: + break + run_end = closing + len(delimiter) + if (closing == 0 or masked[closing - 1] != "`") and ( + run_end == len(masked) or masked[run_end] != "`" + ): + break + closing = run_end + if closing < 0: + return "".join(chars), False + for position in range(index, closing + len(delimiter)): + if chars[position] != "\n": + chars[position] = " " + index = closing + len(delimiter) + return "".join(chars), True + + +def _valid_https_target(target: str) -> bool: + if "\\" in target or any(ord(char) < 33 or ord(char) > 126 for char in target): + return False + try: + raw_parts = urlsplit(target) + if "%" in raw_parts.netloc or re.search(r"%(?![0-9A-Fa-f]{2})", target): + return False + decoded = unquote(target, errors="strict") + if any(ord(char) < 33 or ord(char) > 126 for char in decoded) or DOUBLE_ENCODING_RE.search(decoded): + return False + parsed = urlsplit(decoded) + host = parsed.hostname + port = parsed.port + if ( + parsed.scheme.casefold() != "https" + or not parsed.netloc + or "@" in parsed.netloc + or host is None + or port not in (None, 443) + or host.endswith(".") + ): + return False + host = host.casefold() + try: + ipaddress.ip_address(host) + return False + except ValueError: + pass + if host == "localhost" or host.endswith( + (".localhost", ".local", ".internal", ".lan", ".test", ".invalid", ".example", ".onion", ".arpa") + ): + return False + labels = host.split(".") + return len(labels) >= 2 and bool(re.search(r"[a-z]", labels[-1])) and all( + re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) for label in labels + ) + except (UnicodeDecodeError, ValueError): + return False + + +def _link_target_is_safe(target: str, files: set[str], document: str) -> bool: + if target.startswith("<") and target.endswith(">"): + target = target[1:-1] + if target.startswith("https://"): + return _valid_https_target(target) + if ( + not target + or "%" in target + or target.startswith(("/", "~", "\\")) + or "\\" in target + or any(ord(char) < 33 or ord(char) > 126 for char in target) + ): + return False + try: + if re.search(r"%(?![0-9A-Fa-f]{2})", target): + return False + decoded = unquote(target, errors="strict") + if any(ord(char) < 33 or ord(char) > 126 for char in decoded) or DOUBLE_ENCODING_RE.search(decoded): + return False + parsed = urlsplit(decoded) + except (UnicodeDecodeError, ValueError): + return False + # Local anchors are outside the supported file-link subset: do not + # report an unchecked fragment as a verified link. + if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment: + return False + if not parsed.path: + return False + if parsed.path.startswith(("/", "~")) or "\\" in parsed.path: + return False + normalized = posixpath.normpath(posixpath.join(posixpath.dirname(document), parsed.path)) + if normalized.startswith("/") or normalized == ".." or normalized.startswith("../"): + return False + return normalized in files + + +def _validate_links(markdown: str, files: set[str], document: str) -> int: + masked, valid_code = _mask_code(markdown) + if not valid_code: + return 1 + errors = sum(1 for _ in ENTITY_RE.finditer(masked)) + protected: list[tuple[int, int]] = [] + targets: list[str] = [] + definitions: dict[str, str] = {} + offset = 0 + for line in masked.splitlines(keepends=True): + body = line.rstrip("\n") + definition = REFERENCE_DEF_RE.fullmatch(body) + if definition: + reference = " ".join(definition.group(1).casefold().split()) + if reference in definitions: + errors += 1 + definitions[reference] = definition.group(2) + targets.append(definition.group(2)) + protected.append((offset, offset + len(body))) + elif re.match(r"^ {0,3}\[[^\]\n]+\]:", body): + errors += 1 + protected.append((offset, offset + len(body))) + offset += len(line) + + chars = list(masked) + for start, end in protected: + for index in range(start, end): + if chars[index] != "\n": + chars[index] = " " + without_definitions = "".join(chars) + link_matches: list[tuple[int, int]] = [] + for pattern in (INLINE_LINK_RE, REFERENCE_LINK_RE): + for match in pattern.finditer(without_definitions): + if any(match.start() < end and match.end() > start for start, end in link_matches): + continue + link_matches.append((match.start(), match.end())) + if pattern is INLINE_LINK_RE: + targets.append(match.group(3)) + else: + reference = match.group(3) or match.group(2) + key = " ".join(reference.casefold().split()) + if key not in definitions: + errors += 1 + else: + targets.append(definitions[key]) + + chars = list(without_definitions) + for start, end in link_matches: + for index in range(start, end): + if chars[index] != "\n": + chars[index] = " " + remaining = "".join(chars) + if "[" in remaining or "]" in remaining: + errors += 1 + + for match in ANGLE_RE.finditer(masked): + value = match.group(1) + if f"<{value}>" in PLACEHOLDERS: + continue + if value.startswith("https://"): + targets.append(value) + else: + errors += 1 + stripped_angles = ANGLE_RE.sub("", masked) + if "<" in stripped_angles or ">" in stripped_angles: + errors += 1 + bare_text = ANGLE_RE.sub("", remaining) + if "@" in bare_text: + errors += 1 + for match in BARE_LINK_RE.finditer(bare_text): + targets.append(match.group(0)) + for target in targets: + if not _link_target_is_safe(target, files, document): + errors += 1 + return errors + + +def _is_frontmatter(text: str) -> bool: + return bool(text.splitlines() and text.splitlines()[0].strip() == "---") + + +def _raise_walk_error(error: OSError) -> None: + raise error + + +def _validate_recipe_headings(text: str) -> bool: + headings = [match.group(1) for match in re.finditer(r"^## ([^\n]+)$", text, re.MULTILINE)] + return tuple(headings) == REQUIRED_RECIPE_HEADINGS + + +def _walk_repository(root: Path) -> tuple[set[str], bool]: + files: set[str] = set() + safe = True + for current, directories, names in os.walk(root, topdown=True, followlinks=False, onerror=_raise_walk_error): + current_path = Path(current) + if current_path == root and ".git" in directories: + directories.remove(".git") + for name in list(directories): + path = current_path / name + if path.is_symlink(): + directories.remove(name) + elif not path.is_dir(): + safe = False + directories.remove(name) + for name in names: + if current_path == root and name == ".git": + continue + path = current_path / name + relative = path.relative_to(root).as_posix() + if not path.is_symlink() and path.is_file(): + files.add(relative) + elif not path.is_symlink(): + safe = False + return files, safe + + +def _tracked_symlinks(root: Path) -> tuple[set[str], bool]: + try: + result = subprocess.run( + ["git", "ls-files", "--stage", "-z"], + cwd=root, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=False, + timeout=15, + ) + except (OSError, subprocess.SubprocessError): + return set(), False + if result.returncode != 0: + return set(), False + symlinks: set[str] = set() + for entry in result.stdout.split(b"\0"): + if not entry: + continue + metadata, separator, path = entry.partition(b"\t") + if not separator: + return set(), False + mode = metadata.split(b" ", 1)[0] + if mode == b"120000": + symlinks.add(os.fsdecode(path)) + return symlinks, True + + +def _corpus_files(corpus: Path) -> tuple[dict[str, str], set[str], set[str], bool]: + documents: dict[str, str] = {} + symlinks: set[str] = set() + directories: set[str] = set() + safe = True + if corpus.is_symlink() or not corpus.is_dir(): + return documents, symlinks, directories, False + for current, child_directories, names in os.walk( + corpus, topdown=True, followlinks=False, onerror=_raise_walk_error + ): + current_path = Path(current) + for name in list(child_directories): + path = current_path / name + relative = path.relative_to(corpus).as_posix() + if path.is_symlink(): + symlinks.add(relative) + child_directories.remove(name) + elif path.is_dir(): + directories.add(relative) + else: + safe = False + child_directories.remove(name) + for name in names: + path = current_path / name + relative = path.relative_to(corpus).as_posix() + if path.is_symlink(): + symlinks.add(relative) + elif path.is_file() and path.suffix.casefold() == ".md": + try: + documents[relative] = _ascii_markdown(path.read_bytes()) + except (OSError, UnicodeError, ValueError): + safe = False + else: + safe = False + return documents, symlinks, directories, safe + + +def _valid_layout(documents: dict[str, str], directories: set[str]) -> bool: + expected_directories = {"skills", "automations"} + if directories != expected_directories or "README.md" not in documents: + return False + recipes = set(documents) - {"README.md"} + if not recipes or not any(path.startswith("skills/") for path in recipes): + return False + if not any(path.startswith("automations/") for path in recipes): + return False + folded: set[str] = set() + for path in documents: + if path.casefold() in folded: + return False + folded.add(path.casefold()) + if path == "README.md": + continue + parts = path.split("/") + if len(parts) != 2 or parts[0] not in expected_directories or not RECIPE_NAME_RE.fullmatch(parts[1]): + return False + return True + + +def _catalog_coverage(catalog: str, recipe_paths: set[str]) -> bool: + masked, valid_code = _mask_code(catalog) + if not valid_code: + return False + definitions: dict[str, str] = {} + protected: list[tuple[int, int]] = [] + targets: list[str] = [] + offset = 0 + for line in masked.splitlines(keepends=True): + body = line.rstrip("\n") + definition = REFERENCE_DEF_RE.fullmatch(body) + if definition: + key = " ".join(definition.group(1).casefold().split()) + definitions[key] = definition.group(2) + protected.append((offset, offset + len(body))) + offset += len(line) + chars = list(masked) + for start, end in protected: + for index in range(start, end): + if chars[index] != "\n": + chars[index] = " " + remaining = "".join(chars) + targets.extend(match.group(3) for match in INLINE_LINK_RE.finditer(remaining) if not match.group(1)) + for match in REFERENCE_LINK_RE.finditer(remaining): + if match.group(1): + continue + key = " ".join((match.group(3) or match.group(2)).casefold().split()) + if key in definitions: + targets.append(definitions[key]) + + linked: set[str] = set() + for target in targets: + if target.startswith("<") and target.endswith(">"): + target = target[1:-1] + parsed = urlsplit(target) + if parsed.scheme or parsed.netloc or not parsed.path: + continue + normalized = posixpath.normpath(posixpath.join(".", parsed.path)) + linked.add(normalized) + return recipe_paths.issubset(linked) + + +def _validate_repository(root: Path) -> bool: + root = root.resolve() + if not root.is_dir(): + return False + tracked_links, git_ok = _tracked_symlinks(root) + if not git_ok or tracked_links: + return False + all_files, tree_safe = _walk_repository(root) + if not tree_safe: + return False + + readme_path = root / "README.md" + if readme_path.is_symlink() or not readme_path.is_file(): + return False + try: + readme = _ascii_markdown(readme_path.read_bytes()) + except (OSError, UnicodeError, ValueError): + return False + if _is_frontmatter(readme) or _validate_links(readme, all_files, "README.md"): + return False + corpus = root / CORPUS_ROOT + documents, corpus_symlinks, corpus_directories, corpus_safe = _corpus_files(corpus) + if not corpus_safe or corpus_symlinks or not _valid_layout(documents, corpus_directories): + return False + corpus_paths = set(documents) + recipe_paths = corpus_paths - {"README.md"} + catalog = documents["README.md"] + if _is_frontmatter(catalog) or _validate_links(catalog, corpus_paths, "README.md"): + return False + if not _catalog_coverage(catalog, recipe_paths): + return False + for relative, text in documents.items(): + if _is_frontmatter(text): + return False + masked, valid_code = _mask_code(text) + if not valid_code: + return False + if relative != "README.md" and not _validate_recipe_headings(masked): + return False + if _validate_links(text, corpus_paths, relative): + return False + # A symlink at any component of a local link target is excluded from + # the regular-file set above, so it cannot satisfy a target lookup. + return True + + +def validate_repository(root: Path = REPO_ROOT) -> bool: + try: + return _validate_repository(root) + except (OSError, ValueError, UnicodeError, subprocess.SubprocessError): + return False + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Validate repository Markdown structure and local links") + parser.add_argument("--root", type=Path, default=REPO_ROOT, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + passed = validate_repository(args.root) + print("Documentation validation: " + ("PASS" if passed else "FAIL")) + return 0 if passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_secrets.py b/scripts/check_secrets.py new file mode 100644 index 0000000..f40c142 --- /dev/null +++ b/scripts/check_secrets.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Run pinned Gitleaks scans without exposing scanner output.""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +PINNED_VERSION = "8.30.1" +HISTORY_LOG_OPTIONS = "--all --full-history --text --no-textconv --no-ext-diff" +DEFAULT_CONFIG = "[extend]\nuseDefault = true\n" + + +def _clean_environment(home: Path, temp: Path) -> dict[str, str]: + return { + "HOME": str(home), + "PATH": "/usr/bin:/bin", + "TMPDIR": str(temp), + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + } + + +def _has_symlink(root: Path, include_git: bool) -> bool: + for current, directories, files in os.walk(root, topdown=True, followlinks=False): + current_path = Path(current) + if not include_git and current_path == root and ".git" in directories: + directories.remove(".git") + for name in (*directories, *files): + if (current_path / name).is_symlink(): + return True + return False + + +def _copy_working_tree(source: Path, destination: Path) -> bool: + if not source.is_dir() or _has_symlink(source, include_git=False): + return False + + def ignored(directory: str, names: list[str]) -> set[str]: + if Path(directory) == source: + return {".git"} if ".git" in names else set() + return set() + + try: + shutil.copytree(source, destination, ignore=ignored, symlinks=True) + # Rename repository controls so their contents are scanned, not loaded. + for name in (".gitleaks.toml", ".gitleaksignore"): + control = destination / name + if control.exists(): + renamed = destination / (name + ".scan-input") + if not control.is_file() or renamed.exists(): + return False + control.rename(renamed) + except (OSError, shutil.Error): + return False + return True + + +def _copy_history(source: Path, destination: Path, env: dict[str, str]) -> bool: + if not source.is_dir() or _has_symlink(source, include_git=True): + return False + try: + result = subprocess.run( + ["git", "clone", "--mirror", "--no-local", "--quiet", str(source), str(destination)], + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + timeout=120, + ) + except (OSError, subprocess.SubprocessError): + return False + return result.returncode == 0 + + +def _pinned_binary(binary: Path, env: dict[str, str]) -> bool: + if not binary.is_file() or not os.access(binary, os.X_OK): + return False + try: + result = subprocess.run( + [str(binary), "version"], + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=False, + timeout=10, + ) + except (OSError, subprocess.SubprocessError): + return False + return result.returncode == 0 and result.stdout.strip().decode("ascii", "ignore") == PINNED_VERSION + + +def scan(root: Path, mode: str, binary: str | Path | None = None) -> str: + """Return pass, finding, or error; never return scanner-provided text.""" + if mode not in {"working-tree", "history"}: + return "error" + configured_binary = binary if binary is not None else os.environ.get("GITLEAKS_BINARY") + if not configured_binary: + return "error" + executable = Path(configured_binary).expanduser().absolute() + try: + source = root.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="docs-ci-secrets-", dir=os.environ.get("TMPDIR")) as temp_name: + temp = Path(temp_name) + if temp == source or source in temp.parents: + return "error" + home = temp / "home" + home.mkdir() + env = _clean_environment(home, temp) + if not _pinned_binary(executable, env): + return "error" + + config = temp / "gitleaks.toml" + config.write_text(DEFAULT_CONFIG, encoding="ascii") + ignore_file = temp / "empty-ignore" + ignore_file.write_bytes(b"") + target = temp / "source" + if mode == "working-tree": + if not _copy_working_tree(source, target): + return "error" + command = [str(executable), "dir", "--config", str(config)] + else: + if not _copy_history(source, target, env): + return "error" + command = [str(executable), "git", "--config", str(config)] + + command.extend( + [ + "--gitleaks-ignore-path", + str(ignore_file), + "--ignore-gitleaks-allow", + "--exit-code", + "3", + "--no-banner", + "--redact=100", + ] + ) + if mode == "history": + command.extend(["--log-opts=" + HISTORY_LOG_OPTIONS]) + command.append(str(target)) + try: + result = subprocess.run( + command, + cwd=temp, + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + timeout=180, + ) + except (OSError, subprocess.SubprocessError): + return "error" + if result.returncode == 0: + return "pass" + if result.returncode == 3: + return "finding" + return "error" + except (OSError, ValueError, subprocess.SubprocessError): + return "error" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Scan working-tree files and Git history with Gitleaks 8.30.1") + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--working-tree", action="store_true", help="scan current working-tree files") + modes.add_argument("--history", action="store_true", help="scan all locally fetched Git history") + args = parser.parse_args(argv) + selected = ["working-tree"] if args.working_tree else ["history"] if args.history else ["working-tree", "history"] + failed = False + for mode in selected: + result = scan(REPO_ROOT, mode) + if result == "pass": + status = "PASS" + elif result == "finding": + status = "FAIL (finding)" + failed = True + else: + status = "ERROR (scanner unavailable or failed)" + failed = True + print(f"Secret scan ({mode}): {status}") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_checks.py b/tests/test_checks.py new file mode 100644 index 0000000..b519f52 --- /dev/null +++ b/tests/test_checks.py @@ -0,0 +1,299 @@ +from __future__ import annotations + +import contextlib +import io +import os +import secrets +import string +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +import check_docs +import check_secrets + + +SECTIONS = ("Purpose", "Inputs", "Flow", "Boundaries", "Outputs", "Adaptation", "Verification") + + +def _git(root: Path, *args: str) -> None: + subprocess.run( + ["git", "-C", str(root), *args], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + + +def _recipe(title: str = "Sample") -> str: + return "# " + title + "\n\n" + "\n\n".join(f"## {section}\n\nSample content." for section in SECTIONS) + "\n" + + +def _fixture(root: Path) -> Path: + (root / "blueprints" / "skills").mkdir(parents=True) + (root / "blueprints" / "automations").mkdir() + (root / "README.md").write_text( + "# Sample repository\n\n[Catalog](blueprints/README.md) and [license](LICENSE).\n", + encoding="ascii", + ) + (root / "LICENSE").write_text("Sample license text.\n", encoding="ascii") + (root / "blueprints" / "README.md").write_text( + "# Sample catalog\n\n## Recipes\n\n" + "- [Sample skill](skills/sample-skill.md)\n" + "- [Sample automation](automations/sample-automation.md)\n\n" + "## Authoring contract\n\nRecipe files are plain Markdown.\n", + encoding="ascii", + ) + (root / "blueprints" / "skills" / "sample-skill.md").write_text(_recipe(), encoding="ascii") + (root / "blueprints" / "automations" / "sample-automation.md").write_text( + _recipe("Sample automation"), encoding="ascii" + ) + _git(root, "init", "--quiet") + _git(root, "add", "README.md", "LICENSE", "blueprints") + return root + + +def _temp_root() -> tempfile.TemporaryDirectory[str]: + return tempfile.TemporaryDirectory(prefix="docs-ci-tests-", dir=os.environ.get("TMPDIR")) + + +class DocumentationChecks(unittest.TestCase): + def test_published_corpus_passes(self) -> None: + self.assertTrue(check_docs.validate_repository(ROOT)) + + def test_valid_synthetic_corpus_passes(self) -> None: + with _temp_root() as directory: + self.assertTrue(check_docs.validate_repository(_fixture(Path(directory)))) + + def test_broken_local_link_fails(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + with (root / "README.md").open("a", encoding="ascii") as stream: + stream.write("\n[missing](missing.md)\n") + self.assertFalse(check_docs.validate_repository(root)) + + def test_recipe_section_order_fails(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + recipe = root / "blueprints" / "skills" / "sample-skill.md" + recipe.write_text(recipe.read_text(encoding="ascii").replace("## Inputs", "## Outputs", 1), encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + + def test_catalog_must_cover_every_recipe(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + catalog = root / "blueprints" / "README.md" + catalog.write_text(catalog.read_text(encoding="ascii").replace("- [Sample automation]", "- Sample automation"), encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + + def test_reference_links_cover_catalog_and_extra_local_links_are_allowed(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + catalog = root / "blueprints" / "README.md" + text = catalog.read_text(encoding="ascii").replace( + "[Sample skill](skills/sample-skill.md)", "[Sample skill][skill]" + ) + catalog.write_text(text + "\n[skill]: skills/sample-skill.md\n[Catalog](README.md)\n", encoding="ascii") + self.assertTrue(check_docs.validate_repository(root)) + + def test_ascii_frontmatter_and_exact_layout_are_enforced(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + readme = root / "blueprints" / "skills" / "sample-skill.md" + readme.write_bytes(readme.read_bytes() + b"\xc3\xa9") + self.assertFalse(check_docs.validate_repository(root)) + with _temp_root() as directory: + root = _fixture(Path(directory)) + readme = root / "blueprints" / "skills" / "sample-skill.md" + readme.write_text("---\ntitle: hidden metadata\n---\n" + _recipe(), encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + with _temp_root() as directory: + root = _fixture(Path(directory)) + (root / "blueprints" / "extra").mkdir() + self.assertFalse(check_docs.validate_repository(root)) + with _temp_root() as directory: + root = _fixture(Path(directory)) + (root / "blueprints" / "skills" / "extra.txt").write_text("not a recipe\n", encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + + def test_escape_and_tracked_symlink_fail(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + recipe = root / "blueprints" / "skills" / "sample-skill.md" + recipe.write_text(recipe.read_text(encoding="ascii") + "\n[escape](../../README.md)\n", encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + with _temp_root() as directory: + root = _fixture(Path(directory)) + (root / "outside-link").symlink_to("LICENSE") + _git(root, "add", "outside-link") + self.assertFalse(check_docs.validate_repository(root)) + + def test_document_and_target_symlinks_fail(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + (root / "blueprints" / "skills" / "linked.md").symlink_to("sample-skill.md") + self.assertFalse(check_docs.validate_repository(root)) + with _temp_root() as directory: + root = _fixture(Path(directory)) + (root / "linked-license").symlink_to("LICENSE") + with (root / "README.md").open("a", encoding="ascii") as stream: + stream.write("\n[linked license](linked-license)\n") + self.assertFalse(check_docs.validate_repository(root)) + + def test_unsupported_markup_links_and_non_https_targets_fail(self) -> None: + invalid = ( + "\n[anchor](#missing-anchor)\n", + "\n[anchor](sample-skill.md#missing-anchor)\n", + "\n\n", + "\n&\n", + "\n[shortcut]\n", + "\n[web](http://example.org/path)\n", + "\n\n", + ) + for addition in invalid: + with self.subTest(addition=addition), _temp_root() as directory: + root = _fixture(Path(directory)) + recipe = root / "blueprints" / "skills" / "sample-skill.md" + recipe.write_text(recipe.read_text(encoding="ascii") + addition, encoding="ascii") + self.assertFalse(check_docs.validate_repository(root)) + + def test_public_https_link_is_syntax_checked_without_fetching(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + catalog = root / "blueprints" / "README.md" + catalog.write_text(catalog.read_text(encoding="ascii") + "\n[Public](https://github.com/example/project)\n", encoding="ascii") + self.assertTrue(check_docs.validate_repository(root)) + + def test_code_markup_is_masked_but_unclosed_fence_fails(self) -> None: + with _temp_root() as directory: + root = _fixture(Path(directory)) + recipe = root / "blueprints" / "skills" / "sample-skill.md" + recipe.write_text( + recipe.read_text(encoding="ascii") + + "\n```text\n