From e996cdc00ec866ac70dc66d3dfd403d70d85e938 Mon Sep 17 00:00:00 2001
From: Cole Wagner
Date: Mon, 23 Nov 2026 23:12:28 +0000
Subject: [PATCH 1/2] Add a forms module that submits GitHub web forms like a
browser.
GitHub's web UI posts HTML forms, and automating a page reliably requires
sending the same fields a browser sends. The existing _get_and_submit_form
helper sends only elements that have a value, submits the first form
on the page by default, and parses pages with html5lib 1.1, which lets a
'), '
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()
From ca63a71cc3a62afce75fd7b76d2ebf55233d2808 Mon Sep 17 00:00:00 2001
From: Cole Wagner
Date: Mon, 23 Nov 2026 23:12:59 +0000
Subject: [PATCH 2/2] Support GitHub Enterprise Server URLs and creating apps
from manifests.
Api and create_login_session only worked against github.com, and the
library had no way to register a GitHub App from a manifest, which GitHub
only offers as a browser flow.
* base_url: Api and create_login_session take the web root, defaulting to
https://github.com, and every page URL is built from it. Only sign-in and
manifest creation were verified on a GitHub Enterprise Server. A value
that is not the absolute http(s) URL of a web root (with no path, query
or fragment) raises ValueError. download_dormant_users_report looks for
the export link under base_url and the requested enterprise instead of a
hard-coded github.com enterprise.
* Login: tfa_callback is optional. Without it, a two-factor, sign-in or
device-verification page after the password step raises
LoginChallengeError (a FormError) instead of returning a signed-out
session. With it, a page on the GitHub host other than the two-factor
prompt still raises, and so does a sign-in page after the code is
submitted, which means the code was rejected. create_login_session mounts
transport retries on the session.
* Api.create_app_from_manifest follows GitHub's documented manifest flow the
way a browser does, using the forms module: POST the manifest (which only
renders a confirmation page and may be retried), find the single POST
form with an integration_manifest[owner_login] field, check that it
offers to create the app for the requested organization (or for the
signed-in user named by the page's user-login meta tag), submit it
exactly once with redirects disabled, and return the absolute callback
URL that carries the single-use code. The caller exchanges the code with
POST /app-manifests/{code}/conversions; that exchange, not the
confirmation, is what registers the app, so a code lost after the
confirmation leaves no app. GitHub answers the confirmation with a 200
"You are being redirected to continue setup of your GitHub App" page, so
the URL is taken from that page's meta refresh or a#redirect link, and
only if exactly one URL with a non-empty code is found. The form is found
by its owner field rather than its action because GitHub redirects a
manifest posted for an organization to /settings/apps/manifest, whose form
posts to /settings/apps just like the user's own, and answered a manifest
posted for an organization the user did not own with the user's own
confirmation form, which would have made the app user-owned; that now
raises PageShapeError asking whether the user is an owner of the
organization. Failures are typed: FormRejectedError for visible errors,
PageShapeError (with a redacted body_excerpt) for an unexpected page or
owner before the confirmation is sent, or a 4xx answer to it,
LoginChallengeError for GitHub's sign-in or sudo confirmation page (or a
redirect to it), and OutcomeUnknownError when the confirmation may have
been accepted without delivering a usable code: no definitive answer, any
other redirect (even one to a URL with a code, which the message redacts),
or a page with neither visible errors nor exactly one URL with a code
(with a redacted body_excerpt).
Tests use the responses library (added to requirements.txt with its PyYAML
dependency) and two sanitized captures from a GitHub Enterprise Server: the
organization-owned confirmation page, reached through the same redirect,
and the full continue-setup page that answered the confirmation, whose meta
refresh and a#redirect link both carry the code. The upstream
test_create_login_session_success now gives the code submission its own
landing page: its single mocked response put the session back on the
two-factor page, which is now a rejected code.
BUG=http://b/571180795
---
github_nonpublic_api/api.py | 565 +++++++++-
github_nonpublic_api/forms.py | 14 +-
requirements.txt | 2 +
tests/app_manifest_confirmation.html | 1397 ++++++++++++++++++++++++
tests/app_manifest_continue_setup.html | 69 ++
tests/test_api.py | 766 ++++++++++++-
6 files changed, 2776 insertions(+), 37 deletions(-)
create mode 100644 tests/app_manifest_confirmation.html
create mode 100644 tests/app_manifest_continue_setup.html
diff --git a/github_nonpublic_api/api.py b/github_nonpublic_api/api.py
index c4e564e..a0b9e3d 100644
--- a/github_nonpublic_api/api.py
+++ b/github_nonpublic_api/api.py
@@ -18,7 +18,7 @@
import functools
from enum import Enum
import re
-from urllib.parse import urljoin
+from urllib.parse import parse_qs, urljoin, urlparse
import html5lib
import pyotp
@@ -27,6 +27,18 @@
from configobj import ConfigObj
from typing import Optional
+from github_nonpublic_api import forms
+
+GITHUB_URL = "https://github.com"
+
+
+class LoginChallengeError(forms.FormError, RuntimeError):
+ """Login did not complete: GitHub rejected the credentials or the
+ two-factor code, showed a captcha or device verification page, or asked
+ for a two-factor code that no callback can provide. Or GitHub answered a
+ request with its sign-in or sudo confirmation page instead of acting on
+ it."""
+
def _get_and_submit_form(
session, url: str, data_callback=None, form_matcher=lambda form: True
@@ -40,10 +52,10 @@ def _get_and_submit_form(
logging.info("Redirected from: %s", redirect_response.url)
doc = html5lib.parse(response.text, namespaceHTMLElements=False)
- forms = doc.findall(".//form")
+ page_forms = doc.findall(".//form")
submit_form = None
- for form in forms:
+ for form in page_forms:
if form_matcher(form):
submit_form = form
break
@@ -81,14 +93,72 @@ def _get_url_with_session(session, url: str):
return response
+def _is_login_page(url: str) -> bool:
+ """True for GitHub's sign-in, failed sign-in, two-factor and device
+ verification pages (/login..., /session, /sessions/...)."""
+ path = urlparse(url).path.rstrip("/")
+ return path in ("/login", "/session") or path.startswith(("/login/", "/sessions/"))
+
+
+def _normalize_base_url(base_url: str) -> str:
+ """`base_url` without a trailing slash.
+
+ Raises:
+ ValueError: `base_url` is not the absolute http(s) URL of a web root,
+ for example a bare host name such as "github.example.com", or a
+ URL with a path, query or fragment such as
+ "https://github.example.com/prefix". Page paths are appended to
+ `base_url`, and sign-in pages are recognized by their path from
+ the host's root, so a path, query or fragment would break both.
+ """
+ parsed = urlparse(base_url)
+ if (
+ parsed.scheme not in ("http", "https")
+ or not parsed.netloc
+ or parsed.path.strip("/")
+ or parsed.params
+ # Not parsed.query or parsed.fragment: those are "" for a bare "?" or "#".
+ or "?" in base_url
+ or "#" in base_url
+ ):
+ raise ValueError(
+ f"base_url must be an absolute http(s) URL of the web root, such as "
+ f"'https://github.example.com', with no path, query or fragment, got [{base_url}]"
+ )
+ return base_url.rstrip("/")
+
+
def create_login_session(
username: str,
password: str,
- tfa_callback,
+ tfa_callback=None,
session: Optional[requests.Session] = None,
+ base_url: str = GITHUB_URL,
) -> requests.Session:
- """Create a requests.Session object with logged in GitHub cookies for the user."""
+ """Create a requests.Session object with logged in GitHub cookies for the user.
+
+ Args:
+ username: The account to sign in as.
+ password: The account's password.
+ tfa_callback: Returns the current TOTP code. If None, the account must
+ not require two-factor authentication.
+ session: Session to sign in; a new one is created if None. Its cookies
+ are cleared and transport retries are mounted on it (see
+ `forms.configure_session_adapters`).
+ base_url: The GitHub web root, for example "https://github.com" or a
+ GitHub Enterprise Server URL such as "https://github.example.com".
+
+ Raises:
+ LoginChallengeError: GitHub did not sign the user in: it rejected the
+ credentials or the two-factor code, stopped at a captcha or
+ device verification page, or asked for a two-factor code without
+ a `tfa_callback`.
+ ValueError: `base_url` is not the absolute http(s) URL of a web root.
+ """
+ base_url = _normalize_base_url(base_url)
+ base_host = urlparse(base_url).netloc
session = session or requests.Session()
+ forms.configure_session_adapters(session)
# Clear cookies before re-authentication
session.cookies.clear()
@@ -97,43 +167,339 @@ def _login_callback(data):
data.update(dict(login=username, password=password))
res = _get_and_submit_form(
- session=session, url="https://github.com/login", data_callback=_login_callback
+ session=session, url=f"{base_url}/login", data_callback=_login_callback
)
- if "two-factor" not in res.url and "github.com" in res.url:
- logging.error("Login challenged by GitHub (Captcha/Device Verification). Stuck at: %s", res.url)
- raise RuntimeError(
- f"Login challenged by GitHub (Captcha/Device Verification). Stuck at: {res.url}"
+ asked_for_code = "two-factor" in res.url
+ if tfa_callback is None:
+ # Without a TOTP callback the sign-in must be complete now: a sign-in,
+ # two-factor or device verification page means it is not.
+ if asked_for_code:
+ raise LoginChallengeError(
+ f"Login requires two-factor authentication, but no tfa_callback was given. "
+ f"Stuck at: {res.url}"
+ )
+ if _is_login_page(res.url):
+ message = (
+ f"Sign-in did not complete (wrong credentials, captcha or device verification). "
+ f"Stuck at: {res.url}"
+ )
+ logging.error("%s", message)
+ raise LoginChallengeError(message)
+ return session
+
+ # With a TOTP callback GitHub must ask for the code next; any other page on
+ # the same host is a challenge.
+ if not asked_for_code and base_host in res.url:
+ message = (
+ f"Login challenged by GitHub: expected a two-factor prompt after the password "
+ f"(wrong credentials, captcha or device verification?). Stuck at: {res.url}"
)
+ logging.error("%s", message)
+ raise LoginChallengeError(message)
def _tfa_callback(data):
data.update(dict(otp=tfa_callback()))
- _get_and_submit_form(
+ res = _get_and_submit_form(
session=session,
- url="https://github.com/sessions/two-factor",
+ url=f"{base_url}/sessions/two-factor",
data_callback=_tfa_callback,
)
+ # GitHub sends a session past the sign-in pages once it accepts the code;
+ # still being on one (such as the two-factor page) means it did not.
+ if urlparse(res.url).netloc.lower() == base_host.lower() and _is_login_page(res.url):
+ message = f"Two-factor code was not accepted. Stuck at: {res.url}"
+ logging.error("%s", message)
+ raise LoginChallengeError(message)
return session
-_CREATE_ORG_URL = "https://github.com/account/organizations/new?plan=free"
-_INSTALL_APP_URL = "https://github.com/apps/{app_name}/installations/new/permissions?target_id={org_id}"
-_APP_SUSPEND_URL = "https://github.com/organizations/{org_name}/settings/installations/{app_install_id}"
-_REQUEST_USAGE_URL = "https://github.com/enterprises/{enterprise_name}/settings/billing"
-_USAGE_REPORT_URL = "https://github.com/enterprises/{enterprise_name}/settings/metered_exports/{report_id}"
+_CREATE_ORG_URL = "{base_url}/account/organizations/new?plan=free"
+_INSTALL_APP_URL = "{base_url}/apps/{app_name}/installations/new/permissions?target_id={org_id}"
+_APP_SUSPEND_URL = "{base_url}/organizations/{org_name}/settings/installations/{app_install_id}"
+_REQUEST_USAGE_URL = "{base_url}/enterprises/{enterprise_name}/settings/billing"
+_USAGE_REPORT_URL = "{base_url}/enterprises/{enterprise_name}/settings/metered_exports/{report_id}"
_REQUEST_DORMANTUSERS_URL = (
- "https://github.com/enterprises/{enterprise_name}/settings/compliance"
+ "{base_url}/enterprises/{enterprise_name}/settings/compliance"
)
-_UPDATE_APP_INSTALL_URL = "https://github.com/organizations/{org_name}/settings/installations/{app_install_id}/permissions/update"
+_UPDATE_APP_INSTALL_URL = "{base_url}/organizations/{org_name}/settings/installations/{app_install_id}/permissions/update"
_UPDATE_SECURITY_ANALYSIS_URL = (
- "https://github.com/organizations/{org_name}/settings/security_analysis"
+ "{base_url}/organizations/{org_name}/settings/security_analysis"
)
_UPDATE_GHAS_SETTINGS_URL = (
- "https://github.com/organizations/{org_name}/settings/security_analysis/ghas_settings"
+ "{base_url}/organizations/{org_name}/settings/security_analysis/ghas_settings"
+)
+# Apps owned by the signed-in user live under _USER_APPS_PATH; apps owned by an
+# organization under _ORG_APPS_PATH. Each has a "new" page that accepts a
+# manifest.
+_USER_APPS_PATH = "/settings/apps"
+_ORG_APPS_PATH = "/organizations/{org_name}/settings/apps"
+# The manifest confirmation form's field naming the account that will own the
+# app. It identifies the form and its owner, not the form's action: GitHub
+# answers a manifest posted to an organization's new-app page with a redirect
+# to /settings/apps/manifest, whose form posts to /settings/apps as the user's
+# own confirmation form does, and answers one posted to an organization whose
+# apps the user can't create with the user's form, which would make the app
+# owned by the signed-in user instead.
+_MANIFEST_OWNER_FIELD = "integration_manifest[owner_login]"
+
+
+def _signed_in_login(doc) -> str:
+ """The login of the signed-in user, from the `user-login` `` tag
+ GitHub puts on every page, or "" if the page has none."""
+ meta = doc.find(".//meta[@name='user-login']")
+ return (meta.attrib.get("content") or "").strip() if meta is not None else ""
+
+
+def _offered_owner_logins(doc, form) -> list:
+ """The values a browser would submit for `form`'s owner field: the
+ account GitHub offers to create the app for."""
+ return [value for name, value in forms.browser_form_data(doc, form) if name == _MANIFEST_OWNER_FIELD]
+
+
+def _manifest_confirmation_candidates(doc, page: requests.Response) -> list:
+ """The POST forms on `page` that submit to `page`'s host and have an
+ owner field, wherever they submit to on that host."""
+ page_host = urlparse(page.url).netloc.lower()
+ candidates = []
+ for form in doc.findall(".//form"):
+ action = urlparse(urljoin(page.url, form.attrib.get("action") or page.url))
+ is_post = (form.attrib.get("method") or "get").lower() == "post"
+ has_owner_field = any(
+ c.attrib.get("name") == _MANIFEST_OWNER_FIELD for c in forms.browser_controls(doc, form)[0]
+ )
+ if is_post and action.netloc.lower() == page_host and has_owner_field:
+ candidates.append(form)
+ return candidates
+
+
+def _unexpected_page_error(message: str, response: requests.Response) -> forms.FormError:
+ """`FormRejectedError` if `response` shows visible errors, else
+ `PageShapeError` with a redacted excerpt of the body as `body_excerpt`.
+ The message carries those errors and the response summary, never the
+ body."""
+ summary = forms.response_summary(response)
+ errors = forms.page_errors(response.text)
+ if errors:
+ return forms.FormRejectedError(
+ f"{message}: {summary}. Visible errors: {'; '.join(errors)}.",
+ summary=summary,
+ errors=errors,
+ )
+ return forms.PageShapeError(
+ f"{message}: {summary}. Visible errors: none.",
+ summary=summary,
+ body_excerpt=forms.redacted_body_excerpt(response.text),
+ )
+
+
+def _find_manifest_confirmation_form(doc, page: requests.Response, org_name: Optional[str]):
+ """Returns the form on `page` that confirms a posted manifest for
+ `org_name`, or for the signed-in user if `org_name` is None.
+
+ GitHub does not document that form, and its action need not be under the
+ path the manifest was posted to, so this accepts exactly one POST form to
+ `page`'s host with an `integration_manifest[owner_login]` field. A browser
+ must submit exactly one value for that field, equal to `org_name` or the
+ signed-in user's login (ignoring case: GitHub logins are
+ case-insensitive), and the form must have a submit button.
+
+ Raises:
+ forms.FormRejectedError: There is no such form and the page shows
+ visible errors (for example, an invalid manifest).
+ forms.PageShapeError: There is no such form or more than one, it
+ offers to create the app for another account (for example the
+ signed-in user, who can't create `org_name`'s apps), the
+ signed-in user can't be told from the page, or the form has no
+ submit button. Its `body_excerpt` is a redacted excerpt of
+ `page`.
+ """
+ summary = forms.response_summary(page)
+
+ def page_shape_error(message: str) -> forms.PageShapeError:
+ return forms.PageShapeError(
+ f"{message}: {summary}.", summary=summary, body_excerpt=forms.redacted_body_excerpt(page.text)
+ )
+
+ candidates = _manifest_confirmation_candidates(doc, page)
+ if len(candidates) != 1:
+ if not candidates and forms.page_errors(page.text):
+ raise _unexpected_page_error("GitHub rejected the manifest", page)
+ actions = [urlparse(f.attrib.get("action", "")).path for f in doc.findall(".//form")]
+ raise page_shape_error(
+ f"Expected one manifest confirmation form with an {_MANIFEST_OWNER_FIELD} field, found "
+ f"{len(candidates)}. Form actions on the page: {actions}"
+ )
+
+ form = candidates[0]
+ offered = _offered_owner_logins(doc, form)
+ if len(offered) != 1:
+ raise page_shape_error(
+ f"The manifest confirmation form submits {len(offered)} values for {_MANIFEST_OWNER_FIELD}, "
+ f"not one"
+ )
+ signed_in = _signed_in_login(doc)
+ if org_name:
+ if offered[0].lower() != org_name.lower():
+ user = f"[{signed_in}]" if signed_in else "the signed-in user"
+ raise page_shape_error(
+ f"GitHub offered to create the app for [{offered[0]}], not [{org_name}] (is {user} "
+ f"an owner of [{org_name}]?)"
+ )
+ elif not signed_in:
+ raise page_shape_error(
+ f"GitHub offered to create the app for [{offered[0]}], but the page doesn't say which "
+ f"user is signed in (no user-login tag), so it can't be checked"
+ )
+ elif offered[0].lower() != signed_in.lower():
+ raise page_shape_error(
+ f"GitHub offered to create the app for [{offered[0]}], not for the signed-in user "
+ f"[{signed_in}]"
+ )
+
+ if not any(forms.is_submit_button(c) for c in forms.browser_controls(doc, form)[0]):
+ raise page_shape_error(
+ "The manifest confirmation form has no submit button, so a browser couldn't submit it either"
+ )
+ return form
+
+
+def _has_code(url: str) -> bool:
+ """True if `url` has a `code` query parameter that isn't blank."""
+ return any(code.strip() for code in parse_qs(urlparse(url).query).get("code", []))
+
+
+# A non-empty `code` query parameter's name and value in a URL.
+_URL_CODE_PARAMETER = re.compile(r"([?&]code=)([^]+)", re.I)
+
+
+def _redact_code(url: str) -> str:
+ """`url` with the value of each `code` query parameter replaced by
+ "[REDACTED]": the code converts into the app's private key."""
+ return _URL_CODE_PARAMETER.sub(lambda m: m.group(1) + forms.REDACTED, url)
+
+
+def _manifest_redirect_error(response: requests.Response, submit_url: str) -> forms.FormError:
+ """The error for a redirect that answered a manifest confirmation. GitHub
+ delivers the callback URL on a continue-setup page, not by a redirect
+ (see `_manifest_callback_from_page`). The message never carries the
+ redirect's `code`, if it has one.
+
+ Returns:
+ LoginChallengeError: GitHub redirected to its sign-in or sudo
+ confirmation page on `submit_url`'s host, so it did not act on
+ the confirmation.
+ forms.OutcomeUnknownError: Any other redirect, even to a URL with a
+ `code`. GitHub may have accepted the confirmation.
+ """
+ location = response.headers.get("Location", "")
+ target_url = urljoin(submit_url, location)
+ summary = forms.response_summary(response)
+ if (
+ location
+ and urlparse(target_url).netloc.lower() == urlparse(submit_url).netloc.lower()
+ and _is_login_page(target_url)
+ ):
+ return LoginChallengeError(
+ f"The manifest confirmation was redirected to GitHub's sign-in or sudo confirmation "
+ f"page [{_redact_code(location)}], so GitHub did not act on it. {summary}",
+ summary=summary,
+ )
+ return forms.OutcomeUnknownError(
+ f"The manifest confirmation was answered with a redirect to [{_redact_code(location)}] "
+ f"instead of a page with the callback URL, so whether GitHub accepted it is unknown. "
+ f"{summary}",
+ summary=summary,
+ )
+
+
+# The id of the link on the page GitHub answers a manifest confirmation with
+# ("You are being redirected to continue setup of your GitHub App. If your
+# browser does not redirect you automatically, please visit this setup
+# page"). Its href is the callback URL with the code.
+_MANIFEST_CALLBACK_LINK_ID = "redirect"
+# The content of a , as HTML parses it: a delay,
+# then optionally ";" or ",", an optional "url=" and the URL, optionally
+# quoted. For example "0; url='/callback?code=...'" or "0;/callback?code=...".
+_META_REFRESH_CONTENT = re.compile(
+ r"""\s*[\d.]*\s*[;,]?\s*(?:url\s*=\s*)?(?:'([^']*)'?|"([^"]*)"?|(.*))""", re.I | re.S
)
+def _meta_refresh_target(content: str) -> str:
+ """The URL of a `` with `content`, or ""."""
+ match = _META_REFRESH_CONTENT.match(content)
+ return next((group for group in match.groups() if group is not None), "") if match else ""
+
+
+def _page_callback_urls(response: requests.Response) -> list:
+ """The distinct absolute URLs with a `code` that `response`'s page sends
+ a browser to: the href of its `a#redirect` link and the target of a
+ ``."""
+ doc = forms.parse_page(response.text)
+ targets = [
+ a.attrib.get("href") or ""
+ for a in doc.iter("a")
+ if a.attrib.get("id") == _MANIFEST_CALLBACK_LINK_ID
+ ]
+ targets += [
+ _meta_refresh_target(meta.attrib.get("content") or "")
+ for meta in doc.iter("meta")
+ if (meta.attrib.get("http-equiv") or "").strip().lower() == "refresh"
+ ]
+ urls = []
+ for target in targets:
+ url = urljoin(response.url, target.strip())
+ if target.strip() and _has_code(url) and url not in urls:
+ urls.append(url)
+ return urls
+
+
+def _manifest_callback_from_page(response: requests.Response) -> str:
+ """The callback URL with the conversion `code` on the page that answered
+ a manifest confirmation without a redirect.
+
+ GitHub answers the confirmation with a 200 page that says it is
+ redirecting the browser to continue setting up the app, and puts the
+ callback URL in a `` and in its `a#redirect`
+ link. A single URL with a code (from either) is returned whatever the
+ page's status and visible errors, because the code is the only way to
+ the app's credentials.
+
+ Raises:
+ forms.FormRejectedError: The page has no URL with a code and shows
+ visible errors.
+ forms.PageShapeError: The page has no URL with a code or visible
+ errors, and a client error status (4xx), which GitHub returns
+ when it refuses a request. Its `body_excerpt` holds a redacted
+ excerpt of the page.
+ forms.OutcomeUnknownError: The page has a 2xx status, no URL with a
+ code and no visible errors, or it has several different URLs
+ with a code, so whether GitHub accepted the confirmation is
+ unknown. Its `body_excerpt` holds a redacted excerpt of the page.
+ """
+ urls = _page_callback_urls(response)
+ if len(urls) == 1:
+ return urls[0]
+ errors = forms.page_errors(response.text)
+ if not urls and (errors or not response.ok):
+ raise _unexpected_page_error("GitHub did not accept the manifest confirmation", response)
+ summary = forms.response_summary(response)
+ if urls:
+ problem = f"links to {len(urls)} different URLs with a code"
+ else:
+ problem = (
+ f"has no a#{_MANIFEST_CALLBACK_LINK_ID} link or meta refresh to a URL with a code"
+ )
+ raise forms.OutcomeUnknownError(
+ f"The manifest confirmation was answered without a redirect by a page that {problem}, "
+ f"so whether GitHub accepted it is unknown: {summary}. "
+ f"Visible errors: {'; '.join(errors) or 'none'}.",
+ summary=summary,
+ errors=errors,
+ body_excerpt=forms.redacted_body_excerpt(response.text),
+ )
class OrganizationUsage(Enum):
@@ -156,12 +522,24 @@ def __init__(
password: str,
tfa_callback=None,
session: Optional[requests.Session] = None,
+ base_url: str = GITHUB_URL,
):
+ """Signs in, unless a session is given.
+
+ `base_url` is the GitHub web root: "https://github.com" (the default)
+ or a GitHub Enterprise Server URL such as "https://github.example.com".
+
+ Raises:
+ ValueError: `base_url` is not the absolute http(s) URL of a web
+ root.
+ """
+ self._base_url = _normalize_base_url(base_url)
self._session = session or create_login_session(
username=username,
password=password,
tfa_callback=tfa_callback,
session=session,
+ base_url=self._base_url,
)
def request_usage(self, enterprise_name: str, days: int = 30) -> requests.Response:
@@ -174,7 +552,9 @@ def _request_usage_callback(data):
data["days"] = days
action = f"/enterprises/{enterprise_name}/settings/metered_exports"
- url = url = _REQUEST_USAGE_URL.format(enterprise_name=enterprise_name)
+ url = _REQUEST_USAGE_URL.format(
+ base_url=self._base_url, enterprise_name=enterprise_name
+ )
return _get_and_submit_form(
session=self._session,
url=url,
@@ -182,6 +562,121 @@ def _request_usage_callback(data):
form_matcher=lambda form: form.attrib.get("action") == action,
)
+ def create_app_from_manifest(
+ self,
+ manifest_payload: str,
+ state: str,
+ org_name: Optional[str] = None,
+ timeout: int = forms.DEFAULT_TIMEOUT_SECONDS,
+ ) -> str:
+ """Confirms a GitHub App manifest; returns the callback URL with its code.
+
+ Follows GitHub's manifest flow
+ (https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest)
+ the way a browser does:
+
+ 1. POST `manifest_payload` with `state` to the new-app page of the
+ signed-in user, or of `org_name` if set. This changes nothing;
+ GitHub answers with a redirect to a confirmation page.
+ 2. Check that the confirmation form makes `org_name` (or the
+ signed-in user) the app's owner, then submit it exactly as a
+ browser would, without following any redirect.
+ 3. Return the URL GitHub sends the browser to next: the manifest's
+ `redirect_url` with the single-use `code` and `state` query
+ parameters. GitHub answers the confirmation with a 200 page
+ saying it is redirecting to continue setting up the app, whose
+ `` and `a#redirect` link hold it.
+
+ Exchange the code for the app's ID and private key with the REST API
+ (`POST /app-manifests/{code}/conversions`), and check that `state`
+ matches. The code is delivered only here. The exchange is what
+ registers the app: confirming the manifest does not, so if the code is
+ lost after the confirmation, no app is left behind.
+
+ Args:
+ manifest_payload: The manifest, JSON-encoded.
+ state: Opaque value GitHub echoes back in the callback URL.
+ org_name: Organization that will own the app; the signed-in user
+ if None. The signed-in user must be allowed to create the
+ organization's apps (an organization owner).
+ timeout: Seconds to wait for each HTTP response.
+
+ Raises:
+ LoginChallengeError: GitHub sent the session to its sign-in or
+ sudo confirmation page. No app was created.
+ forms.FormRejectedError: GitHub rendered visible errors instead of
+ the confirmation page, or answered the confirmation with
+ visible errors and no URL with a `code`.
+ forms.PageShapeError: The manifest was answered with an error
+ status or without a single confirmation form with a submit
+ button, or the confirmation form would make another account
+ the app's owner (as GitHub offers when the signed-in user
+ can't create `org_name`'s apps); the confirmation was not
+ sent. Or the confirmation was answered with a client error
+ status (4xx) and no URL with a `code`. Its `body_excerpt`
+ holds a redacted excerpt of the page.
+ forms.OutcomeUnknownError: The confirmation may have reached
+ GitHub, but no definitive answer came back; GitHub answered
+ with a redirect (even to a URL with a `code`) to anywhere
+ but its sign-in or sudo confirmation page; or it answered
+ with a page that links to several different URLs with a
+ `code`, or with a 2xx page that has no URL with a `code` and
+ no visible errors (for these pages, `body_excerpt` holds a
+ redacted excerpt). Whether GitHub accepted the confirmation
+ is unknown; no app was registered either way, since that
+ takes exchanging a code and the caller gets none.
+ requests.RequestException: Step 1 failed, or the confirmation was
+ never sent or was rate limited. No app was created. Step 1 is
+ retried on rate limits and server errors. It is not retried
+ on read errors (a read timeout or dropped connection), since
+ the transport retries don't resend a POST after one. With a
+ session passed to `Api(session=...)` it has no transport
+ retries at all, not even for connection failures, unless the
+ caller mounted them (see `forms.configure_session_adapters`).
+ """
+ apps_path = _ORG_APPS_PATH.format(org_name=org_name) if org_name else _USER_APPS_PATH
+ try:
+ preview = forms.request_with_retry(
+ self._session,
+ "POST",
+ f"{self._base_url}{apps_path}/new",
+ params={"state": state},
+ data={"manifest": manifest_payload},
+ # Posting a manifest only renders the confirmation page.
+ retry_unsafe_methods=True,
+ timeout=timeout,
+ )
+ except requests.HTTPError as e:
+ if e.response is None or forms.is_retryable(e.response):
+ raise
+ # For example a 404 for an organization the user doesn't own:
+ # retrying cannot help.
+ raise _unexpected_page_error(
+ "GitHub did not render the manifest confirmation page", e.response
+ ) from e
+ if _is_login_page(preview.url):
+ raise LoginChallengeError(
+ f"The manifest was answered with GitHub's sign-in or sudo confirmation page. "
+ f"{forms.response_summary(preview)}",
+ summary=forms.response_summary(preview),
+ )
+
+ doc = forms.parse_page(preview.text)
+ form = _find_manifest_confirmation_form(doc, preview, org_name)
+ data = forms.browser_form_data(doc, form)
+ submit_url = urljoin(preview.url, form.attrib.get("action") or preview.url)
+ logging.info("Confirming GitHub App manifest at %s", submit_url)
+ response = forms.submit_once(
+ self._session, submit_url, data=data, allow_redirects=False, timeout=timeout
+ )
+
+ if 300 <= response.status_code < 400:
+ raise _manifest_redirect_error(response, submit_url)
+ if forms.is_retryable(response):
+ # Rate limited before GitHub acted on the confirmation.
+ response.raise_for_status()
+ return _manifest_callback_from_page(response)
+
def create_organization(
self,
org_name: str,
@@ -205,7 +700,7 @@ def _create_org_callback(data):
return _get_and_submit_form(
session=self._session,
- url=_CREATE_ORG_URL,
+ url=_CREATE_ORG_URL.format(base_url=self._base_url),
data_callback=_create_org_callback,
form_matcher=lambda f: f.attrib.get("id") == "org-new-form",
)
@@ -214,7 +709,7 @@ def install_application_in_organization(
self, app_name: str, org_id: int
) -> requests.Response:
"""Installs the specified app on the given organization."""
- url = _INSTALL_APP_URL.format(app_name=app_name, org_id=org_id)
+ url = _INSTALL_APP_URL.format(base_url=self._base_url, app_name=app_name, org_id=org_id)
def _install_app_callback(data):
data["install_target"] = "all"
@@ -230,7 +725,9 @@ def toggle_app_suspended(
self, org_name: str, app_install_id: int
) -> requests.Response:
"""Set this applicaiton install to be suspended or not."""
- url = _APP_SUSPEND_URL.format(org_name=org_name, app_install_id=app_install_id)
+ url = _APP_SUSPEND_URL.format(
+ base_url=self._base_url, org_name=org_name, app_install_id=app_install_id
+ )
return _get_and_submit_form(
session=self._session,
@@ -243,7 +740,7 @@ def download_usage_report(
) -> requests.Response:
"""Download a usage report based on an id recieved in an email"""
url = _USAGE_REPORT_URL.format(
- enterprise_name=enterprise_name, report_id=report_id
+ base_url=self._base_url, enterprise_name=enterprise_name, report_id=report_id
)
return _get_url_with_session(session=self._session, url=url)
@@ -254,7 +751,9 @@ def request_dormant_users_report(self, enterprise_name: str) -> requests.Respons
"""
action = f"/enterprises/{enterprise_name}/settings/dormant-users/exports"
- url = url = _REQUEST_DORMANTUSERS_URL.format(enterprise_name=enterprise_name)
+ url = _REQUEST_DORMANTUSERS_URL.format(
+ base_url=self._base_url, enterprise_name=enterprise_name
+ )
return _get_and_submit_form(
session=self._session,
url=url,
@@ -263,14 +762,19 @@ def request_dormant_users_report(self, enterprise_name: str) -> requests.Respons
def download_dormant_users_report(self, enterprise_name: str) -> requests.Response:
"""Download a usage report based on an id received in an email"""
- url = _REQUEST_DORMANTUSERS_URL.format(enterprise_name=enterprise_name)
+ url = _REQUEST_DORMANTUSERS_URL.format(
+ base_url=self._base_url, enterprise_name=enterprise_name
+ )
page = _get_url_with_session(session=self._session, url=url)
try:
page_content = page.content.decode("utf-8")
except UnicodeDecodeError:
raise ValueError("Unable to decode page content as UTF-8.")
link = re.search(
- r"https://github.com/enterprises/alphabet/settings/dormant-users/exports/[0-9A-Fa-f]{8}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{12}",
+ re.escape(self._base_url)
+ + "/enterprises/"
+ + re.escape(enterprise_name)
+ + r"/settings/dormant-users/exports/[0-9A-Fa-f]{8}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{12}",
page_content,
)
if link is None:
@@ -287,6 +791,7 @@ def approve_updated_app_permissions(
return _get_and_submit_form(
session=self._session,
url=_UPDATE_APP_INSTALL_URL.format(
+ base_url=self._base_url,
org_name=org_name,
app_install_id=app_install_id,
),
@@ -309,6 +814,7 @@ def _data_callback(data):
_get_and_submit_form(
session=self._session,
url=_UPDATE_GHAS_SETTINGS_URL.format(
+ base_url=self._base_url,
org_name=org_name,
),
form_matcher=functools.partial(_form_matcher, name='code_scanning_autofix'),
@@ -320,6 +826,7 @@ def _data_callback(data):
_get_and_submit_form(
session=self._session,
url=_UPDATE_GHAS_SETTINGS_URL.format(
+ base_url=self._base_url,
org_name=org_name,
),
form_matcher=functools.partial(_form_matcher, name='code_scanning_autofix_third_party_tools'),
diff --git a/github_nonpublic_api/forms.py b/github_nonpublic_api/forms.py
index b634279..17cf167 100644
--- a/github_nonpublic_api/forms.py
+++ b/github_nonpublic_api/forms.py
@@ -38,8 +38,9 @@
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.
+`PageShapeError` raised for a response, or an `OutcomeUnknownError` raised
+for a page that neither confirms nor rejects a submission, also carries a
+redacted excerpt of the page, outside the error message.
"""
from __future__ import annotations
@@ -81,9 +82,12 @@ class FormError(Exception):
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`.
+ HTML. It is set only when the page itself needs diagnosing
+ because GitHub answered with a page of unexpected shape: by a
+ `PageShapeError` raised for a response, or by an
+ `OutcomeUnknownError` raised because a submission was answered
+ with a page that neither confirms nor rejects it. Other errors
+ are explained by `summary` and `errors`.
"""
def __init__(
diff --git a/requirements.txt b/requirements.txt
index 3f16464..8e8767f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,7 +3,9 @@ configobj==5.0.9
html5lib==1.1
pyotp==2.9.0
pytest==8.4.0
+PyYAML==6.0.3
requests==2.32.4
+responses==0.26.3
ruff==0.11.13
six==1.17.0
typing_extensions==4.13.2
diff --git a/tests/app_manifest_confirmation.html b/tests/app_manifest_confirmation.html
new file mode 100644
index 0000000..27e0cc0
--- /dev/null
+++ b/tests/app_manifest_confirmation.html
@@ -0,0 +1,1397 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Create GitHub App
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ You signed in with another tab or window. Reload to refresh your session.
+ You signed out in another tab or window. Reload to refresh your session.
+ You switched accounts on another tab or window. Reload to refresh your session.
+
+ Dismiss alert
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ message }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Create GitHub App
+
+
+
+
Don't worry, you can always change this later.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ You can’t perform that action at this time.
+
You are being redirected to continue setup of your GitHub App.
+
If your browser does not redirect you automatically, please visit this setup page to continue.
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/test_api.py b/tests/test_api.py
index 75b47d5..c76c86e 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -14,10 +14,17 @@
"""Unit tests for api.py."""
+import html
import os
from unittest import TestCase, mock
+from urllib.parse import parse_qsl, urljoin
+
+import requests
+import responses
+from responses import matchers
from github_nonpublic_api import api
+from github_nonpublic_api import forms
GITHUB_FORM_HTML = os.path.join(os.path.dirname(__file__), 'github_form.html')
NEW_ORG_FORM_HTML = os.path.join(
@@ -34,6 +41,10 @@
os.path.dirname(__file__), 'update_app_permissions.html')
SECURITY_ANALYSIS_FORM_HTML = os.path.join(
os.path.dirname(__file__), 'security_analysis_form.html')
+APP_MANIFEST_CONFIRMATION_HTML = os.path.join(
+ os.path.dirname(__file__), 'app_manifest_confirmation.html')
+APP_MANIFEST_CONTINUE_SETUP_HTML = os.path.join(
+ os.path.dirname(__file__), 'app_manifest_continue_setup.html')
class TestApi(TestCase):
@@ -87,9 +98,11 @@ def test_create_login_session_captcha_challenge(self):
def test_create_login_session_success(self):
with mock.patch.object(api, '_get_and_submit_form') as mock_submit:
- mock_res = mock.MagicMock()
- mock_res.url = 'https://github.com/sessions/two-factor'
- mock_submit.return_value = mock_res
+ # The password lands on the two-factor page; the code on the dashboard.
+ mock_submit.side_effect = [
+ mock.MagicMock(url='https://github.com/sessions/two-factor'),
+ mock.MagicMock(url='https://github.com/'),
+ ]
session = api.create_login_session(
username='user', password='password', tfa_callback=lambda: '123'
@@ -203,3 +216,750 @@ def test_update_security_analysis_settings_code_scanning_3p(self):
'code_scanning_autofix_third_party_tools': 'enabled',
},
)
+
+ def test_base_url_applies_to_existing_methods(self):
+ self._seed_session_with_file(NEW_ORG_FORM_HTML)
+ gh = api.Api(username='user', password='pass', session=self.session,
+ base_url='https://github.example.com/')
+ gh.create_organization(org_name='test', contact_email='nobody@google.com',
+ org_usage=api.OrganizationUsage.PERSONAL)
+ self.session.get.assert_called_once_with(
+ 'https://github.example.com/account/organizations/new?plan=free')
+ self.assertEqual(self.session.post.call_args.args[0],
+ 'https://github.example.com/account/organizations/new_org')
+
+ def test_download_dormant_users_report_follows_the_link_for_base_url_and_enterprise(self):
+ export_path = '/settings/dormant-users/exports/0123abcd-0123-4567-89ab-0123456789ab'
+ export = 'https://github.example.com/enterprises/test-enterprise' + export_path
+ self.session = mock.MagicMock()
+ self.session.get.return_value.content = (
+ f'github.com'
+ f'other'
+ f'report').encode()
+ gh = api.Api(username='user', password='pass', session=self.session,
+ base_url='https://github.example.com/')
+ gh.download_dormant_users_report(enterprise_name='test-enterprise')
+ self.assertEqual(self.session.get.call_args_list, [
+ mock.call('https://github.example.com/enterprises/test-enterprise/settings/compliance'),
+ mock.call(export),
+ ])
+
+
+class TestCreateLoginSession(TestCase):
+ """Login with an optional TOTP callback on github.com or GHES."""
+
+ BASE = 'https://github.example.com'
+
+ def _login(self, landing_url, tfa_callback=None, after_code_url=None, **kwargs):
+ """Signs in with `_get_and_submit_form` mocked: the password form
+ lands on `landing_url`, and the two-factor form, if submitted, on
+ `after_code_url` (the dashboard by default)."""
+ after_code = mock.Mock(url=after_code_url or self.BASE + '/')
+ with mock.patch.object(api, '_get_and_submit_form') as mock_submit:
+ mock_submit.side_effect = [mock.Mock(url=landing_url), after_code]
+ session = api.create_login_session(
+ username='user', password='password', tfa_callback=tfa_callback,
+ base_url=self.BASE + '/', **kwargs)
+ return session, mock_submit
+
+ def test_without_tfa_callback_signs_in_with_one_form(self):
+ session, mock_submit = self._login(self.BASE + '/')
+ self.assertIsNotNone(session)
+ mock_submit.assert_called_once()
+ self.assertEqual(mock_submit.call_args.kwargs['url'], self.BASE + '/login')
+
+ def test_without_tfa_callback_challenge_pages_raise(self):
+ for path in ('/sessions/verified-device', '/session', '/login?return_to=%2F',
+ '/login/device'):
+ with self.assertRaisesRegex(
+ api.LoginChallengeError,
+ r'Sign-in did not complete \(wrong credentials, captcha or device '
+ r'verification\)'):
+ self._login(self.BASE + path)
+
+ def test_without_tfa_callback_two_factor_prompt_raises(self):
+ with self.assertRaisesRegex(api.LoginChallengeError, 'no tfa_callback'):
+ self._login(self.BASE + '/sessions/two-factor/app')
+
+ def test_challenge_is_still_a_runtime_error(self):
+ with self.assertRaises(RuntimeError):
+ self._login(self.BASE + '/sessions/verified-device')
+
+ def test_with_tfa_callback_submits_code_to_base_url(self):
+ _, mock_submit = self._login(self.BASE + '/sessions/two-factor', tfa_callback=lambda: '123')
+ self.assertEqual(mock_submit.call_count, 2)
+ self.assertEqual(mock_submit.call_args.kwargs['url'], self.BASE + '/sessions/two-factor')
+ data = {}
+ mock_submit.call_args.kwargs['data_callback'](data)
+ self.assertEqual(data, {'otp': '123'})
+
+ def test_with_tfa_callback_rejected_code_raises(self):
+ for after_code_path in ('/sessions/two-factor', '/sessions/two-factor/app', '/login'):
+ with self.subTest(after_code_path=after_code_path):
+ with self.assertRaises(api.LoginChallengeError) as ctx:
+ self._login(self.BASE + '/sessions/two-factor', tfa_callback=lambda: '123',
+ after_code_url=self.BASE + after_code_path)
+ self.assertEqual(str(ctx.exception), 'Two-factor code was not accepted. Stuck at: '
+ + self.BASE + after_code_path)
+
+ def test_with_tfa_callback_off_host_page_after_code_is_signed_in(self):
+ session, _ = self._login(self.BASE + '/sessions/two-factor', tfa_callback=lambda: '123',
+ after_code_url='https://idp.example.com/login')
+ self.assertIsNotNone(session)
+
+ def test_with_tfa_callback_challenge_on_base_host_raises(self):
+ with self.assertRaisesRegex(api.LoginChallengeError,
+ 'expected a two-factor prompt.*verified-device'):
+ self._login(self.BASE + '/sessions/verified-device', tfa_callback=lambda: '123')
+
+ def test_mounts_transport_retries_on_given_session(self):
+ session, _ = self._login(self.BASE + '/', session=requests.Session())
+ self.assertEqual(session.adapters['https://'].max_retries.total, 3)
+
+ def test_with_tfa_callback_off_host_landing_still_submits_code(self):
+ # Upstream behavior: only a non-two-factor page on the GitHub host is a
+ # challenge; anywhere else, the code is still submitted.
+ _, mock_submit = self._login('https://idp.example.com/sso', tfa_callback=lambda: '123')
+ self.assertEqual(mock_submit.call_count, 2)
+ self.assertEqual(mock_submit.call_args.kwargs['url'], self.BASE + '/sessions/two-factor')
+
+ def test_base_url_must_be_absolute(self):
+ for bad in ('github.example.com', 'ftp://github.example.com', 'https://', '',
+ 'https://github.example.com/prefix', 'https://github.example.com/prefix/',
+ 'https://github.example.com/;x', 'https://github.example.com?x=1',
+ 'https://github.example.com/?', 'https://github.example.com#top',
+ 'https://github.example.com/#'):
+ with self.subTest(base_url=bad), mock.patch.object(api, '_get_and_submit_form') as m:
+ with self.assertRaisesRegex(ValueError, 'absolute http'):
+ api.create_login_session('u', 'p', base_url=bad)
+ m.assert_not_called()
+
+ def test_base_url_may_end_with_slashes(self):
+ for base_url in ('https://github.example.com/', 'https://github.example.com//'):
+ with self.subTest(base_url=base_url):
+ gh = api.Api(username='u', password='p', session=requests.Session(),
+ base_url=base_url)
+ self.assertEqual(gh._base_url, 'https://github.example.com')
+
+ def test_api_validates_base_url_with_a_given_session(self):
+ for bad in ('github.example.com', 'https://github.example.com/prefix'):
+ with self.subTest(base_url=bad), self.assertRaisesRegex(ValueError, 'absolute http'):
+ api.Api(username='u', password='p', session=requests.Session(), base_url=bad)
+
+
+MANIFEST = '{"name": "Test App", "redirect_url": "http://127.0.0.1/callback"}'
+CALLBACK = 'http://127.0.0.1/callback?code=c0de&state=s1'
+# The callback URL in the continue-setup page fixture.
+CONTINUE_SETUP_CALLBACK = 'http://127.0.0.1/callback?code=FIXTURE_CODE&state=test_state'
+# Text that must never appear in an exception message: messages carry visible
+# errors and a response summary, never the page body.
+BODY_MARKER = 'BODY-MARKER-NOT-IN-MESSAGES'
+
+
+class TestCreateAppFromManifest(TestCase):
+ BASE = 'https://github.example.com'
+ ORG_NEW = BASE + '/organizations/test-org/settings/apps/new'
+ # GitHub answers a manifest posted to a new-app page with a redirect to
+ # this page, which renders the confirmation form.
+ MANIFEST_PAGE = BASE + '/settings/apps/manifest'
+ # Where the confirmation form posts, for organization- and user-owned
+ # apps alike.
+ CONFIRM = BASE + '/settings/apps'
+ # The continue-setup page's meta refresh and the href of its a#redirect
+ # link, both to the callback.
+ CONTINUE_SETUP_META_REFRESH = (
+ '')
+ CONTINUE_SETUP_LINK_HREF = 'href="http://127.0.0.1/callback?code=FIXTURE_CODE&state=test_state"'
+
+ def setUp(self):
+ self.gh = api.Api(username='u', password='p', session=requests.Session(),
+ base_url=self.BASE + '/')
+ with open(APP_MANIFEST_CONFIRMATION_HTML) as fp:
+ self.page = fp.read()
+ # What GitHub offers when the signed-in user, test-user, can't create
+ # test-org's apps, or when the manifest was posted for test-user.
+ self.user_page = (
+ self.page.replace('value="test-org"', 'value="test-user"')
+ .replace('for test-org', 'for test-user'))
+ # The continue-setup page that answers the confirmation.
+ with open(APP_MANIFEST_CONTINUE_SETUP_HTML) as fp:
+ self.continue_setup_page = fp.read()
+
+ def _add_preview(self, body=None, url=None, redirect=True):
+ """Answers the manifest POST to `url` (the organization's new-app
+ page by default) with `body`, the fixture by default: rendered at
+ the redirect target as GitHub does, or directly if not
+ `redirect`."""
+ url = url or self.ORG_NEW
+ body = self.page if body is None else body
+ match = [matchers.query_param_matcher({'state': 's1'}),
+ matchers.urlencoded_params_matcher({'manifest': MANIFEST})]
+ if not redirect:
+ return responses.post(url, body=body, match=match)
+ manifest_page = urljoin(url, '/settings/apps/manifest')
+ responses.post(url, status=302, headers={'Location': manifest_page}, match=match)
+ return responses.get(manifest_page, body=body)
+
+ def _add_confirm(self, **kwargs):
+ return responses.post(self.CONFIRM, **kwargs)
+
+ def _create(self, **kwargs):
+ return self.gh.create_app_from_manifest(
+ manifest_payload=MANIFEST, state='s1', org_name='test-org', **kwargs)
+
+ def _assert_body_not_in(self, error):
+ self.assertNotIn(BODY_MARKER, str(error))
+ self.assertNotIn(BODY_MARKER, error.summary)
+
+ @responses.activate
+ def test_submits_manifest_then_confirmation_and_returns_callback(self):
+ self._add_preview()
+ self._add_confirm(body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+ # The manifest POST's redirect to the confirmation page is followed;
+ # the callback itself is never requested.
+ self.assertEqual([(c.request.method, c.request.url.split('?')[0]) for c in responses.calls], [
+ ('POST', self.ORG_NEW),
+ ('GET', self.MANIFEST_PAGE),
+ ('POST', self.CONFIRM),
+ ])
+ self.assertEqual(parse_qsl(responses.calls[2].request.body, keep_blank_values=True), [
+ ('authenticity_token', 'FIXTURE_TOKEN'),
+ ('integration_manifest[name]', 'test-app'),
+ ('integration_manifest[data]',
+ '{"name": "test-app", "url": "https://example.com", "public": false, '
+ '"redirect_url": "http://127.0.0.1/callback"}'),
+ ('integration_manifest[owner_login]', 'test-org'),
+ ('integration_manifest[manifest_token]', 'FIXTURE_MANIFEST_TOKEN'),
+ ('integration_manifest[state]', 'test_state'),
+ ('commit', 'Create GitHub App for test-org'),
+ ])
+
+ @responses.activate
+ def test_user_owned_app_with_default_base_url(self):
+ gh = api.Api(username='u', password='p', session=requests.Session())
+ self._add_preview(body=self.user_page, url='https://github.com/settings/apps/new')
+ responses.post('https://github.com/settings/apps', body=self.continue_setup_page)
+ self.assertEqual(gh.create_app_from_manifest(MANIFEST, 's1'), CONTINUE_SETUP_CALLBACK)
+ self.assertIn(('integration_manifest[owner_login]', 'test-user'),
+ parse_qsl(responses.calls[2].request.body))
+
+ @responses.activate
+ def test_user_owned_form_does_not_confirm_an_org_owned_app(self):
+ # GitHub answered a manifest posted to an organization the user
+ # didn't own with a redirect to the user's confirmation page, which
+ # would have made the app user-owned.
+ self._add_preview(body=self.user_page)
+ with self.assertRaisesRegex(
+ forms.PageShapeError,
+ r'^GitHub offered to create the app for \[test-user\], not \[test-org\] \(is '
+ r'\[test-user\] an owner of \[test-org\]\?\): HTTP 200 at .*/settings/apps/manifest '
+ r"after redirects \[302 .*\]; page title 'Create GitHub App'\.$") as ctx:
+ self._create()
+ excerpt = ctx.exception.body_excerpt
+ self.assertIn('value="test-user" type="hidden" name="integration_manifest[owner_login]"',
+ excerpt)
+ self.assertNotIn('FIXTURE_MANIFEST_TOKEN', excerpt)
+ self.assertNotIn('FIXTURE_TOKEN', excerpt)
+ self.assertEqual(len(responses.calls), 2)
+ self.assertEqual(responses.calls[1].request.method, 'GET')
+
+ @responses.activate
+ def test_org_mismatch_without_user_login_meta_names_no_user(self):
+ page = self.user_page.replace('', '')
+ self._add_preview(body=page)
+ with self.assertRaisesRegex(forms.PageShapeError,
+ r'not \[test-org\] \(is the signed-in user an owner of \[test-org\]\?\)'):
+ self._create()
+ self.assertEqual(len(responses.calls), 2)
+
+ @responses.activate
+ def test_org_owned_form_does_not_confirm_a_user_owned_app(self):
+ responses.post(self.BASE + '/settings/apps/new', body=self.page)
+ with self.assertRaisesRegex(
+ forms.PageShapeError,
+ r'offered to create the app for \[test-org\], not for the signed-in user \[test-user\]'):
+ self.gh.create_app_from_manifest(MANIFEST, 's1')
+ self.assertEqual(len(responses.calls), 1)
+
+ @responses.activate
+ def test_user_owned_app_requires_the_signed_in_login(self):
+ page = self.user_page.replace('', '')
+ responses.post(self.BASE + '/settings/apps/new', body=page)
+ with self.assertRaisesRegex(forms.PageShapeError, r"doesn't say which user is signed in"):
+ self.gh.create_app_from_manifest(MANIFEST, 's1')
+ self.assertEqual(len(responses.calls), 1)
+
+ @responses.activate
+ def test_form_is_found_by_its_owner_field_wherever_it_posts(self):
+ page = self.page.replace('action="/settings/apps"',
+ 'action="/organizations/test-org/settings/apps"')
+ self._add_preview(body=page)
+ responses.post(self.BASE + '/organizations/test-org/settings/apps',
+ body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+
+ @responses.activate
+ def test_confirmation_is_posted_to_the_form_action_with_its_query(self):
+ page = self.page.replace('action="/settings/apps"',
+ 'action="/settings/apps?state=test-state"')
+ self._add_preview(body=page)
+ self._add_confirm(match=[matchers.query_param_matcher({'state': 'test-state'})],
+ body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+
+ @responses.activate
+ def test_owner_field_that_a_browser_would_not_submit_raises(self):
+ page = self.page.replace('name="integration_manifest[owner_login]"',
+ 'name="integration_manifest[owner_login]" disabled')
+ self._add_preview(body=page)
+ with self.assertRaisesRegex(forms.PageShapeError, r'submits 0 values for integration_manifest'):
+ self._create()
+ self.assertEqual(len(responses.calls), 2)
+
+ @responses.activate
+ @mock.patch('time.sleep', return_value=None)
+ def test_manifest_post_is_retried_because_it_changes_nothing(self, mock_sleep):
+ responses.post(self.ORG_NEW, status=502)
+ self._add_preview()
+ self._add_confirm(body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+ self.assertEqual(len(responses.calls), 4)
+ mock_sleep.assert_called_once()
+
+ @responses.activate
+ def test_sign_in_page_raises_login_challenge(self):
+ responses.post(self.ORG_NEW, status=302,
+ headers={'Location': self.BASE + '/login?return_to=x'})
+ responses.get(self.BASE + '/login', body='Sign in')
+ with self.assertRaisesRegex(api.LoginChallengeError,
+ "sign-in or sudo confirmation page.*'Sign in'"):
+ self._create()
+ self.assertEqual(len(responses.calls), 2)
+
+ @responses.activate
+ def test_rejected_manifest_raises_visible_errors(self):
+ self._add_preview(body=f'
{BODY_MARKER}
'
+ '
Invalid manifest
',
+ redirect=False)
+ with self.assertRaises(forms.FormRejectedError) as ctx:
+ self._create()
+ self.assertEqual(ctx.exception.errors, ['Invalid manifest'])
+ self.assertIn('HTTP 200 at ' + self.ORG_NEW, ctx.exception.summary)
+ self._assert_body_not_in(ctx.exception)
+ self.assertEqual(ctx.exception.body_excerpt, '') # Explained by the errors.
+ self.assertEqual(len(responses.calls), 1)
+
+ @responses.activate
+ def test_missing_confirmation_form_raises_page_shape(self):
+ # A POST form to the confirmation's action without an owner field
+ # isn't one.
+ self._add_preview(body=f'
{BODY_MARKER}
'
+ '
'
+ ''
+ '
')
+ with self.assertRaisesRegex(
+ forms.PageShapeError,
+ r"^Expected one manifest confirmation form with an "
+ r"integration_manifest\[owner_login\] field, found 0\. Form actions on the page: "
+ r"\['/search', '/settings/apps'\]: HTTP 200 at .*/settings/apps/manifest ") as ctx:
+ self._create()
+ self._assert_body_not_in(ctx.exception)
+ self.assertIn(BODY_MARKER, ctx.exception.body_excerpt)
+ self.assertEqual(len(responses.calls), 2)
+
+ @responses.activate
+ def test_ambiguous_confirmation_forms_raise_page_shape(self):
+ extra = ('
')
+ with self.assertRaisesRegex(
+ forms.FormRejectedError,
+ r"HTTP 200 at https://github\.example\.com/settings/apps \(no redirect\); page title "
+ r"'New GitHub App'\. Visible errors: Name has already been taken\.$") as ctx:
+ self._create()
+ self.assertEqual(ctx.exception.errors, ['Name has already been taken'])
+ self._assert_body_not_in(ctx.exception)
+ self.assertEqual(ctx.exception.body_excerpt, '')
+
+ @responses.activate
+ def test_confirmation_answered_with_unrecognized_page_is_unknown_outcome(self):
+ # The confirmation was sent and the page neither delivers a code nor
+ # shows an error, so whether GitHub accepted it is unknown.
+ self._add_preview()
+ self._add_confirm(body=f'
{BODY_MARKER}
')
+ with self.assertRaisesRegex(
+ forms.OutcomeUnknownError,
+ r'^The manifest confirmation was answered without a redirect by a page that has no '
+ r'a#redirect link or meta refresh to a URL with a code, so whether GitHub accepted '
+ r'it is unknown: HTTP 200 at .*/settings/apps \(no redirect\)\. Visible errors: '
+ r'none\.$') as ctx:
+ self._create()
+ self._assert_body_not_in(ctx.exception)
+ self.assertEqual(ctx.exception.body_excerpt, f'
{BODY_MARKER}
')
+ self.assertEqual(len(responses.calls), 3)
+
+ @responses.activate
+ def test_unrecognized_page_excerpt_never_carries_the_manifest_code(self):
+ # The code converts into the app's private key, so a page that links
+ # to the callback, but not the way the continue-setup page does, must
+ # not leak it through the excerpt.
+ self._add_preview()
+ self._add_confirm(body=f'continue'
+ '')
+ with self.assertRaises(forms.OutcomeUnknownError) as ctx:
+ self._create()
+ excerpt = ctx.exception.body_excerpt
+ self.assertNotIn('c0de', excerpt)
+ self.assertNotIn('c0de', str(ctx.exception))
+ self.assertIn('callback?code=[REDACTED]&state=s1', excerpt)
+
+ @responses.activate
+ def test_continue_setup_page_returns_its_callback_link(self):
+ # GitHub answers the confirmation with a 200 page whose meta refresh
+ # and a#redirect link carry the code. They point to the same URL: one
+ # callback.
+ self.assertIn(self.CONTINUE_SETUP_META_REFRESH, self.continue_setup_page)
+ self.assertIn(self.CONTINUE_SETUP_LINK_HREF, self.continue_setup_page)
+ self._add_preview()
+ self._add_confirm(body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+ # The callback itself is never requested.
+ self.assertEqual(len(responses.calls), 3)
+
+ @responses.activate
+ def test_continue_setup_page_relative_link_is_resolved_against_the_page(self):
+ page = self.continue_setup_page.replace('http://127.0.0.1/callback?', '/callback?')
+ self._add_preview()
+ self._add_confirm(body=page)
+ self.assertEqual(self._create(),
+ self.BASE + '/callback?code=FIXTURE_CODE&state=test_state')
+
+ def test_continue_setup_page_without_code_is_unknown_outcome(self):
+ for link in ('http://127.0.0.1/callback?state=test_state',
+ 'http://127.0.0.1/callback?code=&state=test_state',
+ 'http://127.0.0.1/callback?code=%20&state=test_state',
+ ''):
+ with self.subTest(link=link), responses.RequestsMock() as rsps:
+ page = self.continue_setup_page.replace(
+ 'http://127.0.0.1/callback?code=FIXTURE_CODE&state=test_state', link)
+ self.assertNotIn('FIXTURE_CODE', page)
+ rsps.post(self.ORG_NEW, status=302, headers={'Location': self.MANIFEST_PAGE})
+ rsps.get(self.MANIFEST_PAGE, body=self.page)
+ rsps.post(self.CONFIRM, body=page)
+ with self.assertRaisesRegex(forms.OutcomeUnknownError,
+ r"has no a#redirect link.*whether GitHub accepted it "
+ r"is unknown.*"
+ r"'Continue setting up your GitHub App'") as ctx:
+ self._create()
+ self.assertIn('You are being redirected to continue setup',
+ ctx.exception.body_excerpt)
+ self.assertEqual(ctx.exception.errors, [])
+
+ @responses.activate
+ def test_meta_refresh_to_a_url_with_a_code_is_returned(self):
+ self._add_preview()
+ self._add_confirm(body='')
+ self.assertEqual(self._create(), CALLBACK)
+
+ def test_meta_refresh_content_is_parsed_as_a_browser_does(self):
+ # The "url=" prefix and the quotes are optional.
+ for content in (f'0; url={CALLBACK}', f'0;URL="{CALLBACK}"', f' 0 , {CALLBACK} ',
+ f'0;{CALLBACK}', f"1.5; url = '{CALLBACK}"):
+ with self.subTest(content=content), responses.RequestsMock() as rsps:
+ rsps.post(self.ORG_NEW, status=302, headers={'Location': self.MANIFEST_PAGE})
+ rsps.get(self.MANIFEST_PAGE, body=self.page)
+ rsps.post(self.CONFIRM, body=(f''))
+ self.assertEqual(self._create(), CALLBACK)
+
+ @responses.activate
+ def test_meta_refresh_without_a_url_is_not_a_callback(self):
+ self._add_preview()
+ self._add_confirm(body='')
+ with self.assertRaisesRegex(forms.OutcomeUnknownError, 'has no a#redirect link'):
+ self._create()
+
+ @responses.activate
+ def test_callback_link_on_a_client_error_page_is_returned(self):
+ # Withholding a delivered code would lose the only way to register
+ # the app and to reach its credentials; a code GitHub didn't issue
+ # just fails to convert.
+ self._add_preview()
+ self._add_confirm(status=422, body=self.continue_setup_page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+
+ def test_continue_setup_page_link_or_meta_refresh_alone_is_the_callback(self):
+ for name, page in (
+ ('link only', self.continue_setup_page.replace(self.CONTINUE_SETUP_META_REFRESH, '')),
+ ('meta refresh only',
+ self.continue_setup_page.replace(self.CONTINUE_SETUP_LINK_HREF, 'href="#"'))):
+ with self.subTest(name), responses.RequestsMock() as rsps:
+ self.assertNotEqual(page, self.continue_setup_page)
+ rsps.post(self.ORG_NEW, status=302, headers={'Location': self.MANIFEST_PAGE})
+ rsps.get(self.MANIFEST_PAGE, body=self.page)
+ rsps.post(self.CONFIRM, body=page)
+ self.assertEqual(self._create(), CONTINUE_SETUP_CALLBACK)
+
+ @responses.activate
+ def test_different_urls_with_a_code_are_unknown_outcome(self):
+ page = self.continue_setup_page.replace(
+ self.CONTINUE_SETUP_META_REFRESH,
+ self.CONTINUE_SETUP_META_REFRESH.replace('FIXTURE_CODE', 'OTHER_CODE'))
+ self.assertIn('OTHER_CODE', page)
+ self._add_preview()
+ self._add_confirm(body=page)
+ with self.assertRaisesRegex(forms.OutcomeUnknownError,
+ 'links to 2 different URLs with a code, so whether GitHub '
+ 'accepted it is unknown') as ctx:
+ self._create()
+ for code in ('FIXTURE_CODE', 'OTHER_CODE'):
+ self.assertNotIn(code, str(ctx.exception))
+ self.assertNotIn(code, ctx.exception.body_excerpt)
+
+ @responses.activate
+ def test_redirect_link_inside_a_template_is_not_the_callback(self):
+ page = self.continue_setup_page.replace(self.CONTINUE_SETUP_META_REFRESH, '')
+ page = page.replace('', 'this setup page')
+ self._add_preview()
+ self._add_confirm(body=page)
+ with self.assertRaises(forms.OutcomeUnknownError):
+ self._create()
+
+ @responses.activate
+ def test_callback_link_is_returned_despite_visible_errors(self):
+ # The code is the only way to the app's credentials.
+ page = self.continue_setup_page.replace(
+ '