|
| 1 | +import time |
| 2 | + |
| 3 | +import jwt |
| 4 | +import requests |
| 5 | +from buildbot.interfaces import IRenderable |
| 6 | +from buildbot.reporters.github import GitHubStatusPush |
| 7 | +from twisted.internet import defer, threads |
| 8 | +from zope.interface import implementer |
| 9 | + |
| 10 | +__all__ = ["AppInstallationToken", "GitHubAppCheckPush"] |
| 11 | + |
| 12 | + |
| 13 | +@implementer(IRenderable) |
| 14 | +class AppInstallationToken: |
| 15 | + """Renders to a GitHub App installation access token, refreshed as needed. Pass an instance |
| 16 | + as GitHubAppCheckPush's `token=`; buildbot re-renders it on every request, so refreshes |
| 17 | + happen transparently. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, client_id, private_key, installation_id): |
| 21 | + self._client_id = client_id |
| 22 | + self._private_key = private_key |
| 23 | + self._installation_id = installation_id |
| 24 | + self._token = None |
| 25 | + self._expires = 0 |
| 26 | + self._lock = defer.DeferredLock() |
| 27 | + |
| 28 | + async def getRenderingFor(self, _iprops): |
| 29 | + if time.time() > self._expires: |
| 30 | + async with self._lock: |
| 31 | + if time.time() > self._expires: |
| 32 | + self._token = await threads.deferToThread(self._fetch) |
| 33 | + self._expires = time.time() + 55 * 60 |
| 34 | + return self._token |
| 35 | + |
| 36 | + def _fetch(self): |
| 37 | + now = int(time.time()) |
| 38 | + app_jwt = jwt.encode( |
| 39 | + {"iat": now - 60, "exp": now + 570, "iss": self._client_id}, |
| 40 | + self._private_key, |
| 41 | + algorithm="RS256", |
| 42 | + ) |
| 43 | + resp = requests.post( |
| 44 | + f"https://api.github.com/app/installations/{self._installation_id}/access_tokens", |
| 45 | + headers={"Authorization": f"Bearer {app_jwt}", "Accept": "application/vnd.github+json"}, |
| 46 | + timeout=10, |
| 47 | + ) |
| 48 | + resp.raise_for_status() |
| 49 | + return resp.json()["token"] |
| 50 | + |
| 51 | + |
| 52 | +class GitHubAppCheckPush(GitHubStatusPush): |
| 53 | + """Like GitHubStatusPush, but reports through the Checks API instead of the legacy Statuses |
| 54 | + API, so a build in progress shows GitHub's spinner instead of a static pending dot. Requires |
| 55 | + a GitHub App: pass an AppInstallationToken as `token=` (the Statuses API's PAT-based token |
| 56 | + doesn't work here; only the Checks API used by this class requires App auth). |
| 57 | + """ |
| 58 | + |
| 59 | + @defer.inlineCallbacks |
| 60 | + def _get_auth_header(self, props): |
| 61 | + token = yield props.render(self.token) |
| 62 | + return {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"} |
| 63 | + |
| 64 | + @defer.inlineCallbacks |
| 65 | + def createStatus( |
| 66 | + self, repo_user, repo_name, sha, state, props, target_url=None, context=None, issue=None, description=None |
| 67 | + ): |
| 68 | + headers = yield self._get_auth_header(props) |
| 69 | + base = f"/repos/{repo_user}/{repo_name}/check-runs" |
| 70 | + output = {"title": context, "summary": description or ""} |
| 71 | + |
| 72 | + if state == "pending": |
| 73 | + payload = { |
| 74 | + "name": context, |
| 75 | + "head_sha": sha, |
| 76 | + "status": "in_progress", |
| 77 | + "details_url": target_url, |
| 78 | + "output": output, |
| 79 | + "external_id": issue, |
| 80 | + } |
| 81 | + return (yield self._http.post(base, json=payload, headers=headers)) |
| 82 | + |
| 83 | + # The check run's id isn't threaded through from the "pending" call above, so look it up |
| 84 | + # by name instead of tracking build-run state; one extra GET, but no persisted state. |
| 85 | + resp = yield self._http.get( |
| 86 | + f"/repos/{repo_user}/{repo_name}/commits/{sha}/check-runs", |
| 87 | + params={"check_name": context}, |
| 88 | + headers=headers, |
| 89 | + ) |
| 90 | + runs = (yield resp.json())["check_runs"] |
| 91 | + if not runs: |
| 92 | + return None |
| 93 | + |
| 94 | + # GitHubStatusPush.sendMessage() already collapsed several build results into "error"; |
| 95 | + # both "failure" and "error" map to the same GitHub conclusion. |
| 96 | + conclusion = "success" if state == "success" else "failure" |
| 97 | + payload = { |
| 98 | + "status": "completed", |
| 99 | + "conclusion": conclusion, |
| 100 | + "details_url": target_url, |
| 101 | + "output": output, |
| 102 | + } |
| 103 | + # HTTPSession has no patch() wrapper (only get/put/post/delete); the Checks API update |
| 104 | + # endpoint is PATCH-only, so fall through to the generic dispatcher it's built on. |
| 105 | + return ( |
| 106 | + yield self._http.http._do_request( |
| 107 | + self._http, "patch", f"{base}/{runs[0]['id']}", json=payload, headers=headers |
| 108 | + ) |
| 109 | + ) |
0 commit comments