|
| 1 | +import datetime |
| 2 | +import logging |
| 3 | +from enum import StrEnum |
| 4 | +from typing import TypeAlias |
| 5 | + |
| 6 | +import requests |
| 7 | +from rest_framework import status |
| 8 | + |
| 9 | +from sentry import options |
| 10 | +from sentry.api.exceptions import SentryAPIException |
| 11 | +from sentry.utils import jwt |
| 12 | + |
| 13 | +GitProviderId: TypeAlias = str |
| 14 | + |
| 15 | + |
| 16 | +class GitProvider(StrEnum): |
| 17 | + """ |
| 18 | + Enum representing the Git provider that hosts the user/org that a |
| 19 | + `CodecovApiClient` instance is acting on behalf of. |
| 20 | +
|
| 21 | + Codecov doesn't require this to be GitHub, but that's all that's implemented |
| 22 | + for now. |
| 23 | + """ |
| 24 | + GitHub = "github" |
| 25 | + |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | +TIMEOUT_SECONDS = 10 |
| 30 | + |
| 31 | + |
| 32 | +class ConfigurationError(SentryAPIException): |
| 33 | + status_code = status.HTTP_500_INTERNAL_SERVER_ERROR |
| 34 | + code = "configuration-error" |
| 35 | + |
| 36 | + |
| 37 | +class CodecovApiClient: |
| 38 | + """ |
| 39 | + Thin client for making JWT-authenticated requests to the Codecov API. |
| 40 | +
|
| 41 | + For each request, Sentry creates and signs (HS256) a JWT with a key shared |
| 42 | + with Codecov. This JWT contains information that Codecov needs to service |
| 43 | + the request. |
| 44 | + """ |
| 45 | + |
| 46 | + def _create_jwt(self): |
| 47 | + now = int(datetime.datetime.now(datetime.UTC).timestamp()) |
| 48 | + exp = now + 300 # 5 minutes |
| 49 | + claims = { |
| 50 | + "iss": "https://sentry.io", |
| 51 | + "iat": now, |
| 52 | + "exp": exp, |
| 53 | + } |
| 54 | + claims.update(self.custom_claims) |
| 55 | + |
| 56 | + return jwt.encode(claims, self.signing_secret, algorithm="HS256") |
| 57 | + |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + git_provider_user: GitProviderId, |
| 61 | + git_provider: GitProvider = GitProvider.GitHub, |
| 62 | + ): |
| 63 | + """ |
| 64 | + Creates a `CodecovApiClient`. |
| 65 | +
|
| 66 | + :param git_provider_user: The ID of the current Sentry user's linked git |
| 67 | + provider account, according to the git provider. |
| 68 | + :param git_provider: The git provider that the above user's account is |
| 69 | + hosted on. |
| 70 | + """ |
| 71 | + |
| 72 | + if not (base_url := options.get("codecov.base-url")): |
| 73 | + raise ConfigurationError() |
| 74 | + |
| 75 | + if not (signing_secret := options.get("codecov.api-bridge-signing-secret")): |
| 76 | + raise ConfigurationError() |
| 77 | + |
| 78 | + self.base_url = base_url |
| 79 | + self.signing_secret = signing_secret |
| 80 | + self.custom_claims = { |
| 81 | + "g_u": git_provider_user, |
| 82 | + "g_p": git_provider, |
| 83 | + } |
| 84 | + |
| 85 | + def get(self, endpoint: str, params=None, headers=None) -> requests.Response | None: |
| 86 | + """ |
| 87 | + Makes a GET request to the specified endpoint of the configured Codecov |
| 88 | + API host with the provided params and headers. |
| 89 | +
|
| 90 | + :param endpoint: The endpoint to request, without the host portion. For |
| 91 | + examples: `/api/v2/gh/getsentry/users` or `/graphql` |
| 92 | + :param params: Dictionary of query params. |
| 93 | + :param headers: Dictionary of request headers. |
| 94 | + """ |
| 95 | + headers = headers or {} |
| 96 | + token = self._create_jwt() |
| 97 | + headers.update(jwt.authorization_header(token)) |
| 98 | + |
| 99 | + url = f"{self.base_url}{endpoint}" |
| 100 | + try: |
| 101 | + response = requests.get(url, params=params, headers=headers, timeout=TIMEOUT_SECONDS) |
| 102 | + except Exception: |
| 103 | + logger.exception("Error when making GET request") |
| 104 | + return None |
| 105 | + |
| 106 | + return response |
| 107 | + |
| 108 | + def post(self, endpoint: str, data=None, headers=None) -> requests.Response | None: |
| 109 | + """ |
| 110 | + Makes a POST request to the specified endpoint of the configured Codecov |
| 111 | + API host with the provided data and headers. |
| 112 | +
|
| 113 | + :param endpoint: The endpoint to request, without the host portion. For |
| 114 | + examples: `/api/v2/gh/getsentry/users` or `/graphql` |
| 115 | + :param data: Dictionary of form data. |
| 116 | + :param headers: Dictionary of request headers. |
| 117 | + """ |
| 118 | + headers = headers or {} |
| 119 | + token = self._create_jwt() |
| 120 | + headers.update(jwt.authorization_header(token)) |
| 121 | + url = f"{self.base_url}{endpoint}" |
| 122 | + try: |
| 123 | + response = requests.post(url, data=data, headers=headers, timeout=TIMEOUT_SECONDS) |
| 124 | + except Exception: |
| 125 | + logger.exception("Error when making POST request") |
| 126 | + return None |
| 127 | + |
| 128 | + return response |
0 commit comments