PyGithub-asyncio 3.0.0b1__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.
Files changed (188) hide show
  1. githubasyncio/AccessToken.py +159 -0
  2. githubasyncio/AdvisoryBase.py +163 -0
  3. githubasyncio/AdvisoryCredit.py +131 -0
  4. githubasyncio/AdvisoryCreditDetailed.py +110 -0
  5. githubasyncio/AdvisoryVulnerability.py +191 -0
  6. githubasyncio/AdvisoryVulnerabilityPackage.py +93 -0
  7. githubasyncio/AppAuthentication.py +58 -0
  8. githubasyncio/ApplicationOAuth.py +200 -0
  9. githubasyncio/Artifact.py +183 -0
  10. githubasyncio/Auth.py +560 -0
  11. githubasyncio/AuthenticatedUser.py +1251 -0
  12. githubasyncio/Authorization.py +192 -0
  13. githubasyncio/AuthorizationApplication.py +73 -0
  14. githubasyncio/Autolink.py +104 -0
  15. githubasyncio/Branch.py +689 -0
  16. githubasyncio/BranchProtection.py +224 -0
  17. githubasyncio/CVSS.py +83 -0
  18. githubasyncio/CWE.py +75 -0
  19. githubasyncio/CheckRun.py +315 -0
  20. githubasyncio/CheckRunAnnotation.py +134 -0
  21. githubasyncio/CheckRunOutput.py +108 -0
  22. githubasyncio/CheckSuite.py +319 -0
  23. githubasyncio/Clones.py +97 -0
  24. githubasyncio/CodeScanAlert.py +215 -0
  25. githubasyncio/CodeScanAlertInstance.py +134 -0
  26. githubasyncio/CodeScanAlertInstanceLocation.py +102 -0
  27. githubasyncio/CodeScanRule.py +134 -0
  28. githubasyncio/CodeScanTool.py +94 -0
  29. githubasyncio/CodeSecurityConfig.py +301 -0
  30. githubasyncio/CodeSecurityConfigRepository.py +70 -0
  31. githubasyncio/Commit.py +442 -0
  32. githubasyncio/CommitCombinedStatus.py +126 -0
  33. githubasyncio/CommitComment.py +270 -0
  34. githubasyncio/CommitStats.py +78 -0
  35. githubasyncio/CommitStatus.py +169 -0
  36. githubasyncio/Comparison.py +219 -0
  37. githubasyncio/Consts.py +197 -0
  38. githubasyncio/ContentFile.py +304 -0
  39. githubasyncio/Copilot.py +97 -0
  40. githubasyncio/CopilotSeat.py +132 -0
  41. githubasyncio/DefaultCodeSecurityConfig.py +93 -0
  42. githubasyncio/DependabotAlert.py +184 -0
  43. githubasyncio/DependabotAlertAdvisory.py +82 -0
  44. githubasyncio/DependabotAlertDependency.py +100 -0
  45. githubasyncio/DependabotAlertVulnerability.py +85 -0
  46. githubasyncio/Deployment.py +314 -0
  47. githubasyncio/DeploymentBranchPolicy.py +102 -0
  48. githubasyncio/DeploymentStatus.py +201 -0
  49. githubasyncio/DiscussionBase.py +140 -0
  50. githubasyncio/DiscussionCommentBase.py +140 -0
  51. githubasyncio/Download.py +256 -0
  52. githubasyncio/Enterprise.py +175 -0
  53. githubasyncio/EnterpriseConsumedLicenses.py +138 -0
  54. githubasyncio/Environment.py +354 -0
  55. githubasyncio/EnvironmentDeploymentBranchPolicy.py +87 -0
  56. githubasyncio/EnvironmentProtectionRule.py +117 -0
  57. githubasyncio/EnvironmentProtectionRuleReviewer.py +110 -0
  58. githubasyncio/Event.py +134 -0
  59. githubasyncio/File.py +142 -0
  60. githubasyncio/GeneratedReleaseNotes.py +68 -0
  61. githubasyncio/Gist.py +373 -0
  62. githubasyncio/GistComment.py +162 -0
  63. githubasyncio/GistFile.py +106 -0
  64. githubasyncio/GistHistoryState.py +245 -0
  65. githubasyncio/GitAuthor.py +94 -0
  66. githubasyncio/GitBlob.py +123 -0
  67. githubasyncio/GitCommit.py +208 -0
  68. githubasyncio/GitCommitVerification.py +103 -0
  69. githubasyncio/GitObject.py +84 -0
  70. githubasyncio/GitRef.py +122 -0
  71. githubasyncio/GitRelease.py +476 -0
  72. githubasyncio/GitReleaseAsset.py +232 -0
  73. githubasyncio/GitTag.py +143 -0
  74. githubasyncio/GitTree.py +113 -0
  75. githubasyncio/GitTreeElement.py +104 -0
  76. githubasyncio/GithubApp.py +236 -0
  77. githubasyncio/GithubException.py +226 -0
  78. githubasyncio/GithubIntegration.py +365 -0
  79. githubasyncio/GithubObject.py +910 -0
  80. githubasyncio/GithubRetry.py +253 -0
  81. githubasyncio/GitignoreTemplate.py +88 -0
  82. githubasyncio/GlobalAdvisory.py +141 -0
  83. githubasyncio/Hook.py +238 -0
  84. githubasyncio/HookDelivery.py +243 -0
  85. githubasyncio/HookDescription.py +85 -0
  86. githubasyncio/HookResponse.py +83 -0
  87. githubasyncio/InputFileContent.py +63 -0
  88. githubasyncio/InputGitAuthor.py +71 -0
  89. githubasyncio/InputGitTreeElement.py +79 -0
  90. githubasyncio/Installation.py +298 -0
  91. githubasyncio/InstallationAuthorization.py +138 -0
  92. githubasyncio/Invitation.py +171 -0
  93. githubasyncio/Issue.py +955 -0
  94. githubasyncio/IssueComment.py +309 -0
  95. githubasyncio/IssueDependenciesSummary.py +77 -0
  96. githubasyncio/IssueEvent.py +296 -0
  97. githubasyncio/IssuePullRequest.py +97 -0
  98. githubasyncio/IssueType.py +123 -0
  99. githubasyncio/Label.py +186 -0
  100. githubasyncio/License.py +169 -0
  101. githubasyncio/MainClass.py +1142 -0
  102. githubasyncio/Membership.py +154 -0
  103. githubasyncio/MergedUpstream.py +71 -0
  104. githubasyncio/Migration.py +281 -0
  105. githubasyncio/Milestone.py +255 -0
  106. githubasyncio/NamedEnterpriseUser.py +207 -0
  107. githubasyncio/NamedUser.py +841 -0
  108. githubasyncio/Notification.py +182 -0
  109. githubasyncio/NotificationSubject.py +96 -0
  110. githubasyncio/Organization.py +2462 -0
  111. githubasyncio/OrganizationCodeScanAlert.py +65 -0
  112. githubasyncio/OrganizationCustomProperty.py +215 -0
  113. githubasyncio/OrganizationDependabotAlert.py +75 -0
  114. githubasyncio/OrganizationSecret.py +191 -0
  115. githubasyncio/OrganizationSecretScanAlert.py +112 -0
  116. githubasyncio/OrganizationVariable.py +141 -0
  117. githubasyncio/PaginatedList.py +652 -0
  118. githubasyncio/Path.py +102 -0
  119. githubasyncio/Permissions.py +113 -0
  120. githubasyncio/Plan.py +108 -0
  121. githubasyncio/Project.py +286 -0
  122. githubasyncio/ProjectCard.py +257 -0
  123. githubasyncio/ProjectColumn.py +227 -0
  124. githubasyncio/PublicKey.py +138 -0
  125. githubasyncio/PullRequest.py +1202 -0
  126. githubasyncio/PullRequestComment.py +401 -0
  127. githubasyncio/PullRequestMergeStatus.py +89 -0
  128. githubasyncio/PullRequestPart.py +110 -0
  129. githubasyncio/PullRequestReview.py +214 -0
  130. githubasyncio/Rate.py +123 -0
  131. githubasyncio/RateLimit.py +210 -0
  132. githubasyncio/RateLimitOverview.py +104 -0
  133. githubasyncio/Reaction.py +128 -0
  134. githubasyncio/Referrer.py +94 -0
  135. githubasyncio/RepoCodeSecurityConfig.py +93 -0
  136. githubasyncio/Repository.py +5211 -0
  137. githubasyncio/RepositoryAdvisory.py +431 -0
  138. githubasyncio/RepositoryDiscussion.py +221 -0
  139. githubasyncio/RepositoryDiscussionCategory.py +150 -0
  140. githubasyncio/RepositoryDiscussionComment.py +159 -0
  141. githubasyncio/RepositoryKey.py +166 -0
  142. githubasyncio/RepositoryPreferences.py +82 -0
  143. githubasyncio/RepositoryRulesetBypassActor.py +75 -0
  144. githubasyncio/Requester.py +1518 -0
  145. githubasyncio/RequiredPullRequestReviews.py +269 -0
  146. githubasyncio/RequiredStatusChecks.py +153 -0
  147. githubasyncio/Rule.py +134 -0
  148. githubasyncio/Ruleset.py +292 -0
  149. githubasyncio/Secret.py +139 -0
  150. githubasyncio/SecretScanAlert.py +317 -0
  151. githubasyncio/SecretScanAlertInstance.py +128 -0
  152. githubasyncio/SecurityAndAnalysis.py +188 -0
  153. githubasyncio/SecurityAndAnalysisFeature.py +79 -0
  154. githubasyncio/SelfHostedActionsRunner.py +129 -0
  155. githubasyncio/SelfHostedActionsRunnerApplication.py +92 -0
  156. githubasyncio/SelfHostedActionsRunnerJitConfig.py +74 -0
  157. githubasyncio/SelfHostedActionsRunnerToken.py +118 -0
  158. githubasyncio/SourceImport.py +260 -0
  159. githubasyncio/Stargazer.py +88 -0
  160. githubasyncio/StatsCodeFrequency.py +81 -0
  161. githubasyncio/StatsCommitActivity.py +86 -0
  162. githubasyncio/StatsContributor.py +138 -0
  163. githubasyncio/StatsParticipation.py +78 -0
  164. githubasyncio/StatsPunchCard.py +76 -0
  165. githubasyncio/SubIssueSummary.py +70 -0
  166. githubasyncio/Tag.py +108 -0
  167. githubasyncio/Team.py +618 -0
  168. githubasyncio/TeamDiscussion.py +137 -0
  169. githubasyncio/TimelineEvent.py +164 -0
  170. githubasyncio/TimelineEventSource.py +81 -0
  171. githubasyncio/Topic.py +177 -0
  172. githubasyncio/Traffic.py +95 -0
  173. githubasyncio/UserKey.py +141 -0
  174. githubasyncio/Variable.py +155 -0
  175. githubasyncio/View.py +97 -0
  176. githubasyncio/Workflow.py +335 -0
  177. githubasyncio/WorkflowJob.py +253 -0
  178. githubasyncio/WorkflowRun.py +480 -0
  179. githubasyncio/WorkflowStep.py +118 -0
  180. githubasyncio/__init__.py +38 -0
  181. githubasyncio/compat/__init__.py +52 -0
  182. githubasyncio/requestlib/__init__.py +29 -0
  183. pygithub_asyncio-3.0.0b1.dist-info/METADATA +102 -0
  184. pygithub_asyncio-3.0.0b1.dist-info/RECORD +188 -0
  185. pygithub_asyncio-3.0.0b1.dist-info/WHEEL +5 -0
  186. pygithub_asyncio-3.0.0b1.dist-info/licenses/COPYING +674 -0
  187. pygithub_asyncio-3.0.0b1.dist-info/licenses/COPYING.LESSER +165 -0
  188. pygithub_asyncio-3.0.0b1.dist-info/top_level.txt +1 -0
githubasyncio/Auth.py ADDED
@@ -0,0 +1,560 @@
1
+ # FILE AUTO GENERATED DO NOT TOUCH
2
+ ############################ Copyrights and license ############################
3
+ # #
4
+ # Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
5
+ # Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
6
+ # Copyright 2023 Trim21 <trim21.me@gmail.com> #
7
+ # Copyright 2023 chantra <chantra@users.noreply.github.com> #
8
+ # Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
9
+ # Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
10
+ # Copyright 2024 Jonathan Kliem <jonathan.kliem@gmail.com> #
11
+ # Copyright 2025 Enrico Minack <github@enrico.minack.dev> #
12
+ # Copyright 2025 Soubhik Kumar Mitra <59209034+x612skm@users.noreply.github.com>#
13
+ # Copyright 2026 Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> #
14
+ # #
15
+ # This file is part of PyGithub. #
16
+ # http://pygithub.readthedocs.io/ #
17
+ # #
18
+ # PyGithub is free software: you can redistribute it and/or modify it under #
19
+ # the terms of the GNU Lesser General Public License as published by the Free #
20
+ # Software Foundation, either version 3 of the License, or (at your option) #
21
+ # any later version. #
22
+ # #
23
+ # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
24
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
25
+ # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
26
+ # details. #
27
+ # #
28
+ # You should have received a copy of the GNU Lesser General Public License #
29
+ # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
30
+ # #
31
+ ################################################################################
32
+
33
+ from __future__ import annotations
34
+
35
+ import abc
36
+ import base64
37
+ import inspect
38
+ import time
39
+ from abc import ABC
40
+ from collections.abc import Callable
41
+ from datetime import datetime, timedelta, timezone
42
+ from typing import TYPE_CHECKING
43
+
44
+ import jwt
45
+
46
+ from githubasyncio import Consts
47
+ from githubasyncio.InstallationAuthorization import InstallationAuthorization
48
+ from githubasyncio.Requester import Requester, WithRequester
49
+ from githubasyncio.requestlib import utils
50
+
51
+ if TYPE_CHECKING:
52
+ from githubasyncio.ApplicationOAuth import ApplicationOAuth
53
+ from githubasyncio.GithubIntegration import GithubIntegration
54
+ PrivateKeyGenerator = Callable[[], str | bytes]
55
+ DictSignFunction = Callable[[dict], str | bytes]
56
+
57
+ # For App authentication, time remaining before token expiration to request a new one
58
+ ACCESS_TOKEN_REFRESH_THRESHOLD_SECONDS = 20
59
+ TOKEN_REFRESH_THRESHOLD_TIMEDELTA = timedelta(seconds=ACCESS_TOKEN_REFRESH_THRESHOLD_SECONDS)
60
+
61
+
62
+ # add new implementations of Auth to docs/utilities.rst
63
+ class Auth(abc.ABC):
64
+ """
65
+ This class is the base class of all authentication methods for Requester.
66
+ """
67
+
68
+ @property
69
+ @abc.abstractmethod
70
+ def token_type(self) -> str:
71
+ """
72
+ The type of the auth token as used in the HTTP Authorization header, e.g. Bearer or Basic.
73
+
74
+ :return: token type
75
+
76
+ """
77
+
78
+ @property
79
+ @abc.abstractmethod
80
+ def token(self) -> str:
81
+ """
82
+ The auth token as used in the HTTP Authorization header.
83
+
84
+ :return: token
85
+
86
+ """
87
+
88
+ async def authentication(self, headers: dict) -> None:
89
+ """
90
+ Add authorization to the headers.
91
+ """
92
+ token = self.token
93
+ if inspect.isawaitable(token):
94
+ token = await token
95
+ headers["Authorization"] = f"{self.token_type} {token}"
96
+
97
+ def mask_authentication(self, headers: dict) -> None:
98
+ """
99
+ Mask header, e.g. for logging.
100
+ """
101
+ headers["Authorization"] = self._masked_token
102
+
103
+ @property
104
+ def _masked_token(self) -> str:
105
+ return "(unknown auth removed)"
106
+
107
+
108
+ class HTTPBasicAuth(Auth, abc.ABC):
109
+ @property
110
+ @abc.abstractmethod
111
+ def username(self) -> str:
112
+ """
113
+ The username.
114
+ """
115
+
116
+ @property
117
+ @abc.abstractmethod
118
+ def password(self) -> str:
119
+ """
120
+ The password.
121
+ """
122
+
123
+ @property
124
+ def token_type(self) -> str:
125
+ return "Basic"
126
+
127
+ @property
128
+ def token(self) -> str:
129
+ return base64.b64encode(f"{self.username}:{self.password}".encode()).decode("utf-8").replace("\n", "")
130
+
131
+ @property
132
+ def _masked_token(self) -> str:
133
+ return "Basic (login and password removed)"
134
+
135
+
136
+ class Login(HTTPBasicAuth):
137
+ """
138
+ This class is used to authenticate with login and password.
139
+ """
140
+
141
+ def __init__(self, login: str, password: str):
142
+ assert isinstance(login, str)
143
+ assert len(login) > 0
144
+ assert isinstance(password, str)
145
+ assert len(password) > 0
146
+
147
+ self._login = login
148
+ self._password = password
149
+
150
+ @property
151
+ def login(self) -> str:
152
+ return self._login
153
+
154
+ @property
155
+ def username(self) -> str:
156
+ return self.login
157
+
158
+ @property
159
+ def password(self) -> str:
160
+ return self._password
161
+
162
+
163
+ class Token(Auth):
164
+ """
165
+ This class is used to authenticate with a single constant token.
166
+ """
167
+
168
+ def __init__(self, token: str):
169
+ assert isinstance(token, str)
170
+ assert len(token) > 0
171
+ self._token = token
172
+
173
+ @property
174
+ def token_type(self) -> str:
175
+ return "token"
176
+
177
+ @property
178
+ def token(self) -> str:
179
+ return self._token
180
+
181
+ @property
182
+ def _masked_token(self) -> str:
183
+ return "token (oauth token removed)"
184
+
185
+
186
+ class JWT(Auth, ABC):
187
+ """
188
+ This class is the base class to authenticate with a JSON Web Token (JWT).
189
+
190
+ https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app
191
+
192
+ """
193
+
194
+ @property
195
+ def token_type(self) -> str:
196
+ return "Bearer"
197
+
198
+
199
+ class JwtSigner:
200
+ def __init__(self, private_key_or_func: str | PrivateKeyGenerator, jwt_algorithm: str):
201
+ self._private_key_or_func = private_key_or_func
202
+ self._jwt_algorithm = jwt_algorithm
203
+
204
+ def jwt_sign(self, payload: dict) -> str | bytes:
205
+ if callable(self._private_key_or_func):
206
+ private_key = self._private_key_or_func()
207
+ else:
208
+ private_key = self._private_key_or_func
209
+ return jwt.encode(payload, key=private_key, algorithm=self._jwt_algorithm)
210
+
211
+
212
+ class AppAuth(JWT):
213
+ """
214
+ This class is used to authenticate as a GitHub App.
215
+
216
+ https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app
217
+
218
+ """
219
+
220
+ @staticmethod
221
+ def create_jwt_sign(private_key_or_func: str | PrivateKeyGenerator, jwt_algorithm: str) -> DictSignFunction:
222
+ return JwtSigner(private_key_or_func, jwt_algorithm).jwt_sign
223
+
224
+ # v3: move * above private_key
225
+ def __init__(
226
+ self,
227
+ app_id: int | str,
228
+ private_key: str | PrivateKeyGenerator | None = None,
229
+ *,
230
+ sign_func: DictSignFunction | None = None,
231
+ jwt_expiry: int = Consts.DEFAULT_JWT_EXPIRY,
232
+ jwt_issued_at: int = Consts.DEFAULT_JWT_ISSUED_AT,
233
+ ):
234
+ assert isinstance(app_id, (int, str)), app_id
235
+ if isinstance(app_id, str):
236
+ assert len(app_id) > 0, "app_id must not be empty"
237
+ assert private_key is not None or sign_func is not None, "either private_key or sign_func must be given"
238
+ assert private_key is None or sign_func is None, "private_key or sign_func cannot both be given"
239
+ if private_key is not None:
240
+ assert isinstance(private_key, str) or callable(private_key)
241
+ if isinstance(private_key, str):
242
+ assert len(private_key) > 0, "private_key must not be empty"
243
+ sign_func = AppAuth.create_jwt_sign(private_key, Consts.DEFAULT_JWT_ALGORITHM)
244
+ assert isinstance(jwt_expiry, int), jwt_expiry
245
+ assert Consts.MIN_JWT_EXPIRY <= jwt_expiry <= Consts.MAX_JWT_EXPIRY, jwt_expiry
246
+
247
+ self._app_id = str(app_id)
248
+ self._sign_func = sign_func
249
+ self._jwt_expiry = jwt_expiry
250
+ self._jwt_issued_at = jwt_issued_at
251
+
252
+ @property
253
+ def app_id(self) -> int | str:
254
+ return self._app_id
255
+
256
+ @property
257
+ def token(self) -> str:
258
+ return self.create_jwt()
259
+
260
+ def get_installation_auth(
261
+ self,
262
+ installation_id: int,
263
+ token_permissions: dict[str, str] | None = None,
264
+ requester: Requester | None = None,
265
+ ) -> AppInstallationAuth:
266
+ """
267
+ Creates a Auth.AppInstallationAuth instance for an installation.
268
+
269
+ :param installation_id: installation id
270
+ :param token_permissions: optional permissions
271
+ :param requester: optional requester with app authentication
272
+ :return:
273
+
274
+ """
275
+ return AppInstallationAuth(self, installation_id, token_permissions, requester)
276
+
277
+ def create_jwt(self, expiration: int | None = None) -> str:
278
+ """
279
+ Create a signed JWT
280
+ https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
281
+
282
+ :return string: jwt
283
+ """
284
+ if expiration is not None:
285
+ assert isinstance(expiration, int), expiration
286
+ assert Consts.MIN_JWT_EXPIRY <= expiration <= Consts.MAX_JWT_EXPIRY, expiration
287
+
288
+ now = int(time.time())
289
+ payload = {
290
+ "iat": now + self._jwt_issued_at,
291
+ "exp": now + (expiration if expiration is not None else self._jwt_expiry),
292
+ "iss": self._app_id,
293
+ }
294
+ assert self._sign_func is not None
295
+ encrypted = self._sign_func(payload)
296
+
297
+ if isinstance(encrypted, bytes):
298
+ return encrypted.decode("utf-8")
299
+ return encrypted
300
+
301
+
302
+ class AppAuthToken(JWT):
303
+ """
304
+ This class is used to authenticate as a GitHub App with a single constant JWT.
305
+
306
+ https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app
307
+
308
+ """
309
+
310
+ def __init__(self, token: str):
311
+ assert isinstance(token, str)
312
+ assert len(token) > 0
313
+ self._token = token
314
+
315
+ @property
316
+ def token(self) -> str:
317
+ return self._token
318
+
319
+
320
+ class AppInstallationAuth(Auth, WithRequester["AppInstallationAuth"]):
321
+ """
322
+ This class is used to authenticate as a GitHub App Installation.
323
+
324
+ https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation
325
+
326
+ """
327
+
328
+ # used to fetch live access token when calling self.token
329
+ __integration: GithubIntegration | None = None
330
+ __installation_authorization: InstallationAuthorization | None = None
331
+
332
+ def __init__(
333
+ self,
334
+ app_auth: AppAuth,
335
+ installation_id: int,
336
+ token_permissions: dict[str, str] | None = None,
337
+ requester: Requester | None = None,
338
+ ):
339
+ super().__init__()
340
+
341
+ assert isinstance(app_auth, AppAuth), app_auth
342
+ assert isinstance(installation_id, int), installation_id
343
+ assert token_permissions is None or isinstance(token_permissions, dict), token_permissions
344
+ assert requester is None or isinstance(requester, Requester), requester
345
+
346
+ self._app_auth = app_auth
347
+ self._installation_id = installation_id
348
+ self._token_permissions = token_permissions
349
+
350
+ if requester is not None:
351
+ self.withRequester(requester)
352
+
353
+ def withRequester(self, requester: Requester) -> AppInstallationAuth:
354
+ assert isinstance(requester, Requester), requester
355
+ super().withRequester(requester.withAuth(self._app_auth))
356
+
357
+ # imported here to avoid circular import
358
+ from githubasyncio.GithubIntegration import GithubIntegration
359
+
360
+ self.__integration = GithubIntegration(**self.requester.kwargs)
361
+
362
+ return self
363
+
364
+ @property
365
+ def app_id(self) -> int | str:
366
+ return self._app_auth.app_id
367
+
368
+ @property
369
+ def installation_id(self) -> int:
370
+ return self._installation_id
371
+
372
+ @property
373
+ def token_permissions(self) -> dict[str, str] | None:
374
+ return self._token_permissions
375
+
376
+ @property
377
+ def token_type(self) -> str:
378
+ return "token"
379
+
380
+ @property
381
+ async def token(self) -> str: # type: ignore[override] # awaited by Auth.authentication()
382
+ if self.__installation_authorization is None or self._is_expired:
383
+ self.__installation_authorization = await self._get_installation_authorization()
384
+ return self.__installation_authorization.token
385
+
386
+ @property
387
+ def _is_expired(self) -> bool:
388
+ assert self.__installation_authorization is not None
389
+ token_expires_at = self.__installation_authorization.expires_at - TOKEN_REFRESH_THRESHOLD_TIMEDELTA
390
+ return token_expires_at < datetime.now(timezone.utc)
391
+
392
+ async def _get_installation_authorization(self) -> InstallationAuthorization:
393
+ assert self.__integration is not None, "Method withRequester(Requester) must be called first"
394
+ return await self.__integration.get_access_token(
395
+ self._installation_id,
396
+ permissions=self._token_permissions,
397
+ )
398
+
399
+ @property
400
+ def _masked_token(self) -> str:
401
+ return "token (oauth token removed)"
402
+
403
+
404
+ class AppUserAuth(Auth, WithRequester["AppUserAuth"]):
405
+ """
406
+ This class is used to authenticate as a GitHub App on behalf of a user.
407
+
408
+ https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-with-a-github-app-on-behalf-of-a-user
409
+
410
+ """
411
+
412
+ _client_id: str
413
+ _client_secret: str
414
+ _token: str
415
+ _type: str
416
+ _scope: str | None
417
+ _expires_at: datetime | None
418
+ _refresh_token: str | None
419
+ _refresh_expires_at: datetime | None
420
+
421
+ # imported here to avoid circular import
422
+
423
+ __app: ApplicationOAuth
424
+
425
+ def __init__(
426
+ self,
427
+ client_id: str,
428
+ client_secret: str,
429
+ token: str,
430
+ token_type: str | None = None,
431
+ expires_at: datetime | None = None,
432
+ refresh_token: str | None = None,
433
+ refresh_expires_at: datetime | None = None,
434
+ requester: Requester | None = None,
435
+ ) -> None:
436
+ super().__init__()
437
+
438
+ assert isinstance(client_id, str) and len(client_id) > 0
439
+ assert isinstance(client_secret, str) and len(client_secret) > 0
440
+ assert isinstance(token, str) and len(token) > 0
441
+ assert token_type is None or isinstance(token_type, str) and len(token_type) > 0, token_type
442
+ assert expires_at is None or isinstance(expires_at, datetime), expires_at
443
+ assert refresh_token is None or isinstance(refresh_token, str) and len(refresh_token) > 0
444
+ assert refresh_expires_at is None or isinstance(refresh_expires_at, datetime), refresh_expires_at
445
+ assert requester is None or isinstance(requester, Requester), requester
446
+
447
+ self._client_id = client_id
448
+ self._client_secret = client_secret
449
+ self._token = token
450
+ self._type = token_type or "bearer"
451
+ self._expires_at = expires_at
452
+ self._refresh_token = refresh_token
453
+ self._refresh_expires_at = refresh_expires_at
454
+
455
+ if requester is not None:
456
+ self.withRequester(requester)
457
+
458
+ @property
459
+ def token_type(self) -> str:
460
+ return self._type
461
+
462
+ @property
463
+ async def token(self) -> str: # type: ignore[override] # awaited by Auth.authentication()
464
+ if self._is_expired:
465
+ await self._refresh()
466
+ return self._token
467
+
468
+ def withRequester(self, requester: Requester) -> AppUserAuth:
469
+ assert isinstance(requester, Requester), requester
470
+ super().withRequester(requester.withAuth(None))
471
+
472
+ # imported here to avoid circular import
473
+ from githubasyncio.ApplicationOAuth import ApplicationOAuth
474
+
475
+ self.__app = ApplicationOAuth(
476
+ # take requester given to super().withRequester, not given to this method
477
+ super().requester,
478
+ headers={},
479
+ attributes={
480
+ "client_id": self._client_id,
481
+ "client_secret": self._client_secret,
482
+ },
483
+ )
484
+
485
+ return self
486
+
487
+ @property
488
+ def _is_expired(self) -> bool:
489
+ return self._expires_at is not None and self._expires_at < datetime.now(timezone.utc)
490
+
491
+ async def _refresh(self) -> None:
492
+ if self._refresh_token is None:
493
+ raise RuntimeError("Cannot refresh expired token because no refresh token has been provided")
494
+ if self._refresh_expires_at is not None and self._refresh_expires_at < datetime.now(timezone.utc):
495
+ raise RuntimeError("Cannot refresh expired token because refresh token also expired")
496
+
497
+ # refresh token
498
+ token = await self.__app.refresh_access_token(self._refresh_token)
499
+
500
+ # update this auth
501
+ self._token = token.token
502
+ self._type = token.type
503
+ self._scope = token.scope
504
+ self._expires_at = token.expires_at
505
+ self._refresh_token = token.refresh_token
506
+ self._refresh_expires_at = token.refresh_expires_at
507
+
508
+ @property
509
+ def expires_at(self) -> datetime | None:
510
+ return self._expires_at
511
+
512
+ @property
513
+ def refresh_token(self) -> str | None:
514
+ return self._refresh_token
515
+
516
+ @property
517
+ def refresh_expires_at(self) -> datetime | None:
518
+ return self._refresh_expires_at
519
+
520
+ @property
521
+ def _masked_token(self) -> str:
522
+ return "Bearer (jwt removed)"
523
+
524
+
525
+ class NetrcAuth(HTTPBasicAuth, WithRequester["NetrcAuth"]):
526
+ """
527
+ This class is used to authenticate via .netrc.
528
+ """
529
+
530
+ def __init__(self) -> None:
531
+ super().__init__()
532
+
533
+ self._login: str | None = None
534
+ self._password: str | None = None
535
+
536
+ @property
537
+ def username(self) -> str:
538
+ return self.login
539
+
540
+ @property
541
+ def login(self) -> str:
542
+ assert self._login is not None, "Method withRequester(Requester) must be called first"
543
+ return self._login
544
+
545
+ @property
546
+ def password(self) -> str:
547
+ assert self._password is not None, "Method withRequester(Requester) must be called first"
548
+ return self._password
549
+
550
+ def withRequester(self, requester: Requester) -> NetrcAuth:
551
+ assert isinstance(requester, Requester), requester
552
+ super().withRequester(requester)
553
+
554
+ auth = utils.get_netrc_auth(requester.base_url, raise_errors=True)
555
+ if auth is None:
556
+ raise RuntimeError(f"Could not get credentials from netrc for host {requester.hostname}")
557
+
558
+ self._login, self._password = auth
559
+
560
+ return self