diff --git a/github_nonpublic_api/forms.py b/github_nonpublic_api/forms.py new file mode 100644 index 0000000..b634279 --- /dev/null +++ b/github_nonpublic_api/forms.py @@ -0,0 +1,788 @@ +# Copyright 2026 The Authors (see AUTHORS file) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reads and submits GitHub web forms exactly like a browser does. + +GitHub's web UI posts HTML forms. To automate a page reliably, a client has to +send the same fields a browser sends: every enabled control, the state of each +checkbox and radio, selected options, empty text fields, controls associated +through `form="..."`, and the submit button. This module provides: + +* `parse_page`: parses HTML the way a browser builds its forms. +* `find_form_by_action`: picks a form by its action path and Rails `_method`. +* `browser_form_data`: the entry list a browser's `FormData` would submit, + optionally after simulated user edits. +* `page_errors` and `response_summary`: what went wrong when GitHub rejects a + submission, without returning the page body. +* `redacted_body_excerpt`: a short excerpt of a page with its tokens + redacted, for diagnosing a page that changed shape. +* `describe_forms`: a redacted description of a page's forms, for verifying + that a page still has the expected shape. +* `request_with_retry` and `configure_session_adapters`: retries for rate + limits, server errors and transport failures that never resend a + non-idempotent request by default. +* `submit_once`: sends a state-changing submission once and reports when its + outcome is unknown (`OutcomeUnknownError`). + +Failures are reported as `FormError` subclasses that carry the visible errors +and a response summary, so callers can tell a rejected submission +(`FormRejectedError`) from a page that changed shape (`PageShapeError`). A +`PageShapeError` raised for a response also carries a redacted excerpt of it, +outside the error message. +""" + +from __future__ import annotations + +import random +import re +import time +from typing import Optional +from urllib.parse import urlparse + +import html5lib +import requests +from absl import logging +from requests.adapters import HTTPAdapter +from requests.exceptions import InvalidHeader, InvalidSchema, InvalidURL, MissingSchema +from urllib3.exceptions import ConnectTimeoutError, MaxRetryError +from urllib3.util import Retry + +MAX_RETRIES = 5 +BASE_DELAY_SECONDS = 2.0 +MAX_DELAY_SECONDS = 120.0 +JITTER_MIN_SECONDS = 0.1 +JITTER_MAX_SECONDS = 1.0 +DEFAULT_TIMEOUT_SECONDS = 30 + +# Methods that a server must be able to receive twice without a second effect. +# Only these are resent on a retryable status unless the caller opts in. +_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) + + +class FormError(Exception): + """A GitHub web form could not be read or submitted as expected. + + Attributes: + summary: Status, final URL, redirect chain and page title of the + response involved (see `response_summary`), or "" if none. + errors: Visible error texts GitHub rendered on that response (see + `page_errors`). + body_excerpt: A redacted, truncated excerpt of that response's body + (see `redacted_body_excerpt`), or "" if none. It is never part of + the message, so `str(error)` and logs of it never contain page + HTML. Only `PageShapeError`s raised for a response set it: the + page is what needs diagnosing when its shape changed, while the + other errors are explained by `summary` and `errors`. + """ + + def __init__( + self, + message: str, + summary: str = "", + errors: Optional[list[str]] = None, + body_excerpt: str = "", + ): + super().__init__(message) + self.summary = summary + self.errors = list(errors or []) + self.body_excerpt = body_excerpt + + +class PageShapeError(FormError, ValueError): + """The page lacks an expected form, control or submit button, or GitHub + answered with a page or redirect the caller did not expect.""" + + +class FormRejectedError(FormError, ValueError): + """GitHub rejected a submission and rendered visible errors explaining why + (for example, a name that is already taken).""" + + +class OutcomeUnknownError(FormError): + """A request that changes state may have reached GitHub, but no + definitive response came back (timeout, dropped connection or 5xx). + + The change may or may not have been applied; resending could apply it + twice. Callers should read the current state before retrying. + """ + + +def configure_session_adapters(session: requests.Session) -> None: + """Mounts transport-level retries onto `session`. + + Connection failures (refused, DNS failure, connect timeout) are retried + for every method, since no request was sent. Read errors are retried + only for idempotent methods: urllib3's default `allowed_methods` excludes + POST. Other errors, such as an SSL error, are never retried, because + urllib3 cannot tell whether the request was sent and would otherwise + resend it for every method, POST included. HTTP statuses are not retried + here; see `request_with_retry`. + """ + retries = Retry( + total=3, + connect=3, + read=3, + other=0, + backoff_factor=0.5, + status=0, + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retries) + session.mount("https://", adapter) + session.mount("http://", adapter) + + +def parse_retry_delay( + response: requests.Response, + attempt: int, + base_delay: float = BASE_DELAY_SECONDS, + max_delay: float = MAX_DELAY_SECONDS, +) -> float: + """Seconds to wait before retrying `response`, plus jitter. + + Honors `Retry-After` (seconds), then `X-RateLimit-Reset` (epoch seconds), + then falls back to exponential backoff from `base_delay`. Never exceeds + `max_delay` before jitter. + """ + jitter = random.uniform(JITTER_MIN_SECONDS, JITTER_MAX_SECONDS) + retry_after = response.headers.get("Retry-After") + if retry_after: + try: + return min(max_delay, max(0.0, float(retry_after))) + jitter + except (ValueError, TypeError): + pass + + reset_epoch = response.headers.get("X-RateLimit-Reset") + if reset_epoch: + try: + return min(max_delay, max(0.0, float(reset_epoch) - time.time())) + jitter + except (ValueError, TypeError): + pass + + return min(max_delay, base_delay * (2**attempt)) + jitter + + +def is_retryable(response: requests.Response) -> bool: + """True for rate-limit responses (429, or 403 with rate-limit signals) and + for 500, 502, 503 and 504.""" + if response.status_code == 429: + return True + if response.status_code == 403: + if "Retry-After" in response.headers: + return True + if response.headers.get("X-RateLimit-Remaining") == "0": + return True + return "rate limit" in response.text.lower() + return response.status_code in (500, 502, 503, 504) + + +def request_with_retry( + session: requests.Session, + method: str, + url: str, + max_retries: int = MAX_RETRIES, + base_delay: float = BASE_DELAY_SECONDS, + max_delay: float = MAX_DELAY_SECONDS, + retry_unsafe_methods: bool = False, + **kwargs, +) -> requests.Response: + """Sends a request, retrying rate-limit and server-error responses. + + By default only GET, HEAD and OPTIONS are resent. A 5xx to a POST can + arrive after GitHub already acted on it, so resending could repeat the + change. Pass `retry_unsafe_methods=True` only for requests that change + nothing on the server, such as a POST that renders a preview page. + + Extra keyword arguments are passed to `session.request`. + + Returns the response when its status is below 400 (including an + unfollowed 3xx). Raises `requests.HTTPError` otherwise. + """ + may_resend = retry_unsafe_methods or method.upper() in _SAFE_METHODS + for attempt in range(max(0, max_retries) + 1): + response = session.request(method=method, url=url, **kwargs) + if response.status_code < 400: + return response + if may_resend and attempt < max_retries and is_retryable(response): + sleep_duration = parse_retry_delay( + response, attempt, base_delay=base_delay, max_delay=max_delay + ) + logging.warning( + "Rate limit/transient error (HTTP [%s]) on [%s] [%s]. " + "Retrying in [%.2fs] (attempt [%d]/[%d])...", + response.status_code, + method, + url, + sleep_duration, + attempt + 1, + max_retries, + ) + time.sleep(sleep_duration) + continue + break + response.raise_for_status() + return response + + +# Raised while preparing a request, before any connection is made. +_PRE_SEND_ERRORS = (InvalidHeader, InvalidSchema, InvalidURL, MissingSchema) + + +def _never_sent(error: requests.RequestException) -> bool: + """True if `error` proves the request never reached the server: the + connection itself could not be established.""" + if isinstance(error, (requests.ConnectTimeout, *_PRE_SEND_ERRORS)): + return True + if isinstance(error, requests.ConnectionError) and error.args: + cause = error.args[0] + # NewConnectionError (refused, DNS failure) subclasses ConnectTimeoutError. + return isinstance(cause, MaxRetryError) and isinstance(cause.reason, ConnectTimeoutError) + return False + + +def submit_once( + session: requests.Session, url: str, data, **kwargs +) -> requests.Response: + """POSTs a state-changing form submission exactly once. + + Never resends. Returns any response with a status below 500, for the + caller to judge. Extra keyword arguments are passed to `session.request`. + + Raises: + OutcomeUnknownError: GitHub may have acted on the request: it answered + with a 5xx, or the request failed after it may have been sent + (read timeout, dropped connection). + requests.RequestException: The request was never sent (the + connection could not be established). + """ + try: + response = session.request(method="POST", url=url, data=data, **kwargs) + except requests.RequestException as e: + if _never_sent(e): + raise + raise OutcomeUnknownError( + f"POST {url} may have reached GitHub, but no response arrived: {e!r}" + ) from e + if response.status_code >= 500: + summary = response_summary(response) + raise OutcomeUnknownError( + f"POST {url} may have been applied; GitHub answered: {summary}", summary=summary + ) + return response + + +# Matches a element that contains no other . +_INNERMOST_TEMPLATE = re.compile( + r"]*>(?:(?!", re.I | re.S +) +_TEMPLATE_PLACEHOLDER = "\x00github-nonpublic-api-template\x00" + + +def _strip_template_contents(html: str) -> str: + """Empties every element, innermost first so nesting works. + + html5lib 1.1 mis-parses a + closes the *outer* form, so every control after it is dropped. GitHub's + New GitHub App page has such a template, and the parsed form lost its + submit button. Browsers parse template contents as a separate fragment + and never submit them, so emptying templates first yields the form a + browser sees. + """ + previous = None + while previous != html: + previous = html + html = _INNERMOST_TEMPLATE.sub(_TEMPLATE_PLACEHOLDER, html) + return html.replace(_TEMPLATE_PLACEHOLDER, "") + + +def parse_page(html: str): + """Parses a GitHub page into an ElementTree the way a browser builds its + forms (see `_strip_template_contents`).""" + return html5lib.parse(_strip_template_contents(html), namespaceHTMLElements=False) + + +def find_form_by_action(doc, action_path: str, method: Optional[str] = None): + """Returns the first form whose action path equals `action_path`, or None. + + The query string and a trailing slash are ignored. If `method` is set + (for example "delete"), the form must also carry a Rails `_method` input + with that value, case-insensitively. + """ + for form in doc.findall(".//form"): + if urlparse(form.attrib.get("action", "")).path.rstrip("/") != action_path.rstrip("/"): + continue + if method is not None: + method_inputs = [ + i for i in form.findall(".//input") if i.attrib.get("name") == "_method" + ] + if not any(i.attrib.get("value", "").lower() == method.lower() for i in method_inputs): + continue + return form + return None + + +_NON_SUBMITTED_INPUT_TYPES = frozenset({"button", "reset", "image"}) + + +def _parent_map(doc) -> dict: + return {child: parent for parent in doc.iter() for child in parent} + + +def browser_controls(doc, form) -> tuple[list, dict]: + """The controls associated with `form`, in tree order, as a browser sees + them, and a child -> parent map of `doc`. + + Includes controls elsewhere in the document with `form="
'), 'fragment
') + + def test_truncates_to_4_kb_without_splitting_characters(self): + excerpt = forms.redacted_body_excerpt('' + '\u00e9' * 5000) + self.assertLessEqual(len(excerpt.encode('utf-8')), forms.MAX_BODY_EXCERPT_BYTES) + self.assertGreater(len(excerpt.encode('utf-8')), forms.MAX_BODY_EXCERPT_BYTES - 2) + self.assertEqual(forms.redacted_body_excerpt(''), '') + + def test_fails_closed_when_the_page_cannot_be_scanned(self): + page = '' + with mock.patch.object(forms.html5lib, 'parse', side_effect=RuntimeError('boom')): + self.assertEqual(forms.redacted_body_excerpt(page), '') + + +if __name__ == '__main__': + unittest.main()