From 09ab74bf7c4933463d4060a223fd7ad96f3cafdb Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:50:06 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A9=20Add=20redirect-aware=20PR=20auto?= =?UTF-8?q?fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Guard moved and removed documentation routes, generate contextual permanent Nginx redirects only for unambiguous moves, and prevent untrusted redirect patches from bypassing privileged validation. Add SDEX regression tests and read-only PR checks. Co-authored-by: ChatGPT 6 --- .github/workflows/pr-autofix-apply.yml | 27 ++- .github/workflows/pr-autofix.yml | 28 ++- .github/workflows/pr-redirect-regression.yml | 33 ++++ scripts/check_doc_redirects.py | 184 +++++++++++++++++++ tests/test_doc_redirects.py | 121 ++++++++++++ 5 files changed, 387 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/pr-redirect-regression.yml create mode 100644 scripts/check_doc_redirects.py create mode 100644 tests/test_doc_redirects.py diff --git a/.github/workflows/pr-autofix-apply.yml b/.github/workflows/pr-autofix-apply.yml index 5aaa7c9922..00eaa11dae 100644 --- a/.github/workflows/pr-autofix-apply.yml +++ b/.github/workflows/pr-autofix-apply.yml @@ -153,17 +153,38 @@ jobs: - name: Apply and constrain validated patch if: steps.pr.outputs.run == 'true' && steps.artifact.outputs.has_changes == 'true' working-directory: work + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ steps.pr.outputs.pr_number }} run: | set -euo pipefail patch="$RUNNER_TEMP/pr-autofix/autofix.patch" + + # Privileged apply must not trust redirect changes from PR artifacts. + # Recompute them using trusted default-branch code and compare patches. + if git apply --numstat "$patch" | awk '$3 == "nginx/includes/redirects.conf" {found=1} END {exit !found}'; then + base_sha="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '.base.sha')" + trusted="$RUNNER_TEMP/trusted-check-doc-redirects.py" + gh api "repos/${GITHUB_REPOSITORY}/contents/scripts/check_doc_redirects.py?ref=${GITHUB_SHA}" --jq '.content' | base64 -d > "$trusted" + test -s "$trusted" + git fetch --depth=1 "https://github.com/${GITHUB_REPOSITORY}.git" "$base_sha" + python3 "$trusted" --base "$base_sha" --head HEAD --mode fix \ + --pr-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/${PR_NUMBER}" + git diff --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/expected-redirect.patch" + git checkout -- nginx/includes/redirects.conf + fi git apply --check "$patch" git apply --index "$patch" + if [[ -f "$RUNNER_TEMP/expected-redirect.patch" ]]; then + git diff --cached --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/applied-redirect.patch" + diff -u "$RUNNER_TEMP/expected-redirect.patch" "$RUNNER_TEMP/applied-redirect.patch" + fi count=0 while IFS= read -r -d '' path; do count=$((count + 1)) case "$path" in - routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx) + nginx/includes/redirects.conf|routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx) ;; *) echo "::error::Artifact attempted to change disallowed path: $path" @@ -191,7 +212,7 @@ jobs: set -euo pipefail git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git commit -m '🤖 Apply automated PR fixes' + git commit -m '🔩 Apply validated PR autofixes' -m 'Apply validated formatting, generated routes, and documentation redirects.' -m 'Co-authored-by: ChatGPT 6 ' echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Push bot commit @@ -239,7 +260,7 @@ jobs: set -euo pipefail marker='' body="$marker - Autofix found a validated formatting, lint, or generated-route patch, but the upstream workflow could not push to this PR branch. Download and extract the \`pr-autofix-*\` artifact from the [autofix run]($RUN_URL), then run \`git apply autofix.patch\` on the PR branch." + Autofix produced a validated formatting, lint, generated-route, or redirect patch but could not push to this PR branch. Any added redirect contains a comment explaining the move and its originating PR. Download and extract the \`pr-autofix-*\` artifact from the [autofix run]($RUN_URL), then run \`git apply autofix.patch\` on the PR branch." comment_id="$(gh api --paginate "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \ --jq ".[] | select(.body | contains(\"$marker\")) | .id" | head -n 1)" diff --git a/.github/workflows/pr-autofix.yml b/.github/workflows/pr-autofix.yml index 35c894d3cb..9a94aa425b 100644 --- a/.github/workflows/pr-autofix.yml +++ b/.github/workflows/pr-autofix.yml @@ -46,6 +46,9 @@ jobs: - name: Install dependencies run: pnpm install --prefer-offline --frozen-lockfile + - name: Test redirect regression behavior + run: python3 -m unittest discover -s tests -p test_doc_redirects.py + - name: Generate formatting and lint fixes run: | set -euo pipefail @@ -65,6 +68,18 @@ jobs: git reset --hard "$HEAD_SHA" git clean -fd + - name: Generate safe documentation redirects + env: + PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }} + run: | + set -euo pipefail + git remote add base "https://github.com/${GITHUB_REPOSITORY}.git" + git fetch base "refs/heads/${BASE_REF}:refs/remotes/base/${BASE_REF}" + python3 scripts/check_doc_redirects.py --base "base/${BASE_REF}" --head HEAD --mode fix --pr-url "$PR_URL" + git diff --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/redirect.patch" + git reset --hard "$HEAD_SHA" + git clean -fd + - name: Assemble autofix patch id: patch run: | @@ -77,6 +92,10 @@ jobs: git apply "$RUNNER_TEMP/routes.patch" fi + if [[ -s "$RUNNER_TEMP/redirect.patch" ]]; then + git apply "$RUNNER_TEMP/redirect.patch" + fi + git diff --binary > "$RUNNER_TEMP/autofix.patch" if [[ -s "$RUNNER_TEMP/autofix.patch" ]]; then echo "has_changes=true" >> "$GITHUB_OUTPUT" @@ -93,7 +112,7 @@ jobs: while IFS= read -r -d '' path; do count=$((count + 1)) case "$path" in - routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx) + nginx/includes/redirects.conf|routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx) ;; *) echo "::error::Autofix attempted to change disallowed path: $path" @@ -122,6 +141,11 @@ jobs: git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git commit -m 'Autofix validation tree' + - name: Validate documentation redirect coverage + env: + PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }} + run: python3 scripts/check_doc_redirects.py --base "base/${BASE_REF}" --head HEAD --mode check --pr-url "$PR_URL" + - name: Check MDX formatting run: git update-index -g && pnpm ci:mdx @@ -131,8 +155,6 @@ jobs: - name: Check new absolute internal links run: | set -euo pipefail - git remote add base "https://github.com/${GITHUB_REPOSITORY}.git" - git fetch base "$BASE_REF" --depth=1 scripts/check-relative-links.sh --range "base/${BASE_REF}...HEAD" \ || { echo "::error::New absolute /docs link(s) found above."; exit 1; } diff --git a/.github/workflows/pr-redirect-regression.yml b/.github/workflows/pr-redirect-regression.yml new file mode 100644 index 0000000000..4d63125d94 --- /dev/null +++ b/.github/workflows/pr-redirect-regression.yml @@ -0,0 +1,33 @@ +name: Check documentation redirect regressions + +on: + pull_request: + paths: + - "docs/**" + - "nginx/includes/redirects.conf" + - "scripts/check_doc_redirects.py" + - "tests/test_doc_redirects.py" + - ".github/workflows/pr-redirect-regression.yml" + +permissions: + contents: read + +jobs: + redirect-check: + name: Preserve moved documentation URLs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Run redirect regression tests + run: python3 -m unittest discover -s tests -p test_doc_redirects.py + - name: Verify moved page redirects + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }} + run: | + set -euo pipefail + git fetch --depth=1 origin "$BASE_SHA" + python3 scripts/check_doc_redirects.py --base "$BASE_SHA" --head HEAD --mode check --pr-url "$PR_URL" diff --git a/scripts/check_doc_redirects.py b/scripts/check_doc_redirects.py new file mode 100644 index 0000000000..6b55bfee37 --- /dev/null +++ b/scripts/check_doc_redirects.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Detect removed docs URLs and propose safe, documented Nginx redirects. + +Only moves with uniquely identified destinations receive an automatic fix. +Ambiguous deletions and invalid redirect chains must be reviewed manually. +""" + +import argparse +import re +import subprocess +import sys +from pathlib import Path + +REDIRECTS = Path("nginx/includes/redirects.conf") +DOC_SUFFIXES = (".md", ".mdx") +REWRITE = re.compile(r'^\s*rewrite\s+(\^\S+)\s+"([^"\n]+)"\s+permanent\s*;', re.M) +SLUG = re.compile(r'^slug:\s*["\']?([^\s"\']+)', re.M) + + +def git(*args): + result = subprocess.run(["git", *args], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return result.stdout.decode("utf-8", errors="replace") + + +def is_doc(path): + return path.startswith("docs/") and path.endswith(DOC_SUFFIXES) + + +def route(path, content=""): + """Map ordinary docs paths and supported absolute Docusaurus slugs to URLs.""" + if not is_doc(path): + return None + frontmatter = content.split("---", 2) + if content.startswith("---") and len(frontmatter) > 2: + match = SLUG.search(frontmatter[1]) + if match: + slug = match.group(1) + if not slug.startswith("/"): + return None # Relative slugs require manual inspection. + return ("/docs" + slug).rstrip("/") if not slug.startswith("/docs/") else slug.rstrip("/") + raw = "/" + path.rsplit(".", 1)[0] + return raw[:-6] if raw.endswith("/index") else raw + + +def changed_docs(base, head): + """Return removed or renamed pages, plus candidate newly added pages.""" + changes = git("diff", "--name-status", "-M", "--diff-filter=ADR", base, head, "--", "docs/") + removed = [] + added = [] + for row in changes.splitlines(): + fields = row.split("\t") + action = fields[0][0] + if action == "R" and len(fields) == 3: + old, new = fields[1:] + if is_doc(old): + removed.append((old, new if is_doc(new) else None)) + if is_doc(new): + added.append(new) + elif action == "D" and len(fields) == 2 and is_doc(fields[1]): + removed.append((fields[1], None)) + elif action == "A" and len(fields) == 2 and is_doc(fields[1]): + added.append(fields[1]) + return removed, added + + +def current_docs(head): + paths = git("ls-tree", "-r", "--name-only", head, "--", "docs/").splitlines() + docs = {path: "" for path in paths if is_doc(path)} + # Read bodies only where an explicit slug might override a file's URL. + result = subprocess.run( + ["git", "grep", "-l", "^slug:", head, "--", "docs/"], + check=False, capture_output=True, text=True, + ) + if result.returncode not in (0, 1): + raise RuntimeError(result.stderr) + for row in result.stdout.splitlines(): + path = row.split(":", 1)[1] + if path in docs: + docs[path] = git("show", f"{head}:{path}") + return docs + + +def redirects(contents): + return [(re.compile(source), target) for source, target in REWRITE.findall(contents)] + + +def lookup(url, rules): + """Resolve permanent rewrite chains without accepting loops or external URLs.""" + visited = set() + current = url + for _ in range(20): + if current in visited: + return None, "redirect loop" + visited.add(current) + matches = [(pattern, target) for pattern, target in rules if pattern.match(current)] + if not matches: + return current, None + pattern, target = matches[0] + match = pattern.match(current) + next_url = re.sub( + r"\$(\d+)", + lambda m: (match.group(int(m.group(1))) or "") if int(m.group(1)) <= (match.lastindex or 0) else "", + target, + ) + current = next_url.split("#", 1)[0].split("?", 1)[0] + if not current.startswith("/docs"): + return None, "external or unsupported redirect destination" + return None, "redirect chain too long" + + +def assess(removed, added, before_docs, after_docs, conf, pr_url): + """Return safe generated rewrite statements and unresolved problems.""" + live_routes = {route(path, content) for path, content in after_docs.items()} + live_routes.discard(None) + candidates = {} + for path in added: + candidates.setdefault(Path(path).name, []).append(path) + rules = redirects(conf) + new_rules = [] + problems = [] + for old, moved in removed: + previous = route(old, before_docs[old]) + if previous is None: + problems.append(f"{old}: unsupported slug; check redirect manually") + continue + if previous in live_routes: + continue + new = moved + if not new: + matches = candidates.get(Path(old).name, []) + if len(matches) == 1: + new = matches[0] + replacement = route(new, after_docs[new]) if new in after_docs else None + resolved, error = lookup(previous, rules) + if error: + problems.append(f"{previous}: {error}") + continue + if resolved != previous: + if resolved not in live_routes: + problems.append(f"{previous}: redirect points to missing {resolved}") + continue + if replacement is None or replacement == previous or replacement not in live_routes: + problems.append(f"{previous}: removed without a unique, live replacement; add a reviewed redirect") + continue + if any(pattern.match(previous) for pattern, _ in rules): + problems.append(f"{previous}: existing redirect must be reviewed") + continue + # A contextual comment explains *why* the rule exists, not merely its URL. + explanation = f"# Preserve links after moving {previous} to {replacement} ({pr_url})" + escaped = re.escape(previous).replace("\\-", "-") + statement = f'rewrite ^{escaped}$ "{replacement}" permanent;' + new_rules.append(explanation + "\n" + statement) + rules.append((re.compile("^" + re.escape(previous) + "$"), replacement)) + return new_rules, problems + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base", required=True, help="Git base ref before the PR") + parser.add_argument("--head", default="HEAD", help="Git head ref") + parser.add_argument("--mode", choices=("check", "fix"), default="check") + parser.add_argument("--pr-url", default="https://github.com/stellar/stellar-docs/pulls") + args = parser.parse_args() + removed, added = changed_docs(args.base, args.head) + if not removed: + print("No moved or deleted documentation pages") + return 0 + after = current_docs(args.head) + before = {old: git("show", f"{args.base}:{old}") for old, _ in removed} + conf = REDIRECTS.read_text(encoding="utf-8") + fixes, problems = assess(removed, added, before, after, conf, args.pr_url) + if fixes and args.mode == "fix": + with REDIRECTS.open("a", encoding="utf-8") as stream: + stream.write("\n# Automatically preserved documentation URLs\n" + "\n\n".join(fixes) + "\n") + print(f"Added {len(fixes)} documented Nginx redirects") + elif fixes: + problems.extend(f"Missing permanent redirect: {rule.splitlines()[-1]}" for rule in fixes) + for error in problems: + print(f"::error::{error}", file=sys.stderr) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_doc_redirects.py b/tests/test_doc_redirects.py new file mode 100644 index 0000000000..48d5c801be --- /dev/null +++ b/tests/test_doc_redirects.py @@ -0,0 +1,121 @@ +"""Redirect regression tests, including the #1637/#2858 SDEX incident.""" + +import importlib.util +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "check_doc_redirects.py" +spec = importlib.util.spec_from_file_location("check_doc_redirects", SCRIPT) +redirects = importlib.util.module_from_spec(spec) +spec.loader.exec_module(redirects) +OLD = "docs/learn/encyclopedia/sdex/liquidity-on-stellar-sdex-liquidity-pools.mdx" +NEW = "docs/learn/fundamentals/liquidity-on-stellar-sdex-liquidity-pools.mdx" +OLD_URL = "/" + OLD[:-4] +NEW_URL = "/" + NEW[:-4] +SOURCE = "https://github.com/stellar/stellar-docs/pull/1637" + + +class RedirectChecks(unittest.TestCase): + def test_missing_sdex_redirect_fails_before_2858(self): + before = {OLD: "---\ntitle: Liquidity on Stellar\n---\n"} + after = {NEW: before[OLD]} + conf = f'rewrite ^/docs/(learn/)?glossary/liquidity-pools$ "{OLD_URL}#liquidity-pools" permanent;\n' + additions, errors = redirects.assess([(OLD, NEW)], [NEW], before, after, conf, SOURCE) + self.assertEqual(errors, []) + self.assertEqual(len(additions), 1) + self.assertIn("# Preserve links after moving", additions[0]) + self.assertIn(SOURCE, additions[0]) + self.assertIn(f'rewrite ^{OLD_URL}$ "{NEW_URL}" permanent;', additions[0]) + _, errors = redirects.assess([(OLD, NEW)], [NEW], before, after, conf + additions[0], SOURCE) + self.assertEqual(errors, []) + + def test_2858_existing_fix_passes(self): + before = {OLD: "---\ntitle: Liquidity\n---\n"} + after = {NEW: before[OLD]} + conf = f'rewrite ^{OLD_URL}$ "{NEW_URL}" permanent;\n' + fixes, errors = redirects.assess([(OLD, NEW)], [NEW], before, after, conf, SOURCE) + self.assertEqual((fixes, errors), ([], [])) + + def test_redirect_loop_and_broken_destination_fail(self): + before = {OLD: ""} + after = {NEW: ""} + loop = f'rewrite ^{OLD_URL}$ "{OLD_URL}" permanent;\n' + _, errors = redirects.assess([(OLD, NEW)], [NEW], before, after, loop, SOURCE) + self.assertIn("redirect loop", errors[0]) + wrong = f'rewrite ^{OLD_URL}$ "/docs/removed-page" permanent;\n' + _, errors = redirects.assess([(OLD, NEW)], [NEW], before, after, wrong, SOURCE) + self.assertIn("missing", errors[0]) + + def test_ambiguous_removal_does_not_autofix(self): + before = {OLD: ""} + after = {"docs/elsewhere/a.mdx": ""} + fixes, errors = redirects.assess([(OLD, None)], [], before, after, "", SOURCE) + self.assertEqual(fixes, []) + self.assertIn("without a unique", errors[0]) + + def test_renames_and_deletions_from_git_diff(self): + with tempfile.TemporaryDirectory() as tmp: + repo = Path(tmp) + def git(*args): + return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True).stdout.strip() + git("init", "-q") + git("config", "user.email", "tests@example.com") + git("config", "user.name", "Redirect Test") + src = repo / OLD + src.parent.mkdir(parents=True) + src.write_text("---\ntitle: Stellar liquidity\n---\nText\n") + git("add", ".") + git("commit", "-qm", "Initial SDEX") + base = git("rev-parse", "HEAD") + target = repo / NEW + target.parent.mkdir(parents=True) + src.rename(target) + git("add", "-A") + git("commit", "-qm", "Move SDEX") + prior_git = redirects.git + redirects.git = lambda *args: git(*args) + try: + removed, added = redirects.changed_docs(base, "HEAD") + self.assertEqual(removed, [(OLD, NEW)]) + self.assertEqual(added, [NEW]) + finally: + redirects.git = prior_git + + + def test_cli_fails_then_autofixes_sdex_move(self): + with tempfile.TemporaryDirectory() as tmp: + repo = Path(tmp) + def git(*args): + return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True).stdout.strip() + git("init", "-q") + git("config", "user.email", "tests@example.com") + git("config", "user.name", "Redirect Test") + old = repo / OLD + old.parent.mkdir(parents=True) + old.write_text("---\ntitle: SDEX liquidity\n---\nContent\n") + conf = repo / "nginx/includes/redirects.conf" + conf.parent.mkdir(parents=True) + conf.write_text(f'rewrite ^/docs/(learn/)?glossary/liquidity-pools$ "{OLD_URL}#liquidity-pools" permanent;\n') + git("add", ".") + git("commit", "-qm", "Before SDEX move") + base = git("rev-parse", "HEAD") + new = repo / NEW + new.parent.mkdir(parents=True) + old.rename(new) + git("add", "-A") + git("commit", "-qm", "Move SDEX without redirect") + def run(mode): + return subprocess.run(["python3", str(SCRIPT), "--base", base, "--mode", mode, "--pr-url", SOURCE], cwd=repo, capture_output=True, text=True) + self.assertNotEqual(run("check").returncode, 0) + result = run("fix") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(run("check").returncode, 0) + self.assertIn(SOURCE, conf.read_text()) + self.assertIn(f'rewrite ^{OLD_URL}$ "{NEW_URL}" permanent;', conf.read_text()) + + + +if __name__ == "__main__": + unittest.main()