Skip to content

Commit 236a79f

Browse files
test(ci): verify GitHub installation token compatibility
1 parent ed32f76 commit 236a79f

7 files changed

Lines changed: 235 additions & 5 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ jobs:
3030
swift --version
3131
- name: Verify deterministic behavior
3232
run: make verify
33+
- name: Verify GitHub token authentication
34+
env:
35+
GH_TOKEN: ${{ github.token }}
36+
run: python3 scripts/verify_github_token.py
3337
- name: Ensure XcodeGen
3438
env:
3539
HOMEBREW_NO_AUTO_UPDATE: 1

‎Makefile‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ DEVELOPER_DIR ?= /Applications/Xcode.app/Contents/Developer
66
export DEVELOPER_DIR
77
export DEVELOPMENT_TEAM
88

9-
verify: verify-context verify-fork-sync verify-image-compression test harness verify-harness-cli verify-appcast verify-release-metadata verify-release-notarization verify-release-publication verify-homebrew verify-signing-entitlements verify-native-qa verify-native-checks-runner verify-batch-rename-capture verify-batch-rename-access verify-file-info-capture
9+
verify: verify-context verify-fork-sync verify-github-token verify-image-compression test harness verify-harness-cli verify-appcast verify-release-metadata verify-release-notarization verify-release-publication verify-homebrew verify-signing-entitlements verify-native-qa verify-native-checks-runner verify-batch-rename-capture verify-batch-rename-access verify-file-info-capture
1010

1111
.PHONY: verify-file-info-capture
1212
verify-file-info-capture:
@@ -48,6 +48,13 @@ homebrew-publish:
4848
verify-fork-sync:
4949
python3 scripts/test_fork_sync.py
5050

51+
.PHONY: verify-github-token verify-github-token-live
52+
verify-github-token:
53+
python3 scripts/test_github_token.py
54+
55+
verify-github-token-live:
56+
python3 scripts/verify_github_token.py
57+
5158
verify-native-qa:
5259
python3 scripts/test_native_qa.py
5360

‎scripts/test_fork_sync.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,13 @@ def run_sync(self, token="", event="schedule", branch="main"):
132132

133133
def test_checkout_uses_dedicated_token_or_builtin_token(self):
134134
value = re.search(r"^ token: (.+)$", WORKFLOW, re.M).group(1)
135-
for token in ("", "fixture-sync-token"):
136-
with self.subTest(token_configured=bool(token)):
137-
self.assertEqual(expression(value, {"secrets.FORK_SYNC_TOKEN": token,
138-
"github.token": "built-in"}), token or "built-in")
135+
tokens = ("ghs_" + "a" * 36, "ghs_123_" + "a_B-" * 62 + "." + "c_D-" * 62 + "." + "s" * 14,
136+
"ghs_123_" + "a_B-" * 200 + "." + "c_D-" * 200 + "." + "s_T-" * 200)
137+
for builtin in tokens:
138+
for token in ("", "fixture-sync-token", *tokens):
139+
with self.subTest(builtin_length=len(builtin), dedicated_length=len(token)):
140+
self.assertEqual(expression(value, {"secrets.FORK_SYNC_TOKEN": token,
141+
"github.token": builtin}), token or builtin)
139142

140143
def test_source_only_update_pushes_and_dispatches_with_builtin_token(self):
141144
self.upstream_changes({"source.txt": "updated\n"})

‎scripts/test_github_token.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
#!/usr/bin/env python3
2+
"""Offline token transport regressions through production API/Git consumers."""
3+
import hashlib
4+
import json
5+
import os
6+
from pathlib import Path
7+
import shutil
8+
import subprocess
9+
import sys
10+
import tempfile
11+
import unittest
12+
13+
sys.dont_write_bytecode = True
14+
import verify_github_token as check
15+
16+
ROOT = Path(__file__).resolve().parent.parent
17+
REAL_GH = shutil.which("gh")
18+
TOKENS = {
19+
"classic": "ghs_" + "A1b2" * 9,
20+
# Deliberately unsigned fixtures with underscores, hyphens and two dots.
21+
"stateless_520": "ghs_12345_" + "a_B-" * 20 + "." + "c_D-" * 60 + "." + "s_T-" * 47,
22+
"stateless_long": "ghs_12345_" + "a_B-" * 100 + "." + "c_D-" * 200 + "." + "s_T-" * 300,
23+
"oauth": "gho_" + "C3d4" * 9,
24+
}
25+
26+
FAKE_GH = r'''#!/usr/bin/env python3
27+
import hashlib, json, os, sys
28+
args = sys.argv[1:]
29+
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") or os.environ.get("FIXTURE_LOGIN_TOKEN", "")
30+
if not token or hashlib.sha256(token.encode()).hexdigest() != os.environ["FIXTURE_TOKEN_HASH"]:
31+
sys.exit(1)
32+
if args[:2] == ["auth", "token"]:
33+
print(token)
34+
elif args[:2] == ["auth", "git-credential"]:
35+
sys.stdin.read()
36+
if os.environ.get("FIXTURE_TRUNCATE"):
37+
token = token[:40]
38+
print("username=x-access-token\npassword=" + token + "\n")
39+
elif args[0] == "api":
40+
failure = os.environ.get("FIXTURE_API_ERROR")
41+
if failure and failure in args[1]:
42+
print(token, file=sys.stderr) # A failing tool must not leak into check logs.
43+
sys.exit(1)
44+
data = {"object": {"type": "commit", "sha": "a" * 40}} if args[1].endswith("git/ref/heads/main") else {"full_name": "FileMintApp/homebrew-tap"}
45+
if "--include" in args:
46+
print("HTTP/2.0 200 OK\nContent-Type: application/json\n")
47+
print(json.dumps(data))
48+
else:
49+
sys.exit(1)
50+
'''
51+
52+
53+
class GitHubTokenTests(unittest.TestCase):
54+
def setUp(self):
55+
temporary = tempfile.TemporaryDirectory(prefix="filemint-token-tests-")
56+
self.addCleanup(temporary.cleanup)
57+
self.directory = Path(temporary.name)
58+
binary = self.directory / "gh"
59+
binary.write_text(FAKE_GH)
60+
binary.chmod(0o755)
61+
self.environment = dict(os.environ, PATH=str(self.directory) + os.pathsep + os.environ["PATH"],
62+
GH_HOST="github.com", GH_PROMPT_DISABLED="1")
63+
for key in ("GH_TOKEN", "GITHUB_TOKEN", "FIXTURE_LOGIN_TOKEN", "FIXTURE_TRUNCATE", "FIXTURE_API_ERROR"):
64+
self.environment.pop(key, None)
65+
66+
def run_check(self, token, source="GH_TOKEN", **environment):
67+
env = dict(self.environment, FIXTURE_TOKEN_HASH=hashlib.sha256(token.encode()).hexdigest(),
68+
**{source: token}, **environment)
69+
result = subprocess.run([sys.executable, str(ROOT / "scripts/verify_github_token.py")],
70+
cwd=ROOT, env=env, capture_output=True, text=True, timeout=30)
71+
self.assertNotIn(token, result.stdout + result.stderr)
72+
return result
73+
74+
def test_all_token_shapes_reach_release_tap_and_git_consumers_intact(self):
75+
self.assertEqual(len(TOKENS["classic"]), 40)
76+
self.assertEqual(len(TOKENS["stateless_520"]), 520)
77+
self.assertGreater(len(TOKENS["stateless_long"]), 2048)
78+
for label, token in TOKENS.items():
79+
with self.subTest(format=label):
80+
result = self.run_check(token)
81+
self.assertEqual(result.returncode, 0, result.stderr)
82+
self.assertEqual(json.loads(result.stdout), {
83+
"status": "passed", "release_api": "passed", "tap_api": "passed",
84+
"git_credential": "passed", "installation_token": label != "oauth",
85+
"token_length": len(token), "token_dots": token.count(".")})
86+
87+
def test_github_token_and_existing_login_fallbacks(self):
88+
for source in ("GITHUB_TOKEN", "FIXTURE_LOGIN_TOKEN"):
89+
with self.subTest(source=source):
90+
self.assertEqual(self.run_check(TOKENS["stateless_520"], source).returncode, 0)
91+
92+
def test_truncated_credentials_fail_without_printing_token(self):
93+
result = self.run_check(TOKENS["stateless_long"], FIXTURE_TRUNCATE="1")
94+
self.assertNotEqual(result.returncode, 0)
95+
self.assertIn("did not preserve the complete token", result.stderr)
96+
97+
def test_failed_apis_do_not_relay_sensitive_tool_stderr(self):
98+
for repository in ("repos/FileMintApp/FileMint/", "repos/FileMintApp/homebrew-tap"):
99+
with self.subTest(repository=repository):
100+
result = self.run_check(TOKENS["stateless_520"], FIXTURE_API_ERROR=repository)
101+
self.assertNotEqual(result.returncode, 0)
102+
self.assertIn("API request failed", result.stderr)
103+
104+
def test_missing_credential_fails(self):
105+
env = dict(self.environment, FIXTURE_TOKEN_HASH="missing")
106+
result = subprocess.run([sys.executable, str(ROOT / "scripts/verify_github_token.py")],
107+
env=env, capture_output=True, text=True, timeout=30)
108+
self.assertNotEqual(result.returncode, 0)
109+
self.assertIn("No existing GitHub credential", result.stderr)
110+
111+
@unittest.skipUnless(REAL_GH, "GitHub CLI is unavailable; fixture checks still run offline")
112+
def test_real_git_and_github_cli_preserve_synthetic_tokens_without_network(self):
113+
for label, token in TOKENS.items():
114+
with self.subTest(format=label):
115+
environment = dict(os.environ, GH_TOKEN=token, GH_HOST="github.com",
116+
GH_PROMPT_DISABLED="1")
117+
environment.pop("GH_DEBUG", None)
118+
check.credential_round_trip(token, environment)
119+
120+
121+
if __name__ == "__main__":
122+
unittest.main()

‎scripts/verify_github_token.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#!/usr/bin/env python3
2+
"""Read-only checks using the existing GitHub identity; never print credentials."""
3+
import json
4+
import os
5+
import subprocess
6+
import sys
7+
import tempfile
8+
9+
sys.dont_write_bytecode = True
10+
import homebrew_tap as tap
11+
import release_publication as publication
12+
13+
14+
class TokenCheckError(RuntimeError):
15+
pass
16+
17+
18+
def credential_round_trip(token, environment=None):
19+
"""Use Git's actual helper protocol, isolated from repository/user Git config."""
20+
environment = dict(os.environ if environment is None else environment,
21+
GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1",
22+
GIT_CONFIG_COUNT="0", GIT_TERMINAL_PROMPT="0")
23+
with tempfile.TemporaryDirectory(prefix="filemint-token-check-") as directory:
24+
result = subprocess.run(
25+
["git", "-c", "credential.helper=", "-c",
26+
"credential.helper=!gh auth git-credential", "credential", "fill"],
27+
cwd=directory, env=environment, input="protocol=https\nhost=github.com\n\n",
28+
text=True, capture_output=True, timeout=30)
29+
fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
30+
if result.returncode or fields.get("password") != token:
31+
raise TokenCheckError("Git credential helper did not preserve the complete token")
32+
33+
34+
def verify():
35+
if os.environ.get("GH_HOST", "github.com") != "github.com":
36+
raise TokenCheckError("This check requires github.com as the GitHub host")
37+
# Avoid HTTP debug output even if enabled in the calling shell.
38+
os.environ.pop("GH_DEBUG", None)
39+
result = subprocess.run(["gh", "auth", "token", "--hostname", "github.com"],
40+
text=True, capture_output=True, timeout=30)
41+
token = result.stdout.rstrip("\r\n")
42+
if result.returncode or not token:
43+
raise TokenCheckError("No existing GitHub credential is available")
44+
45+
try:
46+
reference = publication.GitHub().api("git/ref/heads/main")
47+
if reference.get("object", {}).get("type") != "commit":
48+
raise TokenCheckError("Release API returned an unexpected repository reference")
49+
repository = tap.TapGitHub().api("")
50+
if repository.get("full_name") != tap.TAP_REPO:
51+
raise TokenCheckError("Tap API returned an unexpected repository")
52+
except (publication.PublicationError, tap.TapError):
53+
# CLI stderr can contain sensitive debugging information. Do not relay it.
54+
raise TokenCheckError("Authenticated release or tap API request failed") from None
55+
credential_round_trip(token)
56+
# GitHub documents dot counts for diagnostics. Do not decode or validate JWTs,
57+
# or require a particular shape/length for authentication to succeed.
58+
return {"status": "passed", "release_api": "passed", "tap_api": "passed",
59+
"git_credential": "passed", "installation_token": token.startswith("ghs_"),
60+
"token_length": len(token), "token_dots": token.count(".")}
61+
62+
63+
def main():
64+
try:
65+
print(json.dumps(verify(), sort_keys=True))
66+
return 0
67+
except TokenCheckError as error:
68+
print(f"GitHub token check failed: {error}", file=sys.stderr)
69+
except (OSError, subprocess.SubprocessError, AttributeError, ValueError):
70+
print("GitHub token check failed: tool execution or API response error", file=sys.stderr)
71+
return 1
72+
73+
74+
if __name__ == "__main__":
75+
sys.exit(main())

‎specs/HARNESS.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ separate from the offline `make verify`; a green source CI does not imply it ran
6464
The existing `make verify` runs context and compression-artifact checks, Swift tests and the public JSON
6565
harness plus real CLI regression, fork-sync permission/merge/CI-dispatch regressions,
6666
appcast and signing-entitlement preparation tests.
67+
GitHub token regressions pass classic, approximately 520-character and longer
68+
stateless fixtures through production API adapters and Git's credential protocol;
69+
when GitHub CLI is installed, its real credential helper is also exercised offline.
70+
`make verify-github-token-live` separately performs authenticated read-only release
71+
and tap API requests plus a credential-helper round trip with the existing identity.
72+
Source CI runs that live check with its job `GITHUB_TOKEN`; local OAuth success does
73+
not prove installation-token compatibility. Token contents are never reported.
6774
It also checks native-runner selection, subprocess failures/timeouts and reporting
6875
without launching GUI fixtures or accessing signing credentials.
6976
It also runs restricted subprocess regressions for batch-rename metadata capture

‎specs/domains/distribution.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ Part of the [FileMint SPEC](../SPEC.md). This file owns the behavior below; othe
5050
enablement remains a separate system action.
5151
- CI and website-deployment workflows pin third-party GitHub Actions to reviewed
5252
commit IDs. Dependency lockfiles remain frozen during website builds.
53+
- GitHub credentials are opaque strings. Pass installation tokens, including
54+
Actions `GITHUB_TOKEN`, intact to GitHub CLI, Git credential helpers and
55+
Homebrew; do not enforce a fixed length, decode their JWT or store/log their
56+
contents. Support the classic format and variable-length stateless tokens
57+
around and above 520 characters. Offline regression checks cover both shapes
58+
through the release/tap API adapters and Git credentials. Source CI also uses
59+
its read-only job token for real API and credential-helper checks; report only
60+
success and token-format metadata. Local OAuth checks are not installation-token
61+
evidence. No workflow here mints installation tokens, so do not add the temporary
62+
creation-endpoint override header to ordinary requests. See GitHub's
63+
[format guidance](https://github.blog/changelog/2026-05-15-github-app-installation-tokens-per-request-override-header/)
64+
and [completed rollout and header retirement](https://github.blog/changelog/2026-10-02-stateless-github-app-installation-tokens-rolled-out/).
5365
- Website-only deployments use an explicit manual `deploy-website.yml` dispatch,
5466
serialized with release website deployments. Validate current main, ancestry
5567
and an allowlisted website/documentation-only diff from the latest public

0 commit comments

Comments
 (0)