codeasier-gitcode-mcp 0.3.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.
gitcode_mcp/oauth.py ADDED
@@ -0,0 +1,636 @@
1
+ """GitCode login broker implementing the MCP SDK's OAuth provider contract.
2
+
3
+ GitCode credentials stay encrypted on this host. MCP clients receive independent
4
+ opaque tokens bound to one authorization, user, client, resource, and scope set.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import html
11
+ import re
12
+ import secrets
13
+ import time
14
+ from contextlib import asynccontextmanager
15
+ from typing import Any
16
+ from urllib.parse import urlencode
17
+
18
+ import anyio
19
+ from mcp.server.auth.provider import (
20
+ AccessToken,
21
+ AuthorizationCode,
22
+ AuthorizationParams,
23
+ AuthorizeError,
24
+ OAuthAuthorizationServerProvider,
25
+ RefreshToken,
26
+ TokenError,
27
+ )
28
+ from mcp.server.auth.routes import build_metadata
29
+ from mcp.server.auth.settings import AuthSettings, ClientRegistrationOptions, RevocationOptions
30
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
31
+ from pydantic import AnyHttpUrl, Field
32
+ from starlette.requests import Request
33
+ from starlette.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
34
+ from starlette.routing import Route
35
+
36
+ from .api import GitCodeError
37
+ from .config import Settings
38
+ from .oauth_config import READ_SCOPE, WRITE_SCOPE, OAuthSettings
39
+ from .oauth_store import OAuthStore, OAuthStoreError
40
+ from .oauth_upstream import GitCodeOAuthUpstream, OAuthUpstreamError, UpstreamTokens
41
+
42
+ AUTH_TTL = 600
43
+ CODE_TTL = 120
44
+ ACCESS_TTL = 900
45
+ GRANT_TTL = 30 * 86400
46
+ COOKIE_NAME = "__Host-gitcode-oauth"
47
+ OPAQUE = re.compile(r"[A-Za-z0-9_-]{32,128}\Z")
48
+ PAGE_HEADERS = {
49
+ "Cache-Control": "no-store",
50
+ "Pragma": "no-cache",
51
+ "Referrer-Policy": "no-referrer",
52
+ "X-Frame-Options": "DENY",
53
+ "Content-Security-Policy": "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
54
+ "X-Content-Type-Options": "nosniff",
55
+ }
56
+
57
+
58
+ def _nonce() -> str:
59
+ return secrets.token_urlsafe(32)
60
+
61
+
62
+ def _digest(value: str) -> str:
63
+ return hashlib.sha256(value.encode()).hexdigest()
64
+
65
+
66
+ def _token_data(tokens: UpstreamTokens) -> dict[str, Any]:
67
+ return {
68
+ "access_token": tokens.access_token,
69
+ "refresh_token": tokens.refresh_token,
70
+ "expires_at": tokens.expires_at,
71
+ "scope": tokens.scope,
72
+ }
73
+
74
+
75
+ class BrokerCode(AuthorizationCode):
76
+ code: str = Field(repr=False)
77
+ grant_id: str
78
+
79
+
80
+ class BrokerAccessToken(AccessToken):
81
+ token: str = Field(repr=False)
82
+ grant_id: str
83
+
84
+
85
+ class BrokerRefreshToken(RefreshToken):
86
+ token: str = Field(repr=False)
87
+ grant_id: str
88
+
89
+
90
+ class GitCodeOAuthProvider(
91
+ OAuthAuthorizationServerProvider[BrokerCode, BrokerRefreshToken, BrokerAccessToken]
92
+ ):
93
+ def __init__(
94
+ self,
95
+ settings: Settings,
96
+ *,
97
+ store: OAuthStore | None = None,
98
+ upstream: GitCodeOAuthUpstream | None = None,
99
+ ) -> None:
100
+ if settings.oauth is None:
101
+ raise ValueError("OAuth settings are required.")
102
+ self.settings = settings
103
+ self.config: OAuthSettings = settings.oauth
104
+ self.store = store or OAuthStore(self.config.database, self.config.encryption_key)
105
+ self.upstream = upstream or GitCodeOAuthUpstream(
106
+ self.config.gitcode_client_id,
107
+ self.config.gitcode_client_secret,
108
+ self.config.callback_url,
109
+ scopes=self.config.gitcode_scopes,
110
+ timeout=settings.timeout,
111
+ )
112
+ # One worker/event loop is supported. Count holders AND waiters so lock
113
+ # removal cannot create two simultaneous refreshes for the same grant.
114
+ self._refresh_locks: dict[str, tuple[anyio.Lock, int]] = {}
115
+ self._closed = False
116
+ self.scopes = [READ_SCOPE] + ([] if settings.read_only else [WRITE_SCOPE])
117
+ self.client = OAuthClientInformationFull(
118
+ client_id=self.config.client_id,
119
+ client_secret=self.config.client_secret,
120
+ client_name="ChatGPT GitCode",
121
+ redirect_uris=list(self.config.redirect_uris),
122
+ token_endpoint_auth_method="client_secret_post",
123
+ grant_types=["authorization_code", "refresh_token"],
124
+ response_types=["code"],
125
+ scope=" ".join(self.scopes),
126
+ )
127
+
128
+ @property
129
+ def auth_settings(self) -> AuthSettings:
130
+ return AuthSettings(
131
+ issuer_url=self.config.public_url,
132
+ resource_server_url=self.config.resource_url,
133
+ validate_token_resource=True,
134
+ required_scopes=[READ_SCOPE],
135
+ client_registration_options=ClientRegistrationOptions(
136
+ enabled=False, valid_scopes=self.scopes, default_scopes=self.scopes
137
+ ),
138
+ revocation_options=RevocationOptions(enabled=True),
139
+ )
140
+
141
+ @property
142
+ def challenge(self) -> str:
143
+ return (
144
+ 'Bearer error="invalid_token", resource_metadata="'
145
+ + self.config.public_url
146
+ + '/.well-known/oauth-protected-resource/mcp"'
147
+ )
148
+
149
+ async def metadata(self, request: Request) -> Response:
150
+ options = self.auth_settings
151
+ metadata = build_metadata(
152
+ options.issuer_url,
153
+ None,
154
+ options.client_registration_options,
155
+ options.revocation_options,
156
+ ).model_dump(mode="json", exclude_none=True)
157
+ # This pre-registered client uses POST credentials. Do not advertise the
158
+ # SDK's Basic method, whose client_id handling is not suitable here.
159
+ metadata["token_endpoint_auth_methods_supported"] = ["client_secret_post"]
160
+ metadata["revocation_endpoint_auth_methods_supported"] = ["client_secret_post"]
161
+ return JSONResponse(metadata, headers={"Cache-Control": "no-store"})
162
+
163
+ def routes(self) -> list[Route]:
164
+ return [
165
+ Route("/oauth/start", self.start, methods=["GET"]),
166
+ Route("/oauth/gitcode/callback", self.callback, methods=["GET"]),
167
+ Route("/oauth/consent", self.consent, methods=["GET", "POST"]),
168
+ ]
169
+
170
+ async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
171
+ return self.client if client_id == self.config.client_id else None
172
+
173
+ async def register_client(self, client_info: OAuthClientInformationFull) -> None:
174
+ raise NotImplementedError("Dynamic client registration is disabled.")
175
+
176
+ async def authorize(
177
+ self, client: OAuthClientInformationFull, params: AuthorizationParams
178
+ ) -> str:
179
+ if params.resource != self.config.resource_url:
180
+ raise AuthorizeError("invalid_target", "Request this MCP server's resource URL.")
181
+ if not re.fullmatch(r"[A-Za-z0-9_-]{43}", params.code_challenge):
182
+ raise AuthorizeError("invalid_request", "A valid S256 PKCE challenge is required.")
183
+ scopes = params.scopes if params.scopes is not None else self.scopes
184
+ if READ_SCOPE not in scopes or not set(scopes).issubset(self.scopes):
185
+ raise AuthorizeError("invalid_scope", "Request an available GitCode MCP scope.")
186
+ flow = _nonce()
187
+ deadline = time.time() + AUTH_TTL
188
+ payload = {
189
+ **params.model_dump(mode="json"),
190
+ "client_id": client.client_id,
191
+ "scopes": scopes,
192
+ "expires_at": deadline,
193
+ }
194
+ try:
195
+ self.store.put("flow", flow, payload, deadline)
196
+ except OAuthStoreError:
197
+ raise AuthorizeError(
198
+ "temporarily_unavailable", "Authorization is temporarily unavailable."
199
+ ) from None
200
+ return self.config.public_url + "/oauth/start?" + urlencode({"flow": flow})
201
+
202
+ @staticmethod
203
+ def _error_page(
204
+ message: str = "Authorization expired or is invalid. Start a new connection.",
205
+ status: int = 400,
206
+ ) -> Response:
207
+ return HTMLResponse(
208
+ '<!doctype html><html lang="en"><meta charset="utf-8">'
209
+ "<title>GitCode authorization</title><h1>GitCode authorization</h1><p>"
210
+ + html.escape(message)
211
+ + "</p></html>",
212
+ status_code=status,
213
+ headers=PAGE_HEADERS,
214
+ )
215
+
216
+ @staticmethod
217
+ def _browser_matches(request: Request, record: dict[str, Any]) -> bool:
218
+ cookie = request.cookies.get(COOKIE_NAME, "")
219
+ return bool(OPAQUE.fullmatch(cookie)) and secrets.compare_digest(
220
+ _digest(cookie), record.get("browser", "")
221
+ )
222
+
223
+ def _redirect(self, record: dict[str, Any], **params: str) -> Response:
224
+ from mcp.server.auth.provider import construct_redirect_uri
225
+
226
+ if record.get("state") is not None:
227
+ params["state"] = record["state"]
228
+ return RedirectResponse(
229
+ construct_redirect_uri(record["redirect_uri"], **params),
230
+ status_code=303,
231
+ headers=PAGE_HEADERS,
232
+ )
233
+
234
+ async def start(self, request: Request) -> Response:
235
+ flow = request.query_params.get("flow", "")
236
+ if not OPAQUE.fullmatch(flow):
237
+ return self._error_page()
238
+ cookie = request.cookies.get(COOKIE_NAME, "")
239
+ if not OPAQUE.fullmatch(cookie):
240
+ cookie = _nonce()
241
+ state = _nonce()
242
+ with self.store.transaction() as tx:
243
+ record = tx.pop("flow", flow)
244
+ if record is None:
245
+ return self._error_page()
246
+ record["browser"] = _digest(cookie)
247
+ tx.put("state", state, record, record["expires_at"])
248
+ response = RedirectResponse(
249
+ self.upstream.authorization_url(state), status_code=303, headers=PAGE_HEADERS
250
+ )
251
+ response.set_cookie(
252
+ COOKIE_NAME,
253
+ cookie,
254
+ max_age=AUTH_TTL,
255
+ path="/",
256
+ secure=True,
257
+ httponly=True,
258
+ samesite="lax",
259
+ )
260
+ return response
261
+
262
+ async def callback(self, request: Request) -> Response:
263
+ state = request.query_params.get("state", "")
264
+ if not OPAQUE.fullmatch(state):
265
+ return self._error_page()
266
+ with self.store.transaction() as tx:
267
+ record = tx.get("state", state)
268
+ if record is None or not self._browser_matches(request, record):
269
+ return self._error_page()
270
+ tx.delete("state", state)
271
+ if request.query_params.get("error"):
272
+ return self._redirect(
273
+ record,
274
+ error="access_denied",
275
+ error_description="GitCode authorization was declined.",
276
+ )
277
+ code = request.query_params.get("code", "")
278
+ if not code or len(code) > 4096 or any(c.isspace() or ord(c) < 32 for c in code):
279
+ return self._error_page()
280
+ try:
281
+ tokens = await self.upstream.exchange_code(code)
282
+ identity = await self.upstream.user(tokens.access_token)
283
+ except OAuthUpstreamError:
284
+ return self._error_page(
285
+ "GitCode authorization could not be completed. Start a new connection.", 502
286
+ )
287
+ if not self._allowed(identity.subject):
288
+ return self._redirect(
289
+ record,
290
+ error="access_denied",
291
+ error_description="This GitCode account is not allowed on this server.",
292
+ )
293
+ consent = _nonce()
294
+ record.update(
295
+ subject=identity.subject,
296
+ login=identity.login,
297
+ upstream=_token_data(tokens),
298
+ csrf=_nonce(),
299
+ )
300
+ self.store.put("consent", consent, record, record["expires_at"])
301
+ return RedirectResponse(
302
+ self.config.public_url + "/oauth/consent?" + urlencode({"flow": consent}),
303
+ status_code=303,
304
+ headers=PAGE_HEADERS,
305
+ )
306
+
307
+ async def consent(self, request: Request) -> Response:
308
+ form = await request.form() if request.method == "POST" else request.query_params
309
+ flow = str(form.get("flow", ""))
310
+ if not OPAQUE.fullmatch(flow):
311
+ return self._error_page()
312
+ if request.method == "GET":
313
+ record = self.store.get("consent", flow)
314
+ if record is None or not self._browser_matches(request, record):
315
+ return self._error_page()
316
+ escape = html.escape
317
+ actions = "read repository data" + (
318
+ ", create, replace and delete repository files, publish code commits, "
319
+ "and manage issues, branches and pull requests"
320
+ if WRITE_SCOPE in record["scopes"]
321
+ else ""
322
+ )
323
+ repositories = (
324
+ ", ".join(self.settings.allowed_repositories)
325
+ or "repositories accessible to your GitCode account"
326
+ )
327
+ return HTMLResponse(
328
+ '<!doctype html><html lang="en"><meta charset="utf-8"><title>Connect GitCode</title>'
329
+ "<h1>Connect GitCode to ChatGPT</h1><p>GitCode account: <strong>"
330
+ + escape(record["login"])
331
+ + "</strong> ("
332
+ + escape(record["subject"])
333
+ + ")</p>"
334
+ + "<p>Allow client <strong>"
335
+ + escape(record["client_id"])
336
+ + "</strong> to "
337
+ + actions
338
+ + " through "
339
+ + escape(self.config.resource_url)
340
+ + "?</p>"
341
+ + "<p>Repository scope: "
342
+ + escape(repositories)
343
+ + "</p>"
344
+ + '<form method="post" action="'
345
+ + escape(self.config.public_url + "/oauth/consent", quote=True)
346
+ + '">'
347
+ + '<input type="hidden" name="flow" value="'
348
+ + escape(flow, quote=True)
349
+ + '">'
350
+ + '<input type="hidden" name="csrf" value="'
351
+ + escape(record["csrf"], quote=True)
352
+ + '">'
353
+ + '<button name="decision" value="allow">Allow access</button> '
354
+ + '<button name="decision" value="deny">Cancel</button></form></html>',
355
+ headers=PAGE_HEADERS,
356
+ )
357
+ if request.headers.get("origin") != self.config.public_url:
358
+ return self._error_page("Invalid authorization confirmation.", 403)
359
+ authorization_code = _nonce()
360
+ grant_id = _nonce()
361
+ with self.store.transaction() as tx:
362
+ record = tx.get("consent", flow)
363
+ if (
364
+ record is None
365
+ or not self._browser_matches(request, record)
366
+ or not OPAQUE.fullmatch(str(form.get("csrf", "")))
367
+ or not secrets.compare_digest(str(form.get("csrf", "")), record["csrf"])
368
+ or form.get("decision") not in {"allow", "deny"}
369
+ ):
370
+ return self._error_page("Invalid authorization confirmation.", 403)
371
+ tx.delete("consent", flow)
372
+ if form["decision"] == "deny" or not self._allowed(record["subject"]):
373
+ return self._redirect(
374
+ record, error="access_denied", error_description="Authorization was declined."
375
+ )
376
+ deadline = time.time() + GRANT_TTL
377
+ grant = {
378
+ "client_id": record["client_id"],
379
+ "subject": record["subject"],
380
+ "login": record["login"],
381
+ "resource": self.config.resource_url,
382
+ "scopes": record["scopes"],
383
+ "upstream": record["upstream"],
384
+ "expires_at": deadline,
385
+ }
386
+ tx.put("grant", grant_id, grant, deadline)
387
+ code_record = {
388
+ key: record[key]
389
+ for key in (
390
+ "client_id",
391
+ "subject",
392
+ "resource",
393
+ "scopes",
394
+ "code_challenge",
395
+ "redirect_uri",
396
+ "redirect_uri_provided_explicitly",
397
+ )
398
+ }
399
+ code_record.update(grant_id=grant_id, expires_at=time.time() + CODE_TTL)
400
+ tx.put("code", authorization_code, code_record, code_record["expires_at"])
401
+ return self._redirect(record, code=authorization_code)
402
+
403
+ def _allowed(self, subject: str) -> bool:
404
+ return not self.config.allowed_user_ids or subject in self.config.allowed_user_ids
405
+
406
+ def _grant(self, grant_id: str, tx: Any | None = None) -> dict[str, Any] | None:
407
+ record = (tx or self.store).get("grant", grant_id)
408
+ if (
409
+ record is None
410
+ or record["client_id"] != self.config.client_id
411
+ or record["resource"] != self.config.resource_url
412
+ or not self._allowed(record["subject"])
413
+ ):
414
+ return None
415
+ return record
416
+
417
+ async def load_authorization_code(
418
+ self, client: OAuthClientInformationFull, authorization_code: str
419
+ ) -> BrokerCode | None:
420
+ record = self.store.get("code", authorization_code)
421
+ if (
422
+ record is None
423
+ or record["client_id"] != client.client_id
424
+ or not self._grant(record["grant_id"])
425
+ ):
426
+ return None
427
+ return BrokerCode(code=authorization_code, **record)
428
+
429
+ def _issue(
430
+ self, tx: Any, grant_id: str, grant: dict[str, Any], scopes: list[str]
431
+ ) -> OAuthToken:
432
+ access, refresh = _nonce(), _nonce()
433
+ now = int(time.time())
434
+ expires_at = min(now + ACCESS_TTL, int(grant["expires_at"]))
435
+ base = {
436
+ "grant_id": grant_id,
437
+ "subject": grant["subject"],
438
+ "client_id": grant["client_id"],
439
+ "resource": grant["resource"],
440
+ "scopes": scopes,
441
+ }
442
+ tx.put("access", access, {**base, "expires_at": expires_at}, expires_at)
443
+ tx.put(
444
+ "refresh",
445
+ refresh,
446
+ {**base, "expires_at": int(grant["expires_at"])},
447
+ grant["expires_at"],
448
+ )
449
+ return OAuthToken(
450
+ access_token=access,
451
+ refresh_token=refresh,
452
+ expires_in=expires_at - now,
453
+ scope=" ".join(scopes),
454
+ )
455
+
456
+ async def exchange_authorization_code(
457
+ self, client: OAuthClientInformationFull, authorization_code: BrokerCode
458
+ ) -> OAuthToken:
459
+ with self.store.transaction() as tx:
460
+ code = tx.pop("code", authorization_code.code)
461
+ grant = self._grant(authorization_code.grant_id, tx)
462
+ if code is None or grant is None or code["client_id"] != client.client_id:
463
+ raise TokenError("invalid_grant", "Authorization code is no longer valid.")
464
+ return self._issue(tx, authorization_code.grant_id, grant, code["scopes"])
465
+
466
+ async def load_refresh_token(
467
+ self, client: OAuthClientInformationFull, refresh_token: str
468
+ ) -> BrokerRefreshToken | None:
469
+ with self.store.transaction() as tx:
470
+ reused = tx.get("used_refresh", refresh_token)
471
+ if reused is not None and reused["client_id"] == client.client_id:
472
+ tx.delete("grant", reused["grant_id"])
473
+ return None
474
+ record = tx.get("refresh", refresh_token)
475
+ if (
476
+ record is None
477
+ or record["client_id"] != client.client_id
478
+ or not self._grant(record["grant_id"], tx)
479
+ ):
480
+ return None
481
+ return BrokerRefreshToken(token=refresh_token, **record)
482
+
483
+ async def exchange_refresh_token(
484
+ self,
485
+ client: OAuthClientInformationFull,
486
+ refresh_token: BrokerRefreshToken,
487
+ scopes: list[str],
488
+ ) -> OAuthToken:
489
+ result = None
490
+ with self.store.transaction() as tx:
491
+ record = tx.pop("refresh", refresh_token.token)
492
+ grant = self._grant(refresh_token.grant_id, tx)
493
+ if (
494
+ record is not None
495
+ and grant is not None
496
+ and record["client_id"] == client.client_id
497
+ and set(scopes).issubset(record["scopes"])
498
+ and READ_SCOPE in scopes
499
+ ):
500
+ tx.put(
501
+ "used_refresh",
502
+ refresh_token.token,
503
+ {
504
+ "grant_id": refresh_token.grant_id,
505
+ "client_id": client.client_id,
506
+ },
507
+ grant["expires_at"],
508
+ )
509
+ result = self._issue(tx, refresh_token.grant_id, grant, scopes)
510
+ else:
511
+ reused = tx.get("used_refresh", refresh_token.token)
512
+ if reused is not None and reused["client_id"] == client.client_id:
513
+ tx.delete("grant", reused["grant_id"])
514
+ if result is None:
515
+ raise TokenError(
516
+ "invalid_grant", "Refresh token is no longer valid. Reconnect the account."
517
+ )
518
+ return result
519
+
520
+ async def load_access_token(self, token: str) -> BrokerAccessToken | None:
521
+ if not OPAQUE.fullmatch(token):
522
+ return None
523
+ record = self.store.get("access", token)
524
+ if record is None or not self._grant(record["grant_id"]):
525
+ return None
526
+ return BrokerAccessToken(
527
+ token=token, claims={"iss": str(AnyHttpUrl(self.config.public_url))}, **record
528
+ )
529
+
530
+ async def revoke_token(self, token: BrokerAccessToken | BrokerRefreshToken) -> None:
531
+ self.store.delete("grant", token.grant_id)
532
+
533
+ @staticmethod
534
+ def _reauthorize() -> GitCodeError:
535
+ return GitCodeError(
536
+ "authentication_required",
537
+ "Reconnect your GitCode account to authorize this MCP connection.",
538
+ )
539
+
540
+ async def upstream_access_token(self, token: AccessToken | None) -> str:
541
+ if not isinstance(token, BrokerAccessToken):
542
+ raise self._reauthorize()
543
+ async with self._grant_refresh_lock(token.grant_id):
544
+ current = await self.load_access_token(token.token)
545
+ grant = (
546
+ self._grant(token.grant_id)
547
+ if current and current.grant_id == token.grant_id
548
+ else None
549
+ )
550
+ if grant is None:
551
+ raise self._reauthorize()
552
+ upstream = grant["upstream"]
553
+ pending = grant.get("pending_upstream")
554
+ if (
555
+ not pending
556
+ and not grant.get("refresh_in_progress")
557
+ and upstream["expires_at"] > time.time() + 60
558
+ ):
559
+ return upstream["access_token"]
560
+ if not pending and (grant.get("refresh_in_progress") or not upstream["refresh_token"]):
561
+ # A process interruption/unknown exchange outcome must not redeem
562
+ # the old refresh token a second time.
563
+ await self.revoke_token(token)
564
+ raise self._reauthorize()
565
+ try:
566
+ if not pending:
567
+ self._save_refresh_state(token.grant_id, refresh_in_progress=True)
568
+ refreshed = await self.upstream.refresh(upstream["refresh_token"])
569
+ pending = _token_data(refreshed)
570
+ # No await between receiving rotated credentials and encrypted
571
+ # persistence. Identity lookup can then fail/retry/restart safely.
572
+ self._save_refresh_state(
573
+ token.grant_id, pending_upstream=pending, refresh_in_progress=False
574
+ )
575
+ identity = await self.upstream.user(pending["access_token"])
576
+ except OAuthUpstreamError as exc:
577
+ if exc.code in {"invalid_grant", "authentication_failed", "permission_denied"}:
578
+ await self.revoke_token(token)
579
+ raise self._reauthorize() from None
580
+ raise GitCodeError(
581
+ "oauth_upstream_error",
582
+ "GitCode authorization refresh is temporarily unavailable. Try again later.",
583
+ ) from None
584
+ if identity.subject != grant["subject"]:
585
+ await self.revoke_token(token)
586
+ raise self._reauthorize()
587
+ with self.store.transaction() as tx:
588
+ latest = self._grant(token.grant_id, tx)
589
+ if latest is None:
590
+ raise self._reauthorize()
591
+ latest["upstream"] = pending
592
+ latest.pop("pending_upstream", None)
593
+ latest.pop("refresh_in_progress", None)
594
+ tx.put("grant", token.grant_id, latest, latest["expires_at"])
595
+ return pending["access_token"]
596
+
597
+ def _save_refresh_state(self, grant_id: str, **state: Any) -> None:
598
+ with self.store.transaction() as tx:
599
+ latest = self._grant(grant_id, tx)
600
+ if latest is None:
601
+ raise self._reauthorize()
602
+ latest.update(state)
603
+ tx.put("grant", grant_id, latest, latest["expires_at"])
604
+
605
+ @asynccontextmanager
606
+ async def _grant_refresh_lock(self, grant_id: str):
607
+ lock, users = self._refresh_locks.get(grant_id, (anyio.Lock(), 0))
608
+ self._refresh_locks[grant_id] = (lock, users + 1)
609
+ acquired = False
610
+ try:
611
+ try:
612
+ with anyio.fail_after(self.settings.timeout):
613
+ await lock.acquire()
614
+ acquired = True
615
+ except TimeoutError:
616
+ raise GitCodeError(
617
+ "oauth_upstream_error",
618
+ "GitCode authorization refresh is busy. Try again later.",
619
+ ) from None
620
+ yield
621
+ finally:
622
+ if acquired:
623
+ lock.release()
624
+ _, users = self._refresh_locks[grant_id]
625
+ if users == 1:
626
+ del self._refresh_locks[grant_id]
627
+ else:
628
+ self._refresh_locks[grant_id] = (lock, users - 1)
629
+
630
+ async def aclose(self) -> None:
631
+ if not self._closed:
632
+ self._closed = True
633
+ try:
634
+ await self.upstream.aclose()
635
+ finally:
636
+ self.store.close()