From 30aa9f6e9bbb0e1738e32120d11d0cf040bd5cfb Mon Sep 17 00:00:00 2001 From: xLagerFeuer <26746718+xLagerFeuer@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:01:01 +0000 Subject: [PATCH] Support explicit read-only GitHub CLI transport in publication gates --- CHANGELOG.md | 2 +- docs/PUBLICATION_HISTORY.md | 12 ++- scripts/gh_readonly_transport.py | 84 +++++++++++++++++ scripts/publication_history.py | 40 ++++---- scripts/validate_public_issue_payload.py | 6 +- tests/test_gh_readonly_transport.py | 112 +++++++++++++++++++++++ 6 files changed, 233 insertions(+), 23 deletions(-) create mode 100644 scripts/gh_readonly_transport.py create mode 100644 tests/test_gh_readonly_transport.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 67ddd14..7d112bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ ## Unreleased -No changes recorded after the v0.19.0 consolidation. +- **Read-only GitHub CLI transport (PATCH):** Add explicit `--transport gh` to the publication history and exact payload validators, delegating authentication to the configured GitHub CLI instead of handling credentials in agent command text. Preserve existing HTTP mode and all evidence, access, source, history and exact-consent gates; no automatic fallback or release bump. ## [0.19.0](changes/v0.19.0.md) — Source-aware Roadmap construction and verified publication diff --git a/docs/PUBLICATION_HISTORY.md b/docs/PUBLICATION_HISTORY.md index b718836..7fea51c 100644 --- a/docs/PUBLICATION_HISTORY.md +++ b/docs/PUBLICATION_HISTORY.md @@ -15,6 +15,16 @@ Before proposing another public Roadmap Issue, use the **read-only** publication For a read-only organization inventory, use `python3 scripts/publication_history.py --format json`. For any candidate, use the procedure below. The CLI never posts and the bounded archive remains incomplete. +## Explicit GitHub CLI transport + +For an operator runtime with an already configured and authorized GitHub CLI account, both `publication_history.py` and `validate_public_issue_payload.py` accept `--transport gh`. Use the same explicit transport for discovery, persisted-case approval and pre-POST recheck when appropriate. The default `--transport http` is unchanged for existing callers and CI. + +The CLI transport delegates authentication to `gh api --hostname github.com`; the Python scripts do not retrieve, print or pass a credential in command arguments. It accepts only the REST read routes required by the existing evidence scan (explicit GET) and the two fixed, read-only Discussion GraphQL query documents. GraphQL uses POST only as the query transport, never as a mutation. Pagination limits, first-party evidence, canonical metadata checks, exact approval fingerprint, owner PAUSE/STOP and external publication consent are unchanged. + +Use only when the runtime's configured access and applicable security policies authorize that read. Do not select this mode to override a denied operation or evade API limits; errors, missing CLI, missing authorization, rate limits, timeouts, malformed JSON and GraphQL errors remain fail-closed. No implicit retries, account switching or fallback to another credential/transport. The transport does not establish publisher identity or authorize a GitHub write; repeat the separate native route and actual publisher checks before approved publication. + +For example, append `--transport gh` to the existing commands below; no credential extraction is required. + ## Mandatory persisted Roadmap gate The history scan is deliberately a two-step workflow. Discovery and local draft checks do not make a proposal ready for the owner. @@ -67,7 +77,7 @@ The example is an interface illustration, not authorization or a new Browser Har The view uses the existing `roadmap_view.py` verified fork discovery and canonical case IDs; it reads case receipt and append-only `publication` events as proof. A GitHub URL *merely cited in a research file* is **not** evidence OpenSiro published it. Same-case publication in the **same action channel** returns `ALREADY_PUBLISHED` even if an old README said `NOT_PUBLISHED`. A separate fork vs original Issue remains a separately approvable action but returns overlap for review. Exact older OpenSiro-authored titles returned by provider search yield `REUSE_EXISTING`; related original/cross-project references yield `POSSIBLE_OVERLAP`. Insufficient provider, history or search coverage yields `HISTORY_UNVERIFIED`. -GitHub REST GET is used for original/fork Issues, PRs, and bounded Issue comments, while an authenticated **read-only GitHub GraphQL query** is used for Discussion content and comments. A missing token, 403/404, truncated comments, changed outbound SHA, source mismatch or unsupported channel yields `UNVERIFIED`. The CLI searches native original Issues **and PRs**, both by publisher and bounded terms, and reads bounded repository Discussions through authenticated read-only GraphQL when enabled. Missing token or pagination/completeness uncertainty is recorded as `HISTORY_UNVERIFIED`. Native REST Issue/PR search reads up to 1,000 results per query in 100-item pages; every page must have a consistent reported count, complete flag, expected length and distinct, correct-channel identities. A result beyond the provider cap, page error, count drift or duplicate remains unverified; a successful bounded scan is not exhaustive global history. CLI uses the existing GH_TOKEN/GITHUB_TOKEN runtime authentication if configured; exhausted anonymous REST quota is a blocker, not grounds for bypass. Native original search does not cover every alternate audience; new non-original-Issue channels remain conservatively unverified for novelty. Independently review source-native alternatives, actual maintainer feedback and the concrete user-visible delta. Keyword matches and bounded negative searches do not establish equivalence or novelty. +GitHub REST GET is used for original/fork Issues, PRs, and bounded Issue comments, while an authenticated **read-only GitHub GraphQL query** is used for Discussion content and comments. A missing token, 403/404, truncated comments, changed outbound SHA, source mismatch or unsupported channel yields `UNVERIFIED`. The CLI searches native original Issues **and PRs**, both by publisher and bounded terms, and reads bounded repository Discussions through authenticated read-only GraphQL when enabled. Missing token or pagination/completeness uncertainty is recorded as `HISTORY_UNVERIFIED`. Native REST Issue/PR search reads up to 1,000 results per query in 100-item pages; every page must have a consistent reported count, complete flag, expected length and distinct, correct-channel identities. A result beyond the provider cap, page error, count drift or duplicate remains unverified; a successful bounded scan is not exhaustive global history. The default HTTP transport uses existing GH_TOKEN/GITHUB_TOKEN runtime authentication if configured; the explicitly selected CLI transport uses the configured GitHub CLI authorization. Exhausted quota or denied access is a blocker, not grounds for bypass. Native original search does not cover every alternate audience; new non-original-Issue channels remain conservatively unverified for novelty. Independently review source-native alternatives, actual maintainer feedback and the concrete user-visible delta. Keyword matches and bounded negative searches do not establish equivalence or novelty. ## Approval packet / human review diff --git a/scripts/gh_readonly_transport.py b/scripts/gh_readonly_transport.py new file mode 100644 index 0000000..98d15c7 --- /dev/null +++ b/scripts/gh_readonly_transport.py @@ -0,0 +1,84 @@ +"""Explicit read-only GitHub CLI transport for publication evidence. + +GitHub CLI owns authentication. No credentials are extracted or printed. +No implicit retry, alternative account, transport fallback or write operation. +""" +import json +import re +import subprocess +from urllib.parse import unquote, urlsplit + +from aggregate import APIError + +DISCUSSION_QUERY = """query($owner:String!, $name:String!, $number:Int!) { + repository(owner:$owner, name:$name) { + discussion(number:$number) { + title body createdAt updatedAt author { login } + comments(first: 100) { + totalCount pageInfo { hasNextPage } + nodes { url body author { login } authorAssociation createdAt updatedAt } + } + } + } + }""" +DISCUSSION_SEARCH_QUERY = """query($owner:String!, $name:String!, $cursor:String) { + repository(owner:$owner, name:$name) { + discussions(first: 100, after:$cursor) { + totalCount pageInfo { hasNextPage endCursor } + nodes { number url title body updatedAt author { login } } + } + } + }""" + +READ_QUERIES = { + DISCUSSION_QUERY: {"owner", "name", "number"}, + DISCUSSION_SEARCH_QUERY: {"owner", "name", "cursor"}, +} + + +class GhReadOnlyTransport: + """One explicit host; REST GET and two fixed GraphQL query documents.""" + + def _run(self, args, data=None): + command = ["gh", "api", "--hostname", "github.com", + "-H", "Accept: application/vnd.github+json", + "-H", "X-GitHub-Api-Version: 2022-11-28", *args] + try: + result = subprocess.run(command, input=data, text=True, capture_output=True, + check=False, timeout=30) + except (OSError, subprocess.TimeoutExpired) as exc: + raise APIError(0, "GitHub CLI read unavailable") from exc + if result.returncode: + # Do not echo stderr/stdout, command payload, or credential information. + status = re.search(r"\bHTTP ([45][0-9]{2})\b", result.stderr or "") + code = int(status.group(1)) if status else 0 + raise APIError(code, f"GitHub CLI read failed (HTTP {code})" if code + else "GitHub CLI read failed") + try: + return json.loads(result.stdout) + except (ValueError, TypeError) as exc: + raise APIError(0, "GitHub CLI response is not JSON") from exc + + def get(self, path): + if (not isinstance(path, str) or not path.startswith("/") or path.startswith("//") + or any(ord(c) < 32 or ord(c) == 127 for c in path) + or any(c in path for c in ("{", "}"))): + raise APIError(0, "Unsupported GitHub REST read path") + parsed = urlsplit(path) + decoded = unquote(parsed.path) + if (parsed.scheme or parsed.netloc or parsed.fragment + or any(ord(c) < 32 or ord(c) == 127 for c in decoded) + or any(c in decoded for c in (chr(92), "{", "}")) + or any(s in (".", "..") for s in decoded.split("/")) + or not re.fullmatch(r"/(?:repos/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:/(?:contents(?:/[^?]*)?|git/ref/heads/[^?]+|issues/[1-9][0-9]*(?:/comments)?|pulls/[1-9][0-9]*))?|orgs/[A-Za-z0-9_.-]+/repos|search/issues)", parsed.path)): + raise APIError(0, "Unsupported GitHub REST read path") + return self._run(["--method", "GET", "--", path.lstrip("/")]) + + def query(self, query, variables): + if query not in READ_QUERIES or not isinstance(variables, dict) or set(variables) != READ_QUERIES[query]: + raise APIError(0, "Unsupported GitHub GraphQL read operation") + result = self._run(["--method", "POST", "--input", "-", "--", "graphql"], + json.dumps({"query": query, "variables": variables})) + if not isinstance(result, dict) or result.get("errors") or not isinstance(result.get("data"), dict): + raise APIError(0, "GraphQL readback errors") + return result["data"] diff --git a/scripts/publication_history.py b/scripts/publication_history.py index 7921a26..68c57e2 100644 --- a/scripts/publication_history.py +++ b/scripts/publication_history.py @@ -17,6 +17,7 @@ from urllib.error import HTTPError, URLError from aggregate import APIError, GitHub, api, REPOSITORY +from gh_readonly_transport import GhReadOnlyTransport, DISCUSSION_QUERY, DISCUSSION_SEARCH_QUERY from roadmap_view import roadmap_view, read_text from publication_archive import discover_archive from roadmap_proposal_gate import (ACTIONS, BLOCKED, VERIFIED, GATE_ERRORS, @@ -177,17 +178,7 @@ def _query(self, query, variables): def discussion(self, repo, number): owner, name = repo.split("/", 1) - query = """query($owner:String!, $name:String!, $number:Int!) { - repository(owner:$owner, name:$name) { - discussion(number:$number) { - title body createdAt updatedAt author { login } - comments(first: 100) { - totalCount pageInfo { hasNextPage } - nodes { url body author { login } authorAssociation createdAt updatedAt } - } - } - } - }""" + query = DISCUSSION_QUERY data = self._query(query, {"owner": owner, "name": name, "number": number}) item = (data.get("repository") or {}).get("discussion") if not isinstance(item, dict): @@ -197,14 +188,7 @@ def discussion(self, repo, number): def discussion_search(self, repo, terms): """Bounded first-party Discussion enumeration, not a semantic classifier.""" owner, name = repo.split("/", 1) - query = """query($owner:String!, $name:String!, $cursor:String) { - repository(owner:$owner, name:$name) { - discussions(first: 100, after:$cursor) { - totalCount pageInfo { hasNextPage endCursor } - nodes { number url title body updatedAt author { login } } - } - } - }""" + query = DISCUSSION_SEARCH_QUERY cursor = None rows = [] seen = set() @@ -235,6 +219,19 @@ def discussion_search(self, repo, terms): raise APIError(0, "GraphQL discussion scan bound reached") +class GhPublicationGitHub(ReadOnlyGitHub): + """Reuse the exact evidence/pagination logic with explicit CLI transport.""" + + def __init__(self): + self.transport = GhReadOnlyTransport() + + def get(self, path): + return self.transport.get(path) + + def _query(self, query, variables): + return self.transport.query(query, variables) + + def feedback_observation(client, repo, number, expected_count): """Bounded original Issue comments; do not score bot replies as acceptance.""" if expected_count == 0: @@ -820,8 +817,11 @@ def main(argv=None): p.add_argument("--previous-report", type=Path, help="approval-time JSON report; any changed evidence requires re-review") p.add_argument("--format", choices=["json"], default="json") + p.add_argument("--transport", choices=("http", "gh"), default="http", + help="explicit read-only GitHub CLI transport (no token extraction or fallback)") a = p.parse_args(argv) - client = ReadOnlyGitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN")) + client = (GhPublicationGitHub() if a.transport == "gh" else + ReadOnlyGitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN"))) source_before = source_error = None if a.candidate_original and a.candidate_kind in ACTIONS: try: diff --git a/scripts/validate_public_issue_payload.py b/scripts/validate_public_issue_payload.py index 86087ee..5c2cf3c 100644 --- a/scripts/validate_public_issue_payload.py +++ b/scripts/validate_public_issue_payload.py @@ -8,6 +8,7 @@ from pathlib import Path from validate_capability_roadmap import value from aggregate import GitHub +from gh_readonly_transport import GhReadOnlyTransport from roadmap_proposal_gate import (BLOCKED, VERIFIED, GATE_ERRORS, digest, review_evidence_sha256, verify_persisted_case) from preflight_publication_destination import (markdown_feature_template_requirements, @@ -295,6 +296,8 @@ def main(): help="local structural preparation only; never an approval preview") p.add_argument("--history-report", type=Path, help="fresh publication_history.py report for the exact committed candidate") + p.add_argument("--transport", choices=("http", "gh"), default="http", + help="explicit read-only GitHub CLI transport (no token extraction or fallback)") a = p.parse_args() if a.render_fork: if a.kind != "fork": @@ -341,7 +344,8 @@ def main(): raise ValueError("--history-report required; use --draft-only for local preparation") report = json.loads(a.history_report.read_text(encoding="utf-8")) proof = verify_issue_approval_case( - GitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN")), report, + (GhReadOnlyTransport() if a.transport == "gh" else + GitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN"))), report, a.kind, a.case_dir, a.repo, a.case_ref, title, body_bytes, a.source_head) except GATE_ERRORS as exc: print(BLOCKED + ": " + str(exc)) diff --git a/tests/test_gh_readonly_transport.py b/tests/test_gh_readonly_transport.py new file mode 100644 index 0000000..ed85b2b --- /dev/null +++ b/tests/test_gh_readonly_transport.py @@ -0,0 +1,112 @@ +"""Offline transport contract tests: no live requests and no writes.""" +import json +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +from aggregate import APIError +from gh_readonly_transport import GhReadOnlyTransport, DISCUSSION_QUERY, DISCUSSION_SEARCH_QUERY +from publication_history import GhPublicationGitHub, ReadOnlyGitHub + + +class GhReadOnlyTransportTests(unittest.TestCase): + def setUp(self): + self.transport = GhReadOnlyTransport() + + @staticmethod + def response(data, code=0, stderr=""): + return subprocess.CompletedProcess([], code, json.dumps(data), stderr) + + @patch("gh_readonly_transport.subprocess.run") + def test_exact_rest_get_and_page_passthrough(self, run): + path = "/search/issues?q=repo%3Aopensiro/upstream&per_page=100&page=2" + expected = {"items": [], "total_count": 0} + run.return_value = self.response(expected) + self.assertEqual(self.transport.get(path), expected) + args, kwargs = run.call_args + self.assertEqual(args[0], ["gh", "api", "--hostname", "github.com", + "-H", "Accept: application/vnd.github+json", + "-H", "X-GitHub-Api-Version: 2022-11-28", + "--method", "GET", "--", path[1:]]) + self.assertIsNone(kwargs["input"]) + self.assertTrue(kwargs["capture_output"]) + self.assertEqual(kwargs["timeout"], 30) + + @patch("gh_readonly_transport.subprocess.run") + def test_read_paths_and_no_host_or_operation_injection(self, run): + run.return_value = self.response({}) + for path in ("/repos/opensiro/upstream", "/repos/opensiro/upstream/contents/docs", + "/repos/opensiro/upstream/git/ref/heads/main", + "/repos/opensiro/upstream/issues/109/comments?per_page=100&page=1", + "/repos/opensiro/upstream/pulls/127", "/orgs/opensiro/repos"): + self.transport.get(path) + run.reset_mock() + for path in ("graphql", "/graphql", "/user", "//evil.example/repos/a/b", + "https://evil.example/repos/a/b", "/repos/a/b/actions/secrets", + "/repos/a/b/../c", "/repos/a/b/contents/%2e%2e", + "/repos/a/b/contents/%5c", "/repos/a/b/contents/%0a", + "/repos/a/b/contents/{branch}", "/repos/a/b?x={owner}", + "/repos/a/b\n", "/repos/a/b#fragment"): + with self.subTest(path=path), self.assertRaises(APIError): + self.transport.get(path) + run.assert_not_called() + + @patch("gh_readonly_transport.subprocess.run") + def test_error_status_no_fallback_and_no_raw_error_output(self, run): + for status in (401, 403, 404, 429, 500): + run.return_value = self.response({"private": "do not log"}, 1, + f"gh: private text (HTTP {status})") + with self.assertRaises(APIError) as error: + self.transport.get("/repos/opensiro/upstream") + self.assertEqual(error.exception.status, status) + self.assertNotIn("private", str(error.exception)) + self.assertEqual(run.call_count, 5) + for error in (FileNotFoundError(), subprocess.TimeoutExpired("gh", 30)): + run.side_effect = error + with self.assertRaises(APIError): + self.transport.get("/repos/opensiro/upstream") + + @patch("gh_readonly_transport.subprocess.run") + def test_non_json_and_graphql_errors_fail_closed(self, run): + run.return_value = subprocess.CompletedProcess([], 0, "login redirect", "") + with self.assertRaises(APIError): + self.transport.get("/repos/opensiro/upstream") + variables = {"owner": "opensiro", "name": "upstream", "number": 1} + for data in ({"errors": [{"message": "unavailable"}], "data": {}}, + {"data": None}, []): + run.return_value = self.response(data) + with self.assertRaises(APIError): + self.transport.query(DISCUSSION_QUERY, variables) + + @patch("gh_readonly_transport.subprocess.run") + def test_fixed_graphql_queries_only_and_typed_variables(self, run): + run.return_value = self.response({"data": {"repository": {}}}) + for query, variables in ((DISCUSSION_QUERY, {"owner": "opensiro", "name": "upstream", "number": 1}), + (DISCUSSION_SEARCH_QUERY, {"owner": "opensiro", "name": "upstream", "cursor": None})): + self.assertEqual(self.transport.query(query, variables), {"repository": {}}) + args, kwargs = run.call_args + self.assertEqual(args[0][-6:], ["--method", "POST", "--input", "-", "--", "graphql"]) + self.assertEqual(json.loads(kwargs["input"]), {"query": query, "variables": variables}) + run.reset_mock() + for query, variables in (("mutation { createIssue(input: {}) { clientMutationId }}", {}), + ("query { viewer { login }}", {}), + (DISCUSSION_QUERY, {"owner": "opensiro", "name": "upstream"})): + with self.assertRaises(APIError): + self.transport.query(query, variables) + run.assert_not_called() + + @patch("gh_readonly_transport.subprocess.run") + def test_existing_discussion_projection_unchanged(self, run): + data = {"repository": {"discussion": {"title": "test", "body": "example"}}} + run.return_value = self.response({"data": data}) + legacy = ReadOnlyGitHub() + with patch.object(legacy, "_query", return_value=data): + expected = legacy.discussion("opensiro/upstream", 1) + self.assertEqual(GhPublicationGitHub().discussion("opensiro/upstream", 1), expected) + + +if __name__ == "__main__": + unittest.main()