dex-connector-github 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,367 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Authenticated GitHub HTTP client and operation bindings."""
4
+
5
+ import ipaddress
6
+ import json
7
+ import re
8
+ from dataclasses import dataclass, replace
9
+ from datetime import UTC, datetime
10
+ from typing import Any
11
+ from urllib.parse import quote, quote_plus, urlencode, urlsplit
12
+
13
+ import httpx
14
+ from dex_connectors.sdk import Call, CredentialProvider, Failure, FailureKind, QueryAttempt, Receipt
15
+ from dex_connectors.sdk.providerhttp import (
16
+ BodyTooLargeError,
17
+ ProviderTransportError,
18
+ new_provider_http_client,
19
+ parse_retry_after,
20
+ read_bounded_body,
21
+ send_traced,
22
+ )
23
+
24
+ from ._generated import definitions as definitions
25
+ from ._generated.config import Config as Config
26
+ from ._generated.config import Credentials as Credentials
27
+
28
+ _LOGIN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?\Z")
29
+ _REPOSITORY = re.compile(r"[A-Za-z0-9._-]{1,100}\Z")
30
+ _API_VERSION = re.compile(r"\d{4}-\d{2}-\d{2}\Z")
31
+
32
+
33
+ def _is_loopback(host: str | None) -> bool:
34
+ if host is None:
35
+ return False
36
+ if host.lower() == "localhost":
37
+ return True
38
+ try:
39
+ return ipaddress.ip_address(host).is_loopback
40
+ except ValueError:
41
+ return False
42
+
43
+
44
+ def _path_escape(value: str) -> str:
45
+ return quote(value, safe="-._~$&+=:@")
46
+
47
+
48
+ def _query(values: dict[str, str]) -> str:
49
+ return urlencode(sorted(values.items()), quote_via=quote_plus)
50
+
51
+
52
+ def _failure(operation: str, kind: FailureKind, message: str) -> Failure:
53
+ return Failure(kind, "github", operation, message)
54
+
55
+
56
+ class _Response:
57
+ def __init__(self, response: httpx.Response, body: bytes) -> None:
58
+ self.status = response.status_code
59
+ self.headers = response.headers
60
+ self.body = body
61
+ self.request_id = ""
62
+ for name in ("X-GitHub-Request-Id", "X-Request-Id"):
63
+ candidate = response.headers.get(name, "").strip()
64
+ if candidate and len(candidate) <= 128 and re.fullmatch(r"[A-Za-z0-9_.:/-]+", candidate):
65
+ self.request_id = candidate
66
+ break
67
+
68
+ def receipt(self, metadata: dict[str, str] | None = None) -> Receipt:
69
+ return Receipt(provider_request_id=self.request_id, metadata=metadata or {})
70
+
71
+
72
+ def _decode(body: bytes, expected: type) -> Any:
73
+ value = json.loads(body)
74
+ if not isinstance(value, expected):
75
+ raise ValueError("GitHub response type differs")
76
+ return value
77
+
78
+
79
+ def _scopes_match(response: _Response) -> bool:
80
+ return {
81
+ scope.strip() for scope in response.headers.get("X-OAuth-Scopes", "").split(",") if scope.strip()
82
+ } == {"read:user", "user:email"}
83
+
84
+
85
+ @dataclass(slots=True, repr=False)
86
+ class _CredentialState:
87
+ value: Credentials
88
+
89
+
90
+ class Client:
91
+ """Execute bounded GitHub queries and own the shared provider and refresh transport."""
92
+
93
+ def __init__(
94
+ self,
95
+ config: Config,
96
+ credentials: CredentialProvider[Credentials],
97
+ http_client: httpx.AsyncClient | None = None,
98
+ now: Any = None,
99
+ ) -> None:
100
+ if config is None or credentials is None:
101
+ raise ValueError("GitHub configuration and credentials are required")
102
+ defaults = Config()
103
+ config = replace(
104
+ config,
105
+ base_url=config.base_url or defaults.base_url,
106
+ api_version=config.api_version or defaults.api_version,
107
+ timeout_seconds=config.timeout_seconds or defaults.timeout_seconds,
108
+ max_response_bytes=config.max_response_bytes or defaults.max_response_bytes,
109
+ default_repository_limit=config.default_repository_limit or defaults.default_repository_limit,
110
+ max_repositories=config.max_repositories or defaults.max_repositories,
111
+ max_pull_request_body_characters=(
112
+ config.max_pull_request_body_characters or defaults.max_pull_request_body_characters
113
+ ),
114
+ max_patch_characters=config.max_patch_characters or defaults.max_patch_characters,
115
+ max_commit_message_characters=(
116
+ config.max_commit_message_characters or defaults.max_commit_message_characters
117
+ ),
118
+ )
119
+ endpoint = urlsplit(config.base_url)
120
+ if (
121
+ not endpoint.scheme
122
+ or not endpoint.hostname
123
+ or (endpoint.scheme != "https" and not _is_loopback(endpoint.hostname))
124
+ ):
125
+ raise ValueError("GitHub base URL must be HTTPS or loopback")
126
+ if (
127
+ endpoint.username is not None
128
+ or endpoint.password is not None
129
+ or endpoint.query
130
+ or endpoint.fragment
131
+ ):
132
+ raise ValueError("GitHub base URL cannot contain user info, query, or fragment")
133
+ if not _API_VERSION.fullmatch(config.api_version):
134
+ raise ValueError("GitHub API version must use YYYY-MM-DD")
135
+ if config.max_repositories > 500 or config.default_repository_limit > config.max_repositories:
136
+ raise ValueError("GitHub repository limits are invalid")
137
+ if any(
138
+ value <= 0
139
+ for value in (
140
+ config.timeout_seconds,
141
+ config.max_response_bytes,
142
+ config.default_repository_limit,
143
+ config.max_repositories,
144
+ config.max_pull_request_body_characters,
145
+ config.max_patch_characters,
146
+ config.max_commit_message_characters,
147
+ )
148
+ ):
149
+ raise ValueError("GitHub configuration limits must be positive")
150
+ self.config = config
151
+ self._credentials = credentials
152
+ self._http_client = http_client or new_provider_http_client(config.timeout_seconds)
153
+ self._base_url = config.base_url.rstrip("/")
154
+ self._now = now or (lambda: datetime.now(UTC))
155
+
156
+ async def aclose(self) -> None:
157
+ """Close the shared HTTP transport after Worker shutdown."""
158
+ await self._http_client.aclose()
159
+
160
+ async def _credential(
161
+ self, call: Call, operation: str, empty: Any
162
+ ) -> tuple[_CredentialState | None, QueryAttempt[Any] | None]:
163
+ try:
164
+ credential = await self._credentials.resolve(call)
165
+ if not isinstance(credential, Credentials) or not credential.access_token.reveal():
166
+ raise ValueError("GitHub access token is required")
167
+ return _CredentialState(credential), None
168
+ except Exception:
169
+ return None, self._branch(
170
+ operation,
171
+ "defect",
172
+ empty,
173
+ FailureKind.AUTHENTICATION,
174
+ "GitHub authorization is unavailable or revoked",
175
+ )
176
+
177
+ async def _get(
178
+ self, call: Call, credential: _CredentialState, path: str, query: dict[str, str] | None = None
179
+ ) -> _Response:
180
+ target = self._base_url + path + (("?" + _query(query)) if query else "")
181
+ for attempt in range(2):
182
+ request = self._http_client.build_request(
183
+ "GET",
184
+ target,
185
+ headers={
186
+ "Accept": "application/vnd.github+json",
187
+ "Authorization": "Bearer " + credential.value.access_token.reveal(),
188
+ "User-Agent": "superdurable-dex-github-connector/0.1",
189
+ "X-GitHub-Api-Version": self.config.api_version,
190
+ },
191
+ timeout=self.config.timeout_seconds,
192
+ )
193
+ response, _ = await send_traced(self._http_client, request)
194
+ try:
195
+ body = await read_bounded_body(response, self.config.max_response_bytes)
196
+ except BodyTooLargeError:
197
+ raise _Oversized(_Response(response, b"")) from None
198
+ result = _Response(response, body)
199
+ if (
200
+ response.status_code != 401
201
+ or attempt == 1
202
+ or not hasattr(self._credentials, "resolve_after_rejection")
203
+ ):
204
+ return result
205
+ try:
206
+ replacement = await self._credentials.resolve_after_rejection(call)
207
+ except Exception:
208
+ return result
209
+ if not isinstance(replacement, Credentials) or not replacement.access_token.reveal():
210
+ return result
211
+ credential.value = replacement
212
+ raise AssertionError("request attempt exhausted")
213
+
214
+ def _branch(
215
+ self,
216
+ operation: str,
217
+ branch: str,
218
+ empty: Any,
219
+ kind: FailureKind,
220
+ message: str,
221
+ receipt: Receipt | None = None,
222
+ ) -> QueryAttempt[Any]:
223
+ return QueryAttempt.branch_result(
224
+ branch, empty, receipt or Receipt(), _failure(operation, kind, message)
225
+ )
226
+
227
+ def _classify(self, operation: str, response: _Response, empty: Any) -> QueryAttempt[Any] | None:
228
+ status = response.status
229
+ if 200 <= status < 300:
230
+ return None
231
+ if status == 429 or (
232
+ status == 403
233
+ and (
234
+ response.headers.get("Retry-After")
235
+ or response.headers.get("X-RateLimit-Remaining") == "0"
236
+ or self._rate_limit_message(response.body)
237
+ )
238
+ ):
239
+ delay = 60.0
240
+ retry_after = response.headers.get("Retry-After", "")
241
+ if retry_after.isascii() and retry_after.isdecimal() and int(retry_after) > 0:
242
+ delay = parse_retry_after(retry_after, self._now())
243
+ elif response.headers.get("X-RateLimit-Remaining") == "0":
244
+ reset = response.headers.get("X-RateLimit-Reset", "")
245
+ if reset.isdecimal():
246
+ delay = max(0.0, int(reset) - self._now().timestamp()) or 60.0
247
+ return QueryAttempt.retry(
248
+ _failure(operation, FailureKind.RATE_LIMIT, "GitHub rate limit was reached"), delay
249
+ )
250
+ cases = {
251
+ 401: (
252
+ "authorizationRevoked",
253
+ FailureKind.AUTHENTICATION,
254
+ "GitHub authorization is invalid or revoked",
255
+ ),
256
+ 403: (
257
+ "insufficientScope",
258
+ FailureKind.AUTHORIZATION,
259
+ "GitHub authorization is forbidden or lacks scope",
260
+ ),
261
+ 404: ("notFound", FailureKind.NOT_FOUND, "GitHub resource was not found"),
262
+ }
263
+ if status in cases:
264
+ branch, kind, message = cases[status]
265
+ return self._branch(operation, branch, empty, kind, message, response.receipt())
266
+ if status >= 500:
267
+ return QueryAttempt.retry(_failure(operation, FailureKind.AVAILABILITY, "GitHub is unavailable"))
268
+ return self._branch(
269
+ operation,
270
+ "providerRejected",
271
+ empty,
272
+ FailureKind.PROVIDER_REJECTION,
273
+ "GitHub rejected the request",
274
+ response.receipt(),
275
+ )
276
+
277
+ @staticmethod
278
+ def _rate_limit_message(body: bytes) -> bool:
279
+ try:
280
+ value = _decode(body, dict)
281
+ return isinstance(value.get("message"), str) and "rate limit" in value["message"].lower()
282
+ except (ValueError, json.JSONDecodeError):
283
+ return False
284
+
285
+ async def _request(
286
+ self,
287
+ call: Call,
288
+ operation: str,
289
+ credential: _CredentialState,
290
+ path: str,
291
+ query: dict[str, str],
292
+ empty: Any,
293
+ oversized_message: str,
294
+ ) -> tuple[_Response | None, QueryAttempt[Any] | None]:
295
+ try:
296
+ response = await self._get(call, credential, path, query)
297
+ except _Oversized as error:
298
+ return None, self._branch(
299
+ operation,
300
+ "invalidResponse",
301
+ empty,
302
+ FailureKind.RESPONSE_TOO_LARGE,
303
+ oversized_message,
304
+ error.response.receipt(),
305
+ )
306
+ except (ProviderTransportError, httpx.HTTPError, ValueError):
307
+ return None, QueryAttempt.retry(
308
+ _failure(operation, FailureKind.AVAILABILITY, "GitHub is unavailable")
309
+ )
310
+ classified = (
311
+ None
312
+ if operation == "listCommits" and response.status == 409
313
+ else self._classify(operation, response, empty)
314
+ )
315
+ if classified is not None:
316
+ return response, classified
317
+ if not _scopes_match(response):
318
+ return response, self._branch(
319
+ operation,
320
+ "insufficientScope",
321
+ empty,
322
+ FailureKind.AUTHORIZATION,
323
+ "GitHub OAuth grant does not match required scopes",
324
+ response.receipt(),
325
+ )
326
+ return response, None
327
+
328
+ def get_authenticated_profile(self) -> Any:
329
+ """Return the authenticated profile Query."""
330
+ from .operations import GetAuthenticatedProfileOperation
331
+
332
+ return GetAuthenticatedProfileOperation(self)
333
+
334
+ def list_public_repositories(self) -> Any:
335
+ """Return the public repositories Query."""
336
+ from .operations import ListPublicRepositoriesOperation
337
+
338
+ return ListPublicRepositoriesOperation(self)
339
+
340
+ def list_merged_pull_requests(self) -> Any:
341
+ """Return the merged pull requests Query."""
342
+ from .operations import ListMergedPullRequestsOperation
343
+
344
+ return ListMergedPullRequestsOperation(self)
345
+
346
+ def list_pull_request_files(self) -> Any:
347
+ """Return the changed files Query."""
348
+ from .operations import ListPullRequestFilesOperation
349
+
350
+ return ListPullRequestFilesOperation(self)
351
+
352
+ def list_releases(self) -> Any:
353
+ """Return the releases Query."""
354
+ from .operations import ListReleasesOperation
355
+
356
+ return ListReleasesOperation(self)
357
+
358
+ def list_commits(self) -> Any:
359
+ """Return the commits Query."""
360
+ from .operations import ListCommitsOperation
361
+
362
+ return ListCommitsOperation(self)
363
+
364
+
365
+ class _Oversized(Exception):
366
+ def __init__(self, response: _Response) -> None:
367
+ self.response = response
@@ -0,0 +1,5 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """GitHub project connection bindings and OAuth credential source."""
4
+
5
+ from ._generated.connection import * # noqa: F403
@@ -0,0 +1,304 @@
1
+ {
2
+ "connectorId": "github",
3
+ "releaseTag": "connectors/github/go/v0.24.0",
4
+ "package": {
5
+ "ecosystem": "pypi",
6
+ "name": "dex-connector-github",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "new_get_authenticated_profile_step",
12
+ "kind": "query",
13
+ "operationId": "getAuthenticatedProfile",
14
+ "fields": {
15
+ "stepType": "step_type",
16
+ "annotations": "annotations",
17
+ "connectionName": "connection_name",
18
+ "resultAttribute": "result_attribute"
19
+ },
20
+ "branches": [
21
+ {
22
+ "id": "profileLoaded",
23
+ "field": "profile_loaded",
24
+ "optional": false
25
+ },
26
+ {
27
+ "id": "verifiedEmailRequired",
28
+ "field": "verified_email_required",
29
+ "optional": true
30
+ },
31
+ {
32
+ "id": "insufficientScope",
33
+ "field": "insufficient_scope",
34
+ "optional": true
35
+ },
36
+ {
37
+ "id": "authorizationRevoked",
38
+ "field": "authorization_revoked",
39
+ "optional": true
40
+ },
41
+ {
42
+ "id": "notFound",
43
+ "field": "not_found",
44
+ "optional": true
45
+ },
46
+ {
47
+ "id": "providerRejected",
48
+ "field": "provider_rejected",
49
+ "optional": true
50
+ },
51
+ {
52
+ "id": "invalidResponse",
53
+ "field": "invalid_response",
54
+ "optional": true
55
+ },
56
+ {
57
+ "id": "defect",
58
+ "field": "defect",
59
+ "optional": true
60
+ }
61
+ ]
62
+ },
63
+ {
64
+ "name": "new_list_public_repositories_step",
65
+ "kind": "query",
66
+ "operationId": "listPublicRepositories",
67
+ "fields": {
68
+ "stepType": "step_type",
69
+ "annotations": "annotations",
70
+ "connectionName": "connection_name",
71
+ "resultAttribute": "result_attribute"
72
+ },
73
+ "branches": [
74
+ {
75
+ "id": "repositoriesLoaded",
76
+ "field": "repositories_loaded",
77
+ "optional": false
78
+ },
79
+ {
80
+ "id": "insufficientScope",
81
+ "field": "insufficient_scope",
82
+ "optional": true
83
+ },
84
+ {
85
+ "id": "authorizationRevoked",
86
+ "field": "authorization_revoked",
87
+ "optional": true
88
+ },
89
+ {
90
+ "id": "notFound",
91
+ "field": "not_found",
92
+ "optional": true
93
+ },
94
+ {
95
+ "id": "providerRejected",
96
+ "field": "provider_rejected",
97
+ "optional": true
98
+ },
99
+ {
100
+ "id": "invalidResponse",
101
+ "field": "invalid_response",
102
+ "optional": true
103
+ },
104
+ {
105
+ "id": "defect",
106
+ "field": "defect",
107
+ "optional": true
108
+ }
109
+ ]
110
+ },
111
+ {
112
+ "name": "new_list_merged_pull_requests_step",
113
+ "kind": "query",
114
+ "operationId": "listMergedPullRequests",
115
+ "fields": {
116
+ "stepType": "step_type",
117
+ "annotations": "annotations",
118
+ "connectionName": "connection_name",
119
+ "resultAttribute": "result_attribute"
120
+ },
121
+ "branches": [
122
+ {
123
+ "id": "listed",
124
+ "field": "listed",
125
+ "optional": false
126
+ },
127
+ {
128
+ "id": "insufficientScope",
129
+ "field": "insufficient_scope",
130
+ "optional": true
131
+ },
132
+ {
133
+ "id": "authorizationRevoked",
134
+ "field": "authorization_revoked",
135
+ "optional": true
136
+ },
137
+ {
138
+ "id": "notFound",
139
+ "field": "not_found",
140
+ "optional": true
141
+ },
142
+ {
143
+ "id": "providerRejected",
144
+ "field": "provider_rejected",
145
+ "optional": true
146
+ },
147
+ {
148
+ "id": "invalidResponse",
149
+ "field": "invalid_response",
150
+ "optional": true
151
+ },
152
+ {
153
+ "id": "defect",
154
+ "field": "defect",
155
+ "optional": true
156
+ }
157
+ ]
158
+ },
159
+ {
160
+ "name": "new_list_pull_request_files_step",
161
+ "kind": "query",
162
+ "operationId": "listPullRequestFiles",
163
+ "fields": {
164
+ "stepType": "step_type",
165
+ "annotations": "annotations",
166
+ "connectionName": "connection_name",
167
+ "resultAttribute": "result_attribute"
168
+ },
169
+ "branches": [
170
+ {
171
+ "id": "listed",
172
+ "field": "listed",
173
+ "optional": false
174
+ },
175
+ {
176
+ "id": "insufficientScope",
177
+ "field": "insufficient_scope",
178
+ "optional": true
179
+ },
180
+ {
181
+ "id": "authorizationRevoked",
182
+ "field": "authorization_revoked",
183
+ "optional": true
184
+ },
185
+ {
186
+ "id": "notFound",
187
+ "field": "not_found",
188
+ "optional": true
189
+ },
190
+ {
191
+ "id": "providerRejected",
192
+ "field": "provider_rejected",
193
+ "optional": true
194
+ },
195
+ {
196
+ "id": "invalidResponse",
197
+ "field": "invalid_response",
198
+ "optional": true
199
+ },
200
+ {
201
+ "id": "defect",
202
+ "field": "defect",
203
+ "optional": true
204
+ }
205
+ ]
206
+ },
207
+ {
208
+ "name": "new_list_releases_step",
209
+ "kind": "query",
210
+ "operationId": "listReleases",
211
+ "fields": {
212
+ "stepType": "step_type",
213
+ "annotations": "annotations",
214
+ "connectionName": "connection_name",
215
+ "resultAttribute": "result_attribute"
216
+ },
217
+ "branches": [
218
+ {
219
+ "id": "listed",
220
+ "field": "listed",
221
+ "optional": false
222
+ },
223
+ {
224
+ "id": "insufficientScope",
225
+ "field": "insufficient_scope",
226
+ "optional": true
227
+ },
228
+ {
229
+ "id": "authorizationRevoked",
230
+ "field": "authorization_revoked",
231
+ "optional": true
232
+ },
233
+ {
234
+ "id": "notFound",
235
+ "field": "not_found",
236
+ "optional": true
237
+ },
238
+ {
239
+ "id": "providerRejected",
240
+ "field": "provider_rejected",
241
+ "optional": true
242
+ },
243
+ {
244
+ "id": "invalidResponse",
245
+ "field": "invalid_response",
246
+ "optional": true
247
+ },
248
+ {
249
+ "id": "defect",
250
+ "field": "defect",
251
+ "optional": true
252
+ }
253
+ ]
254
+ },
255
+ {
256
+ "name": "new_list_commits_step",
257
+ "kind": "query",
258
+ "operationId": "listCommits",
259
+ "fields": {
260
+ "stepType": "step_type",
261
+ "annotations": "annotations",
262
+ "connectionName": "connection_name",
263
+ "resultAttribute": "result_attribute"
264
+ },
265
+ "branches": [
266
+ {
267
+ "id": "listed",
268
+ "field": "listed",
269
+ "optional": false
270
+ },
271
+ {
272
+ "id": "insufficientScope",
273
+ "field": "insufficient_scope",
274
+ "optional": true
275
+ },
276
+ {
277
+ "id": "authorizationRevoked",
278
+ "field": "authorization_revoked",
279
+ "optional": true
280
+ },
281
+ {
282
+ "id": "notFound",
283
+ "field": "not_found",
284
+ "optional": true
285
+ },
286
+ {
287
+ "id": "providerRejected",
288
+ "field": "provider_rejected",
289
+ "optional": true
290
+ },
291
+ {
292
+ "id": "invalidResponse",
293
+ "field": "invalid_response",
294
+ "optional": true
295
+ },
296
+ {
297
+ "id": "defect",
298
+ "field": "defect",
299
+ "optional": true
300
+ }
301
+ ]
302
+ }
303
+ ]
304
+ }
@@ -0,0 +1,6 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa: F403
4
+
5
+ from .._generated.mock import *
6
+ from .._generated.mock import __all__ as __all__
@@ -0,0 +1,5 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """GitHub operation input and output models."""
4
+
5
+ from ._generated.models import * # noqa: F403