xiii-cli-core 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.
xiii_cli_core/oauth.py ADDED
@@ -0,0 +1,750 @@
1
+ """Browser-based CLI login: OAuth 2.0 authorization code + PKCE (RFC 7636/8252)
2
+ and the device authorization grant (RFC 8628).
3
+
4
+ The CLI is a public client. Where a browser can reach this machine it opens the
5
+ user's real browser at the product's consent page, receives the authorization
6
+ code on an ephemeral loopback port, and exchanges it together with the PKCE
7
+ verifier for a scoped PAT. No password ever reaches the CLI, and a leaked code
8
+ cannot be redeemed without the verifier that never left this process.
9
+
10
+ Where no browser can reach this machine — an SSH session, a container — the
11
+ loopback leg is impossible: the redirect would land on a port bound here, which
12
+ the human's browser cannot see. That is the case RFC 8628 covers, so the CLI
13
+ then holds a device code, shows a short user code, and polls while the human
14
+ approves on a second device. Both flows end in the same workspace-scoped login
15
+ in the OS keyring — an hour-long bearer token plus the refresh token that
16
+ replaces it for up to 90 days — and both are the same OAuth client, so a new
17
+ login of either kind supersedes the one before it.
18
+ """
19
+
20
+ import base64
21
+ import hashlib
22
+ import hmac
23
+ import http.server
24
+ import secrets
25
+ import socket
26
+ import threading
27
+ import time
28
+ import webbrowser
29
+ from collections.abc import Callable
30
+ from dataclasses import dataclass
31
+ from typing import Any
32
+ from urllib.parse import parse_qsl, urlencode, urlsplit
33
+
34
+ import httpx
35
+ from tldextract import TLDExtract
36
+
37
+ from xiii_cli_core.config import ProductConfig, is_loopback_url
38
+ from xiii_cli_core.errors import AuthenticationError, CliError
39
+
40
+ CODE_CHALLENGE_METHOD = "S256"
41
+ RESPONSE_TYPE = "code"
42
+ CALLBACK_PATH = "/callback"
43
+ DEFAULT_LOGIN_TIMEOUT = 300.0
44
+ _POLL_INTERVAL = 0.1
45
+ # RFC 8628 §3.4 fixes the device grant's grant_type URN.
46
+ DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
47
+ # RFC 8628 §3.2: the interval to use when the server does not send one. §3.5:
48
+ # a ``slow_down`` answer widens it by five seconds.
49
+ DEVICE_DEFAULT_INTERVAL = 5.0
50
+ DEVICE_SLOW_DOWN_INCREMENT = 5.0
51
+ # Only used when the server omits expires_in; it mirrors CLI_DEVICE_CODE_TTL.
52
+ DEVICE_DEFAULT_EXPIRES_IN = 600
53
+ DEVICE_PENDING_DETAIL = "CLI_AUTH_DEVICE_PENDING"
54
+ DEVICE_SLOW_DOWN_DETAIL = "CLI_AUTH_DEVICE_SLOW_DOWN"
55
+ DEVICE_DENIED_DETAIL = "CLI_AUTH_DEVICE_DENIED"
56
+ DEVICE_EXPIRED_DETAIL = "CLI_AUTH_DEVICE_EXPIRED"
57
+ # RFC 8252 §7.3: do not assume the device supports a particular IP version, try
58
+ # both loopback literals and use whichever binds. IPv4 first because it is the
59
+ # more widely reachable of the two from a browser on the same host.
60
+ _LOOPBACK_BINDINGS = (
61
+ (socket.AF_INET, "127.0.0.1", "127.0.0.1"),
62
+ (socket.AF_INET6, "::1", "[::1]"),
63
+ )
64
+
65
+ # Offline snapshot, including private hosting suffixes: separate tenants must
66
+ # not become one trust domain. RFC 6761's reserved test/documentation suffixes
67
+ # follow the same boundary in explicitly configured private environments.
68
+ _DOMAIN_EXTRACTOR = TLDExtract(
69
+ cache_dir=None,
70
+ suffix_list_urls=(),
71
+ include_psl_private_domains=True,
72
+ extra_suffixes=("test", "example", "invalid"),
73
+ )
74
+
75
+
76
+ def client_id_for(config: ProductConfig) -> str:
77
+ """OAuth client id at this product's authorization server.
78
+
79
+ Each product runs its own server, so the registration is per product and
80
+ the product names it (`example login` -> `example-cli`).
81
+ """
82
+ return config.product.oauth_client_id
83
+
84
+
85
+ RESULT_GRANTED = "granted"
86
+ RESULT_DENIED = "denied"
87
+ RESULT_FAILED = "failed"
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class LoginResult:
92
+ token: str
93
+ token_prefix: str
94
+ scopes: list[str]
95
+ expires_in: int
96
+ # The workspace the consent page bound this token to. It rides along with
97
+ # the token so the CLI can file the credential under the right workspace
98
+ # without a second request, which is what lets several workspaces stay
99
+ # authenticated at once.
100
+ workspace_id: str
101
+ # Replaces the hour-long bearer token and is itself replaced on every use
102
+ # (RFC 6749 §6, RFC 9700 §2.2.2). Absent from a backend older than the
103
+ # refresh grant, whose token then simply lives its full lifetime.
104
+ refresh_token: str | None = None
105
+
106
+
107
+ def pkce_pair() -> tuple[str, str]:
108
+ verifier = _b64url(secrets.token_bytes(48))
109
+ challenge = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
110
+ return verifier, challenge
111
+
112
+
113
+ def _b64url(raw: bytes) -> str:
114
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
115
+
116
+
117
+ def bind_loopback_callback(
118
+ handler: type[http.server.BaseHTTPRequestHandler],
119
+ ) -> tuple[http.server.HTTPServer, str]:
120
+ """Bind the callback listener on loopback and return it with its redirect URI.
121
+
122
+ Binds an ephemeral port directly rather than probing for a free one first,
123
+ so no other process can take the port between the probe and the bind.
124
+ """
125
+ for family, bind_host, uri_host in _LOOPBACK_BINDINGS:
126
+ server_class = type(
127
+ "_LoopbackHTTPServer",
128
+ (http.server.HTTPServer,),
129
+ {"address_family": family},
130
+ )
131
+ try:
132
+ server = server_class((bind_host, 0), handler)
133
+ except OSError:
134
+ continue
135
+ port = server.server_address[1]
136
+ return server, f"http://{uri_host}:{port}{CALLBACK_PATH}"
137
+ raise CliError(
138
+ "Could not open a loopback port for the login callback. "
139
+ "Use `auth login` with a PAT instead."
140
+ )
141
+
142
+
143
+ class _CallbackHandler(http.server.BaseHTTPRequestHandler):
144
+ """Loopback listener for the authorization response.
145
+
146
+ Never renders its own page: it bounces the browser straight back to the
147
+ product's consent route with a ``result`` parameter, so the user ends up on
148
+ a branded page instead of a bare ``127.0.0.1`` URL.
149
+ """
150
+
151
+ expected_state: str = ""
152
+ consent_url: str = ""
153
+ result: dict[str, str] = {}
154
+ # Socket timeout per connection (StreamRequestHandler). The server handles
155
+ # one request at a time, so without it a connection that never sends a
156
+ # request line blocks `serve_forever` and `shutdown()` waits past the
157
+ # login timeout.
158
+ timeout = 5
159
+
160
+ def do_GET(self) -> None: # noqa: N802 — BaseHTTPRequestHandler API
161
+ parsed = urlsplit(self.path)
162
+ if parsed.path != CALLBACK_PATH:
163
+ self.send_response(404)
164
+ self.end_headers()
165
+ return
166
+ params = dict(parse_qsl(parsed.query))
167
+ state = params.get("state", "")
168
+ if not state.isascii() or not hmac.compare_digest(state, self.expected_state):
169
+ self._bounce(RESULT_FAILED)
170
+ self.result["error"] = "state_mismatch"
171
+ return
172
+ if error := params.get("error"):
173
+ self._bounce(RESULT_DENIED if error == "access_denied" else RESULT_FAILED)
174
+ self.result["error"] = error
175
+ return
176
+ if code := params.get("code"):
177
+ self._bounce(RESULT_GRANTED)
178
+ self.result["code"] = code
179
+ return
180
+ self._bounce(RESULT_FAILED)
181
+ self.result["error"] = "missing_code"
182
+
183
+ def _bounce(self, result: str) -> None:
184
+ separator = "&" if urlsplit(self.consent_url).query else "?"
185
+ self.send_response(302)
186
+ self.send_header(
187
+ "Location", f"{self.consent_url}{separator}{urlencode({'result': result})}"
188
+ )
189
+ self.send_header("Content-Length", "0")
190
+ self.end_headers()
191
+
192
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
193
+ return
194
+
195
+
196
+ def fetch_metadata(
197
+ config: ProductConfig, *, transport: httpx.BaseTransport | None = None
198
+ ) -> dict[str, Any]:
199
+ try:
200
+ with httpx.Client(
201
+ base_url=config.base_url,
202
+ headers={
203
+ "Accept": "application/json",
204
+ "User-Agent": config.user_agent,
205
+ },
206
+ timeout=httpx.Timeout(15.0, connect=5.0),
207
+ transport=transport,
208
+ ) as client:
209
+ response = client.get("/auth/cli/metadata")
210
+ except httpx.RequestError as exc:
211
+ raise CliError(f"Cannot reach {config.base_url}: {exc}") from exc
212
+ if response.is_error:
213
+ raise CliError(
214
+ f"CLI login metadata unavailable ({response.status_code}). "
215
+ "Update the product backend or use `auth login` with a PAT."
216
+ )
217
+ try:
218
+ payload = response.json()
219
+ except ValueError as exc:
220
+ raise CliError(f"Invalid CLI login metadata from {config.base_url}") from exc
221
+ if not isinstance(payload, dict):
222
+ raise CliError(f"Invalid CLI login metadata from {config.base_url}")
223
+ for field in ("authorization_endpoint", "token_endpoint"):
224
+ value = payload.get(field)
225
+ if not isinstance(value, str) or not value:
226
+ raise CliError(f"CLI login metadata is missing `{field}`")
227
+ _require_trusted_endpoints(config, payload)
228
+ return payload
229
+
230
+
231
+ def device_authorization_endpoint(
232
+ config: ProductConfig, metadata: dict[str, Any]
233
+ ) -> str:
234
+ """The device endpoint from the discovery document, pinned to the API origin.
235
+
236
+ Absent on a backend older than the device grant, which is a plain "update or
237
+ use a PAT" situation rather than something to fall back from silently.
238
+ """
239
+ endpoint = metadata.get("device_authorization_endpoint")
240
+ if not isinstance(endpoint, str) or not endpoint:
241
+ raise CliError(
242
+ f"{config.base_url} does not offer device login. Update the product "
243
+ "backend, or use `auth login` with a PAT."
244
+ )
245
+ if _origin(endpoint) != _origin(config.base_url):
246
+ raise AuthenticationError(
247
+ "Refusing to start a device login at "
248
+ f"{_origin(endpoint)}; it must match the API origin "
249
+ f"{_origin(config.base_url)}."
250
+ )
251
+ return endpoint
252
+
253
+
254
+ def _require_trusted_endpoints(config: ProductConfig, metadata: dict[str, Any]) -> None:
255
+ # The metadata document decides where the browser goes and where the code is
256
+ # redeemed, so both endpoints are pinned before anything is sent. The token
257
+ # exchange must stay on the API origin the caller already trusts, and the
258
+ # consent page must be https and belong to the API's own domain — otherwise
259
+ # a tampered document could send the user's password to a phishing page.
260
+ token_endpoint = str(metadata["token_endpoint"])
261
+ if _origin(token_endpoint) != _origin(config.base_url):
262
+ raise AuthenticationError(
263
+ "Refusing to redeem the authorization code at "
264
+ f"{_origin(token_endpoint)}; it must match the API origin "
265
+ f"{_origin(config.base_url)}."
266
+ )
267
+ authorization_endpoint = str(metadata["authorization_endpoint"])
268
+ _require_trusted_browser_page(authorization_endpoint, config.base_url)
269
+
270
+
271
+ def _require_trusted_browser_page(url: str, api_url: str) -> None:
272
+ try:
273
+ parsed = urlsplit(url)
274
+ valid = (
275
+ parsed.scheme in {"http", "https"}
276
+ and bool(parsed.hostname)
277
+ and parsed.username is None
278
+ and parsed.password is None
279
+ and parsed.port != 0
280
+ and not any(ord(char) <= 32 or char == "\\" for char in url)
281
+ )
282
+ except ValueError as exc:
283
+ raise AuthenticationError("Consent page is not a valid absolute URL") from exc
284
+ if not valid:
285
+ raise AuthenticationError(
286
+ "Consent page is not an absolute http(s) URL without credentials"
287
+ )
288
+ if parsed.scheme != "https" and not is_loopback_url(url):
289
+ raise AuthenticationError(
290
+ "Refusing to open a plain-HTTP page; plain HTTP is allowed only on loopback."
291
+ )
292
+ if not _is_related_host(url, api_url):
293
+ raise AuthenticationError(
294
+ f"Refusing to open the consent page at {_origin(url)}; "
295
+ f"it must belong to the same domain as the API {_origin(api_url)}."
296
+ )
297
+
298
+
299
+ def _origin(url: str) -> str:
300
+ parsed = urlsplit(url)
301
+ return f"{parsed.scheme}://{parsed.netloc}".lower()
302
+
303
+
304
+ def _parent_domain(host: str) -> str:
305
+ return _DOMAIN_EXTRACTOR(host.lower().rstrip(".")).top_domain_under_public_suffix
306
+
307
+
308
+ def _is_related_host(url: str, api_url: str) -> bool:
309
+ host = (urlsplit(url).hostname or "").lower()
310
+ api_host = (urlsplit(api_url).hostname or "").lower()
311
+ if not host or not api_host:
312
+ return False
313
+ if host == api_host:
314
+ return True
315
+ if is_loopback_url(url) and is_loopback_url(api_url):
316
+ return True
317
+ domain = _parent_domain(host)
318
+ return bool(domain) and domain == _parent_domain(api_host)
319
+
320
+
321
+ def build_authorize_url(
322
+ authorization_endpoint: str,
323
+ *,
324
+ client_id: str,
325
+ redirect_uri: str,
326
+ code_challenge: str,
327
+ state: str,
328
+ ) -> str:
329
+ query = urlencode(
330
+ {
331
+ # RFC 6749 §4.1.1 lists response_type as REQUIRED on the
332
+ # authorization request; the consent route rejects anything else.
333
+ "response_type": RESPONSE_TYPE,
334
+ "client_id": client_id,
335
+ "redirect_uri": redirect_uri,
336
+ "code_challenge": code_challenge,
337
+ "code_challenge_method": CODE_CHALLENGE_METHOD,
338
+ "state": state,
339
+ }
340
+ )
341
+ separator = "&" if urlsplit(authorization_endpoint).query else "?"
342
+ return f"{authorization_endpoint}{separator}{query}"
343
+
344
+
345
+ def exchange_code(
346
+ config: ProductConfig,
347
+ *,
348
+ token_endpoint: str,
349
+ code: str,
350
+ code_verifier: str,
351
+ redirect_uri: str,
352
+ transport: httpx.BaseTransport | None = None,
353
+ ) -> LoginResult:
354
+ payload = {
355
+ "grant_type": "authorization_code",
356
+ "client_id": client_id_for(config),
357
+ "code": code,
358
+ "redirect_uri": redirect_uri,
359
+ "code_verifier": code_verifier,
360
+ }
361
+ try:
362
+ with httpx.Client(
363
+ headers={
364
+ "Accept": "application/json",
365
+ "User-Agent": config.user_agent,
366
+ },
367
+ timeout=httpx.Timeout(15.0, connect=5.0),
368
+ transport=transport,
369
+ ) as client:
370
+ # Form-encoded, not JSON: RFC 6749 §4.1.3 defines the token
371
+ # endpoint's request encoding, and the backend parses it that way.
372
+ response = client.post(token_endpoint, data=payload)
373
+ except httpx.RequestError as exc:
374
+ raise CliError(f"Token exchange failed: {exc}") from exc
375
+ if response.is_error:
376
+ raise AuthenticationError(
377
+ f"Token exchange rejected ({response.status_code}: {_detail(response)})"
378
+ )
379
+ return _login_result(response)
380
+
381
+
382
+ def refresh_login(
383
+ config: ProductConfig,
384
+ refresh_token: str,
385
+ *,
386
+ transport: httpx.BaseTransport | None = None,
387
+ ) -> LoginResult:
388
+ """Trade a refresh token for a new bearer token and its successor.
389
+
390
+ The presented refresh token is spent by this call whatever the caller does
391
+ with the answer, so the answer has to be stored before anything else runs:
392
+ presenting the spent token again ends the login on the server.
393
+ """
394
+ metadata = fetch_metadata(config, transport=transport)
395
+ payload = {
396
+ "grant_type": "refresh_token",
397
+ "client_id": client_id_for(config),
398
+ "refresh_token": refresh_token,
399
+ }
400
+ try:
401
+ with httpx.Client(
402
+ headers={
403
+ "Accept": "application/json",
404
+ "User-Agent": config.user_agent,
405
+ },
406
+ timeout=httpx.Timeout(15.0, connect=5.0),
407
+ transport=transport,
408
+ ) as client:
409
+ response = client.post(str(metadata["token_endpoint"]), data=payload)
410
+ except httpx.RequestError as exc:
411
+ raise CliError(f"Token refresh failed: {exc}") from exc
412
+ if response.is_error:
413
+ raise AuthenticationError(
414
+ f"The login has ended ({_detail(response)}). "
415
+ f"Run `{config.entrypoint} login` again."
416
+ )
417
+ return _login_result(response)
418
+
419
+
420
+ def _response_object(response: httpx.Response, message: str) -> dict[str, Any]:
421
+ try:
422
+ body = response.json() if response.content else None
423
+ except ValueError as exc:
424
+ raise AuthenticationError(message) from exc
425
+ if not isinstance(body, dict):
426
+ raise AuthenticationError(message)
427
+ return body
428
+
429
+
430
+ def _login_result(response: httpx.Response) -> LoginResult:
431
+ message = "Unexpected token exchange response"
432
+ body = _response_object(response, message)
433
+ token = body.get("access_token")
434
+ scopes = body.get("scopes", [])
435
+ if (
436
+ not isinstance(token, str)
437
+ or not token.strip()
438
+ or not isinstance(scopes, list)
439
+ or any(not isinstance(scope, str) for scope in scopes)
440
+ ):
441
+ raise AuthenticationError(message)
442
+ try:
443
+ expires_in = int(body.get("expires_in", 0))
444
+ except (ValueError, TypeError, OverflowError) as exc:
445
+ raise AuthenticationError(message) from exc
446
+ # Required, not defaulted: the workspace decides which keyring slot the
447
+ # token is filed under, so a response without one cannot be stored at all.
448
+ if not isinstance(body.get("workspace_id"), str) or not body["workspace_id"]:
449
+ raise AuthenticationError(
450
+ "Token exchange response did not name a workspace. "
451
+ "Update the CLI or the server so both speak the workspace-scoped grant."
452
+ )
453
+ refresh_token = body.get("refresh_token")
454
+ if refresh_token is not None and (
455
+ not isinstance(refresh_token, str) or not refresh_token.strip()
456
+ ):
457
+ raise AuthenticationError(message)
458
+ return LoginResult(
459
+ token=token,
460
+ token_prefix=str(body.get("token_prefix", "")),
461
+ scopes=scopes,
462
+ expires_in=expires_in,
463
+ workspace_id=body["workspace_id"],
464
+ refresh_token=refresh_token,
465
+ )
466
+
467
+
468
+ def _detail(response: httpx.Response) -> str:
469
+ try:
470
+ payload = response.json()
471
+ except ValueError:
472
+ return response.text[:200] or response.reason_phrase
473
+ if isinstance(payload, dict) and payload.get("detail"):
474
+ return str(payload["detail"])
475
+ return str(payload)[:200]
476
+
477
+
478
+ def await_authorization_code(
479
+ authorization_endpoint: str,
480
+ *,
481
+ client_id: str,
482
+ code_challenge: str,
483
+ open_browser: bool = True,
484
+ timeout_seconds: float = DEFAULT_LOGIN_TIMEOUT,
485
+ announce: Callable[[str], None] | None = None,
486
+ ) -> tuple[str, str]:
487
+ """Serve the loopback callback and return ``(code, redirect_uri)``."""
488
+ state = _b64url(secrets.token_bytes(16))
489
+ result: dict[str, str] = {}
490
+ handler = type(
491
+ "_BoundCallbackHandler",
492
+ (_CallbackHandler,),
493
+ {
494
+ "expected_state": state,
495
+ "consent_url": authorization_endpoint,
496
+ "result": result,
497
+ },
498
+ )
499
+ server, redirect_uri = bind_loopback_callback(handler)
500
+ authorize_url = build_authorize_url(
501
+ authorization_endpoint,
502
+ client_id=client_id,
503
+ redirect_uri=redirect_uri,
504
+ code_challenge=code_challenge,
505
+ state=state,
506
+ )
507
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
508
+ thread.start()
509
+ try:
510
+ if announce is not None:
511
+ announce(authorize_url)
512
+ if open_browser:
513
+ webbrowser.open(authorize_url)
514
+ deadline = time.monotonic() + timeout_seconds
515
+ while time.monotonic() < deadline:
516
+ if result:
517
+ break
518
+ time.sleep(_POLL_INTERVAL)
519
+ else:
520
+ raise AuthenticationError(
521
+ "Timed out waiting for the browser consent redirect"
522
+ )
523
+ finally:
524
+ server.shutdown()
525
+ server.server_close()
526
+ if error := result.get("error"):
527
+ raise AuthenticationError(f"Consent was not granted ({error})")
528
+ return result["code"], redirect_uri
529
+
530
+
531
+ @dataclass(frozen=True)
532
+ class DeviceAuthorization:
533
+ device_code: str
534
+ user_code: str
535
+ verification_uri: str
536
+ verification_uri_complete: str
537
+ expires_in: int
538
+ interval: int
539
+
540
+
541
+ def request_device_authorization(
542
+ config: ProductConfig,
543
+ *,
544
+ endpoint: str,
545
+ transport: httpx.BaseTransport | None = None,
546
+ ) -> DeviceAuthorization:
547
+ """Start a device login (RFC 8628 §3.1) and validate what comes back.
548
+
549
+ The response names the page the user is told to open, so it is checked with
550
+ the same rule as the consent page from the discovery document: https (or
551
+ loopback) and the API's own domain. A tampered response must not be able to
552
+ send someone to a look-alike sign-in page.
553
+ """
554
+ try:
555
+ with httpx.Client(
556
+ headers={
557
+ "Accept": "application/json",
558
+ "User-Agent": config.user_agent,
559
+ },
560
+ timeout=httpx.Timeout(15.0, connect=5.0),
561
+ transport=transport,
562
+ ) as client:
563
+ response = client.post(endpoint, data={"client_id": client_id_for(config)})
564
+ except httpx.RequestError as exc:
565
+ raise CliError(f"Device login could not be started: {exc}") from exc
566
+ if response.is_error:
567
+ raise AuthenticationError(
568
+ f"Device login rejected ({response.status_code}: {_detail(response)})"
569
+ )
570
+ message = "Unexpected device authorization response"
571
+ body = _response_object(response, message)
572
+ for field in ("device_code", "user_code", "verification_uri"):
573
+ if not isinstance(body.get(field), str) or not body[field]:
574
+ raise AuthenticationError(
575
+ f"Device authorization response is missing `{field}`"
576
+ )
577
+ verification_uri = str(body["verification_uri"])
578
+ _require_trusted_browser_page(verification_uri, config.base_url)
579
+ complete = body.get("verification_uri_complete")
580
+ complete_uri = (
581
+ complete if isinstance(complete, str) and complete else verification_uri
582
+ )
583
+ _require_trusted_browser_page(complete_uri, config.base_url)
584
+ try:
585
+ expires_in = int(body.get("expires_in", DEVICE_DEFAULT_EXPIRES_IN))
586
+ interval = max(1, int(body.get("interval", DEVICE_DEFAULT_INTERVAL)))
587
+ except (ValueError, TypeError, OverflowError) as exc:
588
+ raise AuthenticationError(message) from exc
589
+ return DeviceAuthorization(
590
+ device_code=str(body["device_code"]),
591
+ user_code=str(body["user_code"]),
592
+ verification_uri=verification_uri,
593
+ verification_uri_complete=complete_uri,
594
+ expires_in=expires_in,
595
+ interval=interval,
596
+ )
597
+
598
+
599
+ def poll_device_token(
600
+ config: ProductConfig,
601
+ *,
602
+ token_endpoint: str,
603
+ authorization: DeviceAuthorization,
604
+ transport: httpx.BaseTransport | None = None,
605
+ sleep: Callable[[float], None] = time.sleep,
606
+ ) -> LoginResult:
607
+ """Poll the token endpoint until the user decides (RFC 8628 §3.4/§3.5).
608
+
609
+ ``authorization_pending`` and ``slow_down`` are progress reports, not
610
+ failures; everything else ends the wait. A rate-limited answer is also
611
+ retried, because a shared address can exhaust the endpoint's class through
612
+ no fault of this client.
613
+ """
614
+ payload = {
615
+ "grant_type": DEVICE_GRANT_TYPE,
616
+ "client_id": client_id_for(config),
617
+ "device_code": authorization.device_code,
618
+ }
619
+ interval = float(authorization.interval)
620
+ deadline = time.monotonic() + authorization.expires_in
621
+ with httpx.Client(
622
+ headers={
623
+ "Accept": "application/json",
624
+ "User-Agent": config.user_agent,
625
+ },
626
+ timeout=httpx.Timeout(15.0, connect=5.0),
627
+ transport=transport,
628
+ ) as client:
629
+ while time.monotonic() < deadline:
630
+ sleep(interval)
631
+ try:
632
+ response = client.post(token_endpoint, data=payload)
633
+ except httpx.RequestError as exc:
634
+ raise CliError(f"Device login failed: {exc}") from exc
635
+ if not response.is_error:
636
+ return _login_result(response)
637
+ detail = _detail(response)
638
+ if detail == DEVICE_SLOW_DOWN_DETAIL:
639
+ interval += DEVICE_SLOW_DOWN_INCREMENT
640
+ continue
641
+ if detail == DEVICE_PENDING_DETAIL or response.status_code == 429:
642
+ continue
643
+ if detail == DEVICE_DENIED_DETAIL:
644
+ raise AuthenticationError("Consent was not granted (access_denied)")
645
+ if detail == DEVICE_EXPIRED_DETAIL:
646
+ raise AuthenticationError(
647
+ "The device login expired before it was approved"
648
+ )
649
+ raise AuthenticationError(
650
+ f"Device login rejected ({response.status_code}: {detail})"
651
+ )
652
+ raise AuthenticationError("The device login expired before it was approved")
653
+
654
+
655
+ def browser_is_available() -> bool:
656
+ """Whether this machine can open a browser the loopback flow could reach.
657
+
658
+ On a remote shell there is usually no browser at all, and a listener bound
659
+ here would be unreachable from the browser the human actually has. That is
660
+ exactly the case RFC 8628 exists for, so the answer picks the flow.
661
+ """
662
+ try:
663
+ return webbrowser.get() is not None
664
+ except webbrowser.Error:
665
+ return False
666
+
667
+
668
+ def run_device_login(
669
+ config: ProductConfig,
670
+ *,
671
+ open_browser: bool = True,
672
+ transport: httpx.BaseTransport | None = None,
673
+ announce: Callable[[DeviceAuthorization], None] | None = None,
674
+ sleep: Callable[[float], None] = time.sleep,
675
+ ) -> LoginResult:
676
+ metadata = fetch_metadata(config, transport=transport)
677
+ authorization = request_device_authorization(
678
+ config,
679
+ endpoint=device_authorization_endpoint(config, metadata),
680
+ transport=transport,
681
+ )
682
+ if announce is not None:
683
+ announce(authorization)
684
+ if open_browser:
685
+ webbrowser.open(authorization.verification_uri_complete)
686
+ return poll_device_token(
687
+ config,
688
+ token_endpoint=str(metadata["token_endpoint"]),
689
+ authorization=authorization,
690
+ transport=transport,
691
+ sleep=sleep,
692
+ )
693
+
694
+
695
+ def run_browser_login(
696
+ config: ProductConfig,
697
+ *,
698
+ open_browser: bool = True,
699
+ timeout_seconds: float = DEFAULT_LOGIN_TIMEOUT,
700
+ announce: Callable[[str], None] | None = None,
701
+ transport: httpx.BaseTransport | None = None,
702
+ ) -> LoginResult:
703
+ metadata = fetch_metadata(config, transport=transport)
704
+ verifier, challenge = pkce_pair()
705
+ code, redirect_uri = await_authorization_code(
706
+ str(metadata["authorization_endpoint"]),
707
+ client_id=client_id_for(config),
708
+ code_challenge=challenge,
709
+ open_browser=open_browser,
710
+ timeout_seconds=timeout_seconds,
711
+ announce=announce,
712
+ )
713
+ return exchange_code(
714
+ config,
715
+ token_endpoint=str(metadata["token_endpoint"]),
716
+ code=code,
717
+ code_verifier=verifier,
718
+ redirect_uri=redirect_uri,
719
+ transport=transport,
720
+ )
721
+
722
+
723
+ __all__ = [
724
+ "CALLBACK_PATH",
725
+ "CODE_CHALLENGE_METHOD",
726
+ "DEFAULT_LOGIN_TIMEOUT",
727
+ "DEVICE_DEFAULT_INTERVAL",
728
+ "DEVICE_GRANT_TYPE",
729
+ "DEVICE_SLOW_DOWN_INCREMENT",
730
+ "RESPONSE_TYPE",
731
+ "RESULT_DENIED",
732
+ "RESULT_FAILED",
733
+ "RESULT_GRANTED",
734
+ "DeviceAuthorization",
735
+ "LoginResult",
736
+ "await_authorization_code",
737
+ "bind_loopback_callback",
738
+ "browser_is_available",
739
+ "build_authorize_url",
740
+ "client_id_for",
741
+ "device_authorization_endpoint",
742
+ "exchange_code",
743
+ "fetch_metadata",
744
+ "pkce_pair",
745
+ "poll_device_token",
746
+ "refresh_login",
747
+ "request_device_authorization",
748
+ "run_browser_login",
749
+ "run_device_login",
750
+ ]