1919import subprocess
2020import sys
2121from typing import Callable
22+ from urllib .parse import parse_qs , urlsplit
2223
2324
2425CONTEXTS = ("pineforge/verify" , "pineforge/parity" )
2728# release.yml pushes protected main with its PINEFORGE_APP_ID installation token.
2829# This is GitHub's authenticated push actor, never the commit's author/committer.
2930RELEASE_PUSH_ACTOR = "pineforge-app[bot]"
31+ # Integration for release.yml's PINEFORGE_APP_ID installation token.
32+ # The gate relies on App permission administration: read to see bypass_actors;
33+ # removing it makes every release-bump exemption refuse, even with contents: write.
34+ RELEASE_APP_ID = 4105147
3035RELEASE_BUMP_PATHS = frozenset (("VERSION" , "docker/run_failure_codes_diff.json" ))
3136MAIN_PROOF_WATCHER_FIRST_SHA : str | None = None
3237"""None = the watcher is not live yet. Otherwise its FIRST recorded main sha.
@@ -75,7 +80,8 @@ def _http_failure(raw: str, *, exception: bool = False) -> str | None:
7580 return None
7681
7782
78- def _read_text (api : API , endpoint : str , ** options ) -> str :
83+ def _read_text (api : API , endpoint : str , * , complete_rulesets : bool = False ,
84+ ** options ) -> str :
7985 try :
8086 raw = api (endpoint , ** options )
8187 except subprocess .CalledProcessError as exc :
@@ -94,6 +100,36 @@ def _read_text(api: API, endpoint: str, **options) -> str:
94100 # --include emits one header block per page, also when --jq is used.
95101 # Preserve page boundaries so a good page cannot hide an empty response.
96102 responses = list (_HTTP_RESPONSE .finditer (raw ))
103+ if complete_rulesets :
104+ # Unlike Actions, the ruleset list has no total_count. Keep gh's HTTP
105+ # Link evidence until we prove every advertised next page was read.
106+ failure = f"API { endpoint } returned incomplete ruleset pagination"
107+ if not responses or not options .get ("paginate" ):
108+ raise ReleaseGateError (f"{ failure } : missing HTTP page headers" )
109+ for index , response in enumerate (responses ):
110+ links = re .findall (r"^Link:[ \t]*([^\r\n]*)" , response [0 ],
111+ re .MULTILINE | re .IGNORECASE )
112+ relations = {}
113+ for field in links :
114+ for link in field .split ("," ):
115+ parsed = re .fullmatch (
116+ r'\s*<(https://[^<>\s]+)>;\s*rel="(next|prev|first|last)"\s*' , link )
117+ if parsed is None or parsed [2 ] in relations :
118+ raise ReleaseGateError (f"{ failure } : malformed Link header" )
119+ try :
120+ page = parse_qs (urlsplit (parsed [1 ]).query ).get ("page" )
121+ except ValueError as exc :
122+ raise ReleaseGateError (f"{ failure } : invalid page URL" ) from exc
123+ if (page is None or len (page ) != 1
124+ or re .fullmatch (r"[1-9][0-9]*" , page [0 ]) is None ):
125+ raise ReleaseGateError (f"{ failure } : invalid page number" )
126+ relations [parsed [2 ]] = int (page [0 ])
127+ if ("next" in relations ) != (index + 1 < len (responses )):
128+ raise ReleaseGateError (f"{ failure } : unread or unlinked next page" )
129+ expected = {"next" : index + 2 , "prev" : index ,
130+ "first" : 1 , "last" : len (responses )}
131+ if any (page != expected [relation ] for relation , page in relations .items ()):
132+ raise ReleaseGateError (f"{ failure } : skipped, repeated or truncated pages" )
97133 if responses :
98134 if raw [:responses [0 ].start ()].strip () or (
99135 not options .get ("paginate" , False ) and len (responses ) != 1 ):
@@ -112,8 +148,8 @@ def _read_text(api: API, endpoint: str, **options) -> str:
112148
113149
114150def _read_json (api : API , endpoint : str , * , paginate : bool = False ,
115- items_key : str | None = None ):
116- raw = _read_text (api , endpoint , paginate = paginate )
151+ items_key : str | None = None , complete_rulesets : bool = False ):
152+ raw = _read_text (api , endpoint , paginate = paginate , complete_rulesets = complete_rulesets )
117153 try :
118154 if not paginate :
119155 result = json .loads (raw )
@@ -246,6 +282,113 @@ def _require_release_push(api: API, repo: str, sha: str) -> None:
246282 raise ReleaseGateError (f"no exact-main push workflow run for release bump { sha } " )
247283
248284
285+ def _ruleset_applies_to_main (payload : dict , endpoint : str ) -> bool :
286+ conditions = payload .get ("conditions" )
287+ refs = conditions .get ("ref_name" ) if isinstance (conditions , dict ) else None
288+ if (not isinstance (refs , dict )
289+ or any (not isinstance (refs .get (key ), list )
290+ or any (not isinstance (pattern , str ) or not pattern
291+ for pattern in refs [key ]) for key in ("include" , "exclude" ))):
292+ raise ReleaseGateError (f"API { endpoint } returned invalid ref_name conditions" )
293+
294+ def matches (pattern : str ) -> bool :
295+ if pattern in ("~DEFAULT_BRANCH" , "~ALL" ):
296+ return True
297+ # GitHub uses pathname-aware fnmatch: * and ? cannot cross '/'.
298+ # Refuse advanced/unknown syntax instead of guessing applicability.
299+ if (pattern .startswith ("~" ) or "**" in pattern
300+ or any (char in pattern for char in ("[" , "]" , "{" , "}" , "\\ " ))):
301+ raise ReleaseGateError (f"API { endpoint } returned invalid ref_name conditions: "
302+ f"unsupported pattern { pattern !r} " )
303+ expression = re .escape (pattern ).replace (r"\*" , "[^/]*" ).replace (r"\?" , "[^/]" )
304+ return re .fullmatch (expression , "refs/heads/main" ) is not None
305+
306+ included = [matches (pattern ) for pattern in refs ["include" ]]
307+ excluded = [matches (pattern ) for pattern in refs ["exclude" ]]
308+ return any (included ) and not any (excluded )
309+
310+
311+ def _ruleset_bypasses (payload : dict , endpoint : str ) -> set [tuple [str , int | None , str ]]:
312+ actors = payload .get ("bypass_actors" )
313+ if not isinstance (actors , list ):
314+ raise ReleaseGateError (f"API { endpoint } returned missing or invalid bypass_actors "
315+ "(App requires administration: read)" )
316+ bypasses = set ()
317+ for actor in actors :
318+ if not isinstance (actor , dict ):
319+ raise ReleaseGateError (f"API { endpoint } returned invalid bypass actor: { actor !r} " )
320+ kind , number , mode = (actor .get (key ) for key in
321+ ("actor_type" , "actor_id" , "bypass_mode" ))
322+ if (not isinstance (kind , str )
323+ or kind not in ("Integration" , "OrganizationAdmin" , "DeployKey" ,
324+ "RepositoryRole" , "Team" )
325+ or "actor_id" not in actor
326+ or (number is None and kind not in ("OrganizationAdmin" , "DeployKey" ))
327+ or (number is not None and (type (number ) is not int or number <= 0 ))
328+ or not isinstance (mode , str ) or mode not in ("always" , "pull_request" )):
329+ raise ReleaseGateError (f"API { endpoint } returned invalid bypass actor: { actor !r} " )
330+ identity = (kind , number , mode )
331+ if identity in bypasses :
332+ raise ReleaseGateError (f"API { endpoint } returned invalid bypass actor: duplicate" )
333+ bypasses .add (identity )
334+ return bypasses
335+
336+
337+ def _require_release_rulesets (api : API , repo : str ) -> None :
338+ endpoint = f"repos/{ repo } "
339+ repository = _read_json (api , endpoint )
340+ if not isinstance (repository , dict ) or repository .get ("default_branch" ) != "main" :
341+ raise ReleaseGateError (f"API { endpoint } must identify main as the default branch" )
342+
343+ endpoint = f"repos/{ repo } /rulesets?includes_parents=true&per_page=100"
344+ inventory = _read_json (api , endpoint , paginate = True , complete_rulesets = True )
345+ seen , summaries = set (), []
346+ for row in inventory :
347+ if (not isinstance (row , dict ) or type (row .get ("id" )) is not int or row ["id" ] <= 0
348+ or not isinstance (row .get ("target" ), str )
349+ or row ["target" ] not in ("branch" , "tag" , "push" )
350+ or not isinstance (row .get ("enforcement" ), str )
351+ or row ["enforcement" ] not in ("active" , "disabled" , "evaluate" )):
352+ raise ReleaseGateError (f"API { endpoint } returned invalid ruleset summary: { row !r} " )
353+ if row ["id" ] in seen :
354+ raise ReleaseGateError (f"API { endpoint } returned duplicate ruleset id { row ['id' ]} " )
355+ seen .add (row ["id" ])
356+ summaries .append (row )
357+
358+ intersection = None
359+ for summary in summaries :
360+ if summary ["target" ] != "branch" :
361+ continue
362+ endpoint = f"repos/{ repo } /rulesets/{ summary ['id' ]} "
363+ payload = _read_json (api , endpoint )
364+ if (not isinstance (payload , dict ) or type (payload .get ("id" )) is not int
365+ or any (payload .get (key ) != summary [key ]
366+ for key in ("id" , "target" , "enforcement" ))):
367+ raise ReleaseGateError (f"API { endpoint } returned inconsistent ruleset detail" )
368+ bypasses = _ruleset_bypasses (payload , endpoint )
369+ applies = _ruleset_applies_to_main (payload , endpoint )
370+ rules = payload .get ("rules" )
371+ if (not isinstance (rules , list )
372+ or any (not isinstance (rule , dict ) or not isinstance (rule .get ("type" ), str )
373+ or not rule ["type" ] for rule in rules )):
374+ raise ReleaseGateError (f"API { endpoint } returned invalid rules" )
375+ blocking = any (rule ["type" ] in ("pull_request" , "required_status_checks" )
376+ for rule in rules )
377+ if not applies or not blocking :
378+ continue
379+ if payload ["enforcement" ] != "active" :
380+ raise ReleaseGateError (
381+ f"main push-blocking ruleset { summary ['id' ]} must be active" )
382+ # Rulesets are cumulative: an actor must bypass EVERY main push blocker.
383+ intersection = bypasses if intersection is None else intersection & bypasses
384+
385+ if intersection is None :
386+ raise ReleaseGateError ("main has no active applicable push-blocking ruleset" )
387+ if intersection != {("Integration" , RELEASE_APP_ID , "always" )}:
388+ raise ReleaseGateError ("main direct-push bypass intersection must be exactly "
389+ f"Integration { RELEASE_APP_ID } with bypass_mode always" )
390+
391+
249392def _tree_files (api : API , repo : str , tree : str ) -> dict [str , tuple [str , str , str ]]:
250393 endpoint = f"repos/{ repo } /git/trees/{ tree } ?recursive=1"
251394 payload = _read_json (api , endpoint )
@@ -275,6 +418,7 @@ def _tree_files(api: API, repo: str, tree: str) -> dict[str, tuple[str, str, str
275418
276419def _release_bump (api : API , repo : str , sha : str ) -> str :
277420 _require_release_push (api , repo , sha )
421+ _require_release_rulesets (api , repo )
278422 candidate = _commit_info (api , repo , sha )
279423 parents = candidate .get ("parents" )
280424 if (not isinstance (parents , list ) or len (parents ) != 1
0 commit comments