ms-cli 0.2.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.
Files changed (67) hide show
  1. ad_cli/__init__.py +6 -0
  2. ad_cli/__main__.py +6 -0
  3. ad_cli/auth.py +351 -0
  4. ad_cli/cli.py +278 -0
  5. ad_cli/discovery.py +243 -0
  6. ad_cli/dynamic.py +816 -0
  7. ad_cli/errors.py +45 -0
  8. ad_cli/http.py +424 -0
  9. ad_cli/invoke.py +652 -0
  10. ad_cli/main.py +703 -0
  11. cann_cli/__init__.py +6 -0
  12. cann_cli/__main__.py +6 -0
  13. cann_cli/auth.py +351 -0
  14. cann_cli/cli.py +278 -0
  15. cann_cli/discovery.py +243 -0
  16. cann_cli/dynamic.py +816 -0
  17. cann_cli/errors.py +45 -0
  18. cann_cli/http.py +424 -0
  19. cann_cli/invoke.py +652 -0
  20. cann_cli/main.py +703 -0
  21. ms_cli/__init__.py +6 -0
  22. ms_cli/__main__.py +6 -0
  23. ms_cli/auth.py +351 -0
  24. ms_cli/cli.py +278 -0
  25. ms_cli/discovery.py +243 -0
  26. ms_cli/dynamic.py +816 -0
  27. ms_cli/errors.py +45 -0
  28. ms_cli/http.py +424 -0
  29. ms_cli/invoke.py +652 -0
  30. ms_cli/main.py +703 -0
  31. ms_cli-0.2.0.dist-info/METADATA +444 -0
  32. ms_cli-0.2.0.dist-info/RECORD +67 -0
  33. ms_cli-0.2.0.dist-info/WHEEL +5 -0
  34. ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
  35. ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
  36. ms_cli-0.2.0.dist-info/top_level.txt +5 -0
  37. oed_cli/__init__.py +6 -0
  38. oed_cli/__main__.py +6 -0
  39. oed_cli/auth.py +1629 -0
  40. oed_cli/cli.py +297 -0
  41. oed_cli/defaults.toml +44 -0
  42. oed_cli/discovery.py +243 -0
  43. oed_cli/dynamic.py +816 -0
  44. oed_cli/errors.py +45 -0
  45. oed_cli/http.py +423 -0
  46. oed_cli/invoke.py +651 -0
  47. oed_cli/main.py +782 -0
  48. ogd_cli/__init__.py +6 -0
  49. ogd_cli/__main__.py +6 -0
  50. ogd_cli/auth.py +351 -0
  51. ogd_cli/cli.py +278 -0
  52. ogd_cli/discovery.py +243 -0
  53. ogd_cli/dynamic.py +816 -0
  54. ogd_cli/errors.py +45 -0
  55. ogd_cli/http.py +424 -0
  56. ogd_cli/invoke.py +652 -0
  57. ogd_cli/main.py +703 -0
  58. oud_cli/__init__.py +6 -0
  59. oud_cli/__main__.py +6 -0
  60. oud_cli/auth.py +351 -0
  61. oud_cli/cli.py +278 -0
  62. oud_cli/discovery.py +243 -0
  63. oud_cli/dynamic.py +816 -0
  64. oud_cli/errors.py +45 -0
  65. oud_cli/http.py +424 -0
  66. oud_cli/invoke.py +652 -0
  67. oud_cli/main.py +703 -0
oed_cli/auth.py ADDED
@@ -0,0 +1,1629 @@
1
+ """openEuler credential storage and login flows (v0.5).
2
+
3
+ v0.5 replaces the v0.4 browser-callback flow with **RFC 8628 Device
4
+ Authorization Grant**, backed by the MSAL Python library. The CLI never opens
5
+ a local HTTP server; authentication works in headless / CI / SSH / agent
6
+ contexts without modification.
7
+
8
+ Storage:
9
+ ``<OED_CACHE_DIR>/auth.json`` (POSIX 0600, atomic write) holds a
10
+ serialized MSAL token cache plus an optional ``cookie`` field. The MSAL
11
+ cache contains ``access_token`` + ``refresh_token`` + account metadata,
12
+ which is what enables silent refresh on subsequent calls.
13
+
14
+ Public surface:
15
+ - :func:`save_auth` / :func:`load_auth` / :func:`clear_auth` — manual token
16
+ persistence (also synthesizes a minimal MSAL cache for backward compat)
17
+ - :func:`get_token` / :func:`get_cookie` — read fields out of auth.json
18
+ - :func:`auth_headers_from_storage` — build ``Authorization`` / ``Cookie``
19
+ headers, preferring the env overrides ``OED_TOKEN`` / ``OED_COOKIE``
20
+ - :func:`device_login` — RFC 8628 device authorization grant (MSAL)
21
+ - :func:`manual_login` — TTY paste of a token (unchanged from v0.4)
22
+ - :func:`load_defaults` / :func:`get_client_id` / :func:`get_device_url` —
23
+ read bundled ``defaults.toml`` with env-var override
24
+ - :func:`_try_open_browser` / :func:`_has_display` — auto-open the
25
+ verification URL when a display is available
26
+ - :func:`_copy_to_clipboard` — stdlib ``subprocess`` against
27
+ ``wl-copy`` / ``xclip`` / ``pbcopy`` / ``clip.exe``
28
+ - :data:`auth_group` — click sub-group wired into :mod:`oed_cli.cli`
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import contextlib
34
+ import json
35
+ import os
36
+ import subprocess
37
+ import sys
38
+ import time
39
+ import webbrowser
40
+ from base64 import b64decode
41
+ from collections.abc import Callable
42
+ from importlib.resources import files
43
+ from pathlib import Path
44
+ from typing import Any
45
+
46
+ import click
47
+ import httpx # used by _fetch_user_allowlist (one HTTP GET after token success)
48
+ import msal # RFC 8628 device authorization grant + token cache
49
+ import tomllib
50
+
51
+ from .discovery import ag_token_path, auth_token_path
52
+
53
+ # Best-effort token lifetime — the openEuler gateway does not publish a TTL.
54
+ TOKEN_MAX_AGE = 24 * 60 * 60
55
+
56
+ # Credential store identifiers for the OS-native backend (keyring).
57
+ # Single-account for v0.6; multi-account support can namespace by MSAL
58
+ # ``home_account_id`` later without breaking compatibility (keyring
59
+ # tolerates multiple usernames under one service).
60
+ _KEYRING_SERVICE = "oed-cli"
61
+ _KEYRING_USERNAME = "default"
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Defaults (bundled in the wheel at oed_cli/defaults.toml)
66
+ # ---------------------------------------------------------------------------
67
+
68
+
69
+ def load_defaults() -> dict[str, Any]:
70
+ """Read bundled ``defaults.toml``. Returns parsed dict."""
71
+
72
+ text = (
73
+ files("oed_cli").joinpath("defaults.toml").read_text(encoding="utf-8")
74
+ )
75
+ return tomllib.loads(text)
76
+
77
+
78
+ def get_client_id() -> str:
79
+ """OAuth ``client_id``. Env ``OED_APP_ID`` overrides bundled default."""
80
+
81
+ defaults = load_defaults()
82
+ return os.environ.get("OED_APP_ID") or defaults["oauth"]["client_id"]
83
+
84
+
85
+ def get_device_url() -> str:
86
+ """openEuler usercenter base URL. Env ``OED_DEVICE_URL`` overrides bundled default."""
87
+
88
+ defaults = load_defaults()
89
+ return os.environ.get("OED_DEVICE_URL") or defaults["oauth"]["device_url"]
90
+
91
+
92
+ def _get_device_authorization_url() -> str | None:
93
+ """Device authorization endpoint from defaults.toml or ``None``."""
94
+
95
+ defaults = load_defaults()
96
+ return defaults["oauth"].get("device_authorization_url")
97
+
98
+
99
+ def _get_user_data_url() -> str | None:
100
+ """CLI user-data (allow-list) endpoint from defaults.toml or ``None``."""
101
+
102
+ defaults = load_defaults()
103
+ return defaults["oauth"].get("cli_user_data_url")
104
+
105
+
106
+ # MSAL reserved scopes — it auto-appends these and refuses them if passed
107
+ # explicitly (ValueError: "cannot use any scope value that is reserved").
108
+ _RESERVED_SCOPES = {"openid", "profile", "offline_access"}
109
+
110
+ # Hardcoded base OAuth scopes. These are part of the wire contract with
111
+ # openEuler oneid and intentionally NOT read from defaults.toml:
112
+ # - `email`: makes /userinfo return the user's email.
113
+ # - `id_token`: oneid's `OidcService.getOidcTokenByDeviceCode` only emits
114
+ # an `id_token` field in the /token response when the requested scopes
115
+ # literally contain the string "id_token" (see
116
+ # scopes.contains("id_token") gate). Non-standard OIDC (where `openid`
117
+ # alone would trigger id_token issuance), but required by this server.
118
+ # MSAL keys its silent-refresh Account map on id_token claims — without
119
+ # id_token, refresh_token is unusable and the 120s access_token TTL
120
+ # forces re-login every 2 minutes.
121
+ #
122
+ # MSAL will auto-prepend the reserved set on top of these.
123
+ _BASE_SCOPES: tuple[str, ...] = ("email", "id_token")
124
+
125
+
126
+ def get_scopes() -> list[str]:
127
+ """OAuth scopes to request at device-flow initiation.
128
+
129
+ Returns the hardcoded base set (``email`` + ``id_token``) unless
130
+ ``OED_SCOPES`` env var is set, in which case a comma-separated value
131
+ overrides. MSAL auto-appends ``openid`` / ``profile`` / ``offline_access``;
132
+ any reserved scope passed via env is filtered out to avoid MSAL's
133
+ reserved-scope error.
134
+ """
135
+
136
+ raw = os.environ.get("OED_SCOPES")
137
+ if raw is not None:
138
+ scopes = [s.strip() for s in raw.split(",") if s.strip()]
139
+ else:
140
+ scopes = list(_BASE_SCOPES)
141
+ return [s for s in scopes if s and s not in _RESERVED_SCOPES]
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Token storage (keyring primary + plaintext fallback)
146
+ # ---------------------------------------------------------------------------
147
+ #
148
+ # v0.6+: tokens are persisted into the OS-native credential store via the
149
+ # ``keyring`` library when an accessible backend is detected (macOS Keychain,
150
+ # Windows DPAPI / Credential Manager, Linux SecretService). On environments
151
+ # where keyring is unreachable (headless Linux / CI / Docker without
152
+ # libsecret) or when keyring raises on read/write, the implementation falls
153
+ # back to a 0600-mode plaintext file. The plaintext file is deleted after a
154
+ # successful keyring write so the OS keystore is the single source of truth.
155
+
156
+
157
+ class _SecureStore:
158
+ """Thin facade over :mod:`keyring` with a transparent plaintext fallback.
159
+
160
+ Resolution is lazy: each call probes the current best backend and caches
161
+ the verdict. Any ``keyring`` failure (``NoKeyringError``, locked
162
+ credential DB, ``OSError`` from libsecret, sandbox restrictions) causes
163
+ a silent fallback to ``auth.json`` (mode 0600) and a one-line stderr
164
+ note — never a hard error, so silent refresh keeps working.
165
+ """
166
+
167
+ def __init__(self, *, username: str = _KEYRING_USERNAME,
168
+ fallback_path: Callable[[], Path] = auth_token_path) -> None:
169
+ # ``username`` namespaces the keyring entry so a second credential
170
+ # (e.g. the AtomGit PAT) can share the ``_KEYRING_SERVICE`` without
171
+ # colliding with the oneid ``default`` entry. ``fallback_path`` picks
172
+ # the plaintext 0600 file used when keyring is unreachable — the ag
173
+ # PAT lives under ``tokens/ag.json``, separate from ``auth.json``.
174
+ self._username = username
175
+ self._fallback_path = fallback_path
176
+ self._keyring: Any | None = None
177
+ # ``None`` = not probed yet, ``True``/``False`` = resolved verdict
178
+ self._available: bool | None = None
179
+ self._last_backend: str = "unprobed"
180
+
181
+ # -- internal ----------------------------------------------------------
182
+
183
+ def _resolve(self) -> bool:
184
+ if self._available is not None:
185
+ return self._available
186
+ try:
187
+ import keyring # type: ignore[import-untyped]
188
+ import keyring.errors # type: ignore[import-untyped]
189
+
190
+ self._keyring = keyring
191
+ # Cheapest probe: a single get. Side-effect free — we don't want
192
+ # to write a probe entry into the user's real keychain.
193
+ # NoKeyringError is the canonical "no backend" signal; other
194
+ # exceptions mean the backend exists but is broken/locked, in
195
+ # which case we silently fall through to plaintext 0600.
196
+ try:
197
+ keyring.get_password(_KEYRING_SERVICE, self._username)
198
+ except keyring.errors.NoKeyringError:
199
+ self._available = False
200
+ return False
201
+ except Exception: # noqa: BLE001 — best-effort probe
202
+ # Locked credential DB, libsecret not running, sandbox block,
203
+ # GNOME Keyring not unlocked — module loaded but unusable.
204
+ # Surface the backend via `oed auth status`, not stderr noise.
205
+ self._available = False
206
+ return False
207
+ self._available = True
208
+ return True
209
+ except ImportError:
210
+ self._available = False
211
+ return False
212
+
213
+ # -- public API ---------------------------------------------------------
214
+
215
+ def save(self, payload: dict[str, Any]) -> str:
216
+ """Persist ``payload`` via the best available backend.
217
+
218
+ Returns the backend label (``"keyring"`` or ``"plaintext"``) so the
219
+ caller can surface it (``oed auth status``).
220
+ """
221
+
222
+ path = self._fallback_path()
223
+ if self._resolve():
224
+ try:
225
+ blob = json.dumps(payload, ensure_ascii=False)
226
+ self._keyring.set_password(_KEYRING_SERVICE, self._username, blob) # type: ignore[union-attr]
227
+ # keyring is the source of truth now — drop the plaintext copy
228
+ # so a later read cannot see stale data from a previous
229
+ # plaintext-only session.
230
+ with contextlib.suppress(OSError):
231
+ path.unlink()
232
+ self._last_backend = "keyring"
233
+ return "keyring"
234
+ except Exception: # noqa: BLE001 — best-effort fallback
235
+ # Backend reported as available by the probe but the real
236
+ # write raised (locked keyring, etc.). Mark broken for this
237
+ # process so subsequent operations go straight to plaintext
238
+ # instead of re-probing keyring on every call.
239
+ self._available = False
240
+ path.parent.mkdir(parents=True, exist_ok=True)
241
+ _atomic_write_json_plaintext(path, payload)
242
+ self._last_backend = "plaintext"
243
+ return "plaintext"
244
+
245
+ def load(self) -> dict[str, Any] | None:
246
+ """Read ``payload`` from the best available backend.
247
+
248
+ Prefers keyring when reachable; falls back to the plaintext file
249
+ (used both for migration of legacy auth.json and for headless
250
+ environments without an OS keystore).
251
+ """
252
+
253
+ if self._resolve():
254
+ try:
255
+ raw = self._keyring.get_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
256
+ except Exception: # noqa: BLE001 — best-effort fallback
257
+ # Same as save(): mark broken so we don't keep retrying
258
+ # keyring (and burning time on a locked backend) every read.
259
+ self._available = False
260
+ raw = None
261
+ if raw:
262
+ try:
263
+ self._last_backend = "keyring"
264
+ return json.loads(raw)
265
+ except json.JSONDecodeError:
266
+ # corrupt entry — drop it and let the caller treat as
267
+ # unauthenticated rather than crash
268
+ with contextlib.suppress(Exception):
269
+ self._keyring.delete_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
270
+ # Fallback: plaintext file (migration or no-keyring envs).
271
+ existing = _read_existing(self._fallback_path())
272
+ self._last_backend = "plaintext" if existing else "unprobed"
273
+ return existing or None
274
+
275
+ def clear(self) -> None:
276
+ """Remove the payload from both backends (idempotent)."""
277
+
278
+ if self._resolve():
279
+ with contextlib.suppress(Exception):
280
+ self._keyring.delete_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
281
+ with contextlib.suppress(OSError):
282
+ self._fallback_path().unlink()
283
+ self._last_backend = "unprobed"
284
+
285
+ def backend_label(self) -> str:
286
+ """Last backend actually used (``"keyring"`` / ``"plaintext"`` / ``"unprobed"``)."""
287
+
288
+ return self._last_backend
289
+
290
+
291
+ # Module-level singleton — writers/readers delegate to this.
292
+ _secure_store = _SecureStore()
293
+
294
+
295
+ def save_auth(
296
+ token: str,
297
+ *,
298
+ cookie: str | None = None,
299
+ refresh_token: str | None = None,
300
+ ) -> Path:
301
+ """Persist a token (+ optional cookie / refresh_token).
302
+
303
+ Manual ``oed auth token <bearer>`` flow. Synthesizes a minimal MSAL cache
304
+ so :func:`get_token` and :func:`auth_headers_from_storage` work uniformly
305
+ for both manual and device-flow logins.
306
+
307
+ Writes go through :class:`_SecureStore`, which prefers the OS keyring
308
+ when reachable (macOS Keychain / Windows DPAPI / Linux SecretService)
309
+ and falls back to a 0600 plaintext ``auth.json`` otherwise.
310
+ """
311
+
312
+ if not token:
313
+ raise ValueError("token must be a non-empty string")
314
+ path = auth_token_path()
315
+ path.parent.mkdir(parents=True, exist_ok=True)
316
+ existing = _secure_store.load() or {}
317
+ data: dict[str, Any] = dict(existing)
318
+ data["msal_cache"] = _synth_msal_cache_json(token, refresh_token)
319
+ data["created_at"] = existing.get("created_at", time.time())
320
+ if cookie is not None:
321
+ data["cookie"] = cookie
322
+ _secure_store.save(data)
323
+ return path
324
+
325
+
326
+ def save_msal_auth(
327
+ cache: Any,
328
+ *,
329
+ cookie: str | None = None,
330
+ allowlist: list[str] | None = None,
331
+ ) -> Path:
332
+ """Persist an MSAL :class:`SerializableTokenCache` (+ optional cookie / allowlist).
333
+
334
+ Used by the device-flow path. ``cache`` is a ``msal.SerializableTokenCache``
335
+ whose ``.serialize()`` returns the MSAL JSON string. Pass ``allowlist``
336
+ to also persist the per-user service allow-list (typically fetched by
337
+ :func:`_fetch_user_allowlist` right after token success); pass ``None``
338
+ to leave the existing field untouched (legacy auth.json compat).
339
+
340
+ Writes go through :class:`_SecureStore` (keyring primary, plaintext fallback).
341
+ """
342
+
343
+ path = auth_token_path()
344
+ path.parent.mkdir(parents=True, exist_ok=True)
345
+ existing = _secure_store.load() or {}
346
+ data: dict[str, Any] = dict(existing)
347
+ if cache.has_state_changed:
348
+ data["msal_cache"] = cache.serialize()
349
+ if not data.get("msal_cache"):
350
+ # Nothing to persist (cache was empty + no cookie change). Keep existing.
351
+ return path
352
+ # A fresh device-flow token just landed — refresh the login timestamp so
353
+ # ``is_token_expired`` / ``oed auth status`` reflect *this* login rather
354
+ # than the previous one. The old ``if "created_at" not in data`` guard
355
+ # left the stale timestamp from a prior login in place, so a re-login on
356
+ # an existing auth.json kept reporting ``expired: true`` even though the
357
+ # new token was valid. See ``oed auth status`` / :func:`is_token_expired`.
358
+ data["created_at"] = time.time()
359
+ if cookie is not None:
360
+ data["cookie"] = cookie
361
+ if allowlist is not None:
362
+ data["allowlist"] = allowlist
363
+ _secure_store.save(data)
364
+ return path
365
+
366
+
367
+ def load_auth() -> dict[str, Any] | None:
368
+ """Return the parsed auth-store contents, or ``None`` if missing / corrupt.
369
+
370
+ Reads from keyring when reachable; falls back to the plaintext file
371
+ for migration of legacy auth.json or for environments without an OS
372
+ keystore.
373
+ """
374
+
375
+ return _secure_store.load()
376
+
377
+
378
+ def clear_auth() -> bool:
379
+ """Remove the stored credentials (keyring + plaintext). Idempotent.
380
+
381
+ Returns True if any data was removed from either backend.
382
+ """
383
+
384
+ had_data = load_auth() is not None
385
+ _secure_store.clear()
386
+ return had_data
387
+
388
+
389
+ def get_token() -> str | None:
390
+ """Return the active ``access_token`` from auth.json, or ``None``.
391
+
392
+ If the cached access token is present but expired, attempts a silent
393
+ refresh via MSAL ``acquire_token_silent`` (uses the cached refresh_token).
394
+ On success the updated cache is persisted automatically.
395
+ """
396
+
397
+ data = load_auth()
398
+ if not data:
399
+ return None
400
+ cache_json = data.get("msal_cache") or ""
401
+ token = _extract_access_token(cache_json)
402
+ if token:
403
+ return token
404
+
405
+ # access_token missing or expired — try silent refresh from MSAL cache
406
+ refreshed = _try_silent_refresh(data)
407
+ if refreshed:
408
+ return refreshed
409
+ return None
410
+
411
+
412
+ def _try_silent_refresh(stored: dict[str, Any]) -> str | None:
413
+ """Attempt MSAL ``acquire_token_silent`` to refresh an expired access token.
414
+
415
+ Reconstructs the ``PublicClientApplication`` with the persisted cache and
416
+ calls ``acquire_token_silent``. If a new access token is obtained, the
417
+ updated cache is written back to ``auth.json``.
418
+ """
419
+
420
+ cache_json = stored.get("msal_cache") or ""
421
+ if not cache_json:
422
+ return None
423
+
424
+ cache = msal.SerializableTokenCache()
425
+ with contextlib.suppress(Exception):
426
+ cache.deserialize(cache_json)
427
+
428
+ # Check if there's a refresh_token in the cache — no point trying without one.
429
+ rt_entries = None
430
+ with contextlib.suppress(Exception):
431
+ rt_entries = list(cache.search("RefreshToken"))
432
+ if not rt_entries:
433
+ return None
434
+
435
+ client_id = get_client_id()
436
+ device_url = get_device_url()
437
+
438
+ app = msal.PublicClientApplication(
439
+ client_id=client_id,
440
+ oidc_authority=device_url, # non-Azure OIDC discovery
441
+ token_cache=cache,
442
+ instance_discovery=False, # openEuler is not Azure; skip Azure domain check
443
+ )
444
+
445
+ accounts = app.get_accounts()
446
+ if not accounts:
447
+ return None
448
+
449
+ with contextlib.suppress(Exception):
450
+ result = app.acquire_token_silent(
451
+ scopes=[], # reserved scopes (openid/profile/offline_access) added by MSAL
452
+ account=accounts[0],
453
+ )
454
+ if result and "access_token" in result:
455
+ # Persist the refreshed cache back to disk.
456
+ save_msal_auth(cache)
457
+ return result["access_token"]
458
+ return None
459
+
460
+
461
+ def get_cookie() -> str | None:
462
+ """Return the stored ``cookie`` value, or ``None``."""
463
+
464
+ data = load_auth()
465
+ return data.get("cookie") if data else None
466
+
467
+
468
+ def is_token_expired(stored: dict[str, Any], *, max_age: int = TOKEN_MAX_AGE) -> bool:
469
+ """Best-effort age check based on local ``created_at`` timestamp."""
470
+
471
+ created_at = float(stored.get("created_at", 0))
472
+ return (time.time() - created_at) > max_age
473
+
474
+
475
+ def auth_headers_from_storage() -> dict[str, str]:
476
+ """Build ``Authorization`` / ``Cookie`` headers from env (priority) or auth.json."""
477
+
478
+ token = os.environ.get("OED_TOKEN") or None
479
+ cookie = os.environ.get("OED_COOKIE") or None
480
+ if not token:
481
+ stored = load_auth()
482
+ if stored:
483
+ token = token or get_token()
484
+ cookie = cookie or stored.get("cookie")
485
+ headers: dict[str, str] = {}
486
+ if token:
487
+ headers["Authorization"] = f"Bearer {token}"
488
+ if cookie:
489
+ headers["Cookie"] = cookie
490
+ return headers
491
+
492
+
493
+ # ---------------------------------------------------------------------------
494
+ # Cookie capture from backend responses (unchanged contract)
495
+ # ---------------------------------------------------------------------------
496
+
497
+
498
+ def extract_set_cookie(headers: Any) -> str | None:
499
+ """Return first ``Set-Cookie`` ``name=value`` from a header mapping."""
500
+
501
+ candidates: list[str] = []
502
+ if hasattr(headers, "items"):
503
+ for key, value in headers.items():
504
+ if str(key).lower() == "set-cookie" and value:
505
+ candidates.append(str(value))
506
+ elif hasattr(headers, "get_list"):
507
+ candidates.extend(headers.get_list("set-cookie"))
508
+ for raw in candidates:
509
+ first = raw.split(";", 1)[0].strip()
510
+ if "=" in first:
511
+ return first
512
+ return None
513
+
514
+
515
+ def update_auth_from_response_headers(headers: Any) -> bool:
516
+ """Persist a rotated ``Set-Cookie`` from the backend into the auth store.
517
+
518
+ Preserves the existing MSAL cache (and any refresh_token it carries) —
519
+ only the ``cookie`` field is overwritten. Goes through :class:`_SecureStore`
520
+ so the cookie lands in the same backend (keyring or plaintext) as the
521
+ existing MSAL cache.
522
+ """
523
+
524
+ new_cookie = extract_set_cookie(headers)
525
+ if not new_cookie:
526
+ return False
527
+ existing = _secure_store.load() or {}
528
+ if existing.get("cookie") == new_cookie:
529
+ return False
530
+ existing["cookie"] = new_cookie
531
+ existing.setdefault("created_at", time.time())
532
+ _secure_store.save(existing)
533
+ return True
534
+
535
+
536
+ # ---------------------------------------------------------------------------
537
+ # Display helpers
538
+ # ---------------------------------------------------------------------------
539
+
540
+
541
+ def _token_fingerprint(token: str) -> str:
542
+ """Return ``first3...last2`` for display. Never the full token."""
543
+
544
+ if len(token) <= 6:
545
+ return "***"
546
+ return f"{token[:3]}...{token[-2:]}"
547
+
548
+
549
+ # ---------------------------------------------------------------------------
550
+ # Browser / display helpers (reused for verification_uri)
551
+ # ---------------------------------------------------------------------------
552
+
553
+
554
+ def _has_display() -> bool:
555
+ """Linux: ``DISPLAY`` (X11) or ``WAYLAND_DISPLAY`` (Wayland). macOS/Win: True."""
556
+
557
+ if sys.platform.startswith("linux"):
558
+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
559
+ # macOS / Windows are assumed to have a display; tests can override via
560
+ # BROWSER=none if they need to.
561
+ return True
562
+
563
+
564
+ def _try_open_browser(url: str) -> bool:
565
+ """Open ``url`` in default browser. On failure, print JSON to stderr.
566
+
567
+ Honors ``BROWSER=none|echo|off|print`` → skip webbrowser entirely.
568
+ """
569
+
570
+ browser_env = os.environ.get("BROWSER", "").strip().lower()
571
+ if browser_env in {"none", "echo", "off", "print"}:
572
+ click.echo(
573
+ json.dumps(
574
+ {
575
+ "ok": True,
576
+ "stage": "browser_skipped",
577
+ "reason": f"BROWSER={browser_env}",
578
+ "login_url": url,
579
+ },
580
+ ensure_ascii=False,
581
+ ),
582
+ err=True,
583
+ )
584
+ return False
585
+
586
+ if not _has_display():
587
+ click.echo(
588
+ json.dumps(
589
+ {
590
+ "ok": True,
591
+ "stage": "no_display",
592
+ "platform": sys.platform,
593
+ "login_url": url,
594
+ "hint": (
595
+ "Headless Linux detected (no DISPLAY). Open this URL "
596
+ "in a browser on any device, then return here to "
597
+ "continue polling. Or press Ctrl-C and re-run with "
598
+ "`oed auth login --manual`."
599
+ ),
600
+ },
601
+ ensure_ascii=False,
602
+ ),
603
+ err=True,
604
+ )
605
+ return False
606
+
607
+ try:
608
+ opened = webbrowser.open(url)
609
+ except webbrowser.Error as exc:
610
+ click.echo(
611
+ json.dumps(
612
+ {
613
+ "ok": True,
614
+ "stage": "browser_failed",
615
+ "error": str(exc),
616
+ "login_url": url,
617
+ "hint": (
618
+ "Could not auto-open the browser. Open this URL "
619
+ "manually, or run `oed auth login --manual`."
620
+ ),
621
+ },
622
+ ensure_ascii=False,
623
+ ),
624
+ err=True,
625
+ )
626
+ return False
627
+
628
+ if not opened:
629
+ click.echo(
630
+ json.dumps(
631
+ {
632
+ "ok": True,
633
+ "stage": "browser_unavailable",
634
+ "login_url": url,
635
+ },
636
+ ensure_ascii=False,
637
+ ),
638
+ err=True,
639
+ )
640
+ return False
641
+
642
+ return True
643
+
644
+
645
+ # ---------------------------------------------------------------------------
646
+ # Clipboard helper (RFC 8628 §3.3 user_code copy)
647
+ # ---------------------------------------------------------------------------
648
+
649
+
650
+ def _copy_to_clipboard(text: str) -> bool:
651
+ """Copy ``text`` to the OS clipboard. Returns True on success.
652
+
653
+ Tries in order: ``wl-copy`` (Wayland), ``xclip -sel c`` (X11), ``xsel``
654
+ (X11 fallback), ``pbcopy`` (macOS), ``clip`` (Windows). Stdlib only.
655
+ """
656
+
657
+ candidates: list[list[str]] = [
658
+ ["wl-copy"],
659
+ ["xclip", "-selection", "clipboard"],
660
+ ["xsel", "--clipboard", "--input"],
661
+ ["pbcopy"],
662
+ ["clip"],
663
+ ]
664
+ encoded = text.encode("utf-8")
665
+ for cmd in candidates:
666
+ try:
667
+ subprocess.run(cmd, input=encoded, check=True, timeout=2)
668
+ return True
669
+ except (
670
+ FileNotFoundError,
671
+ subprocess.SubprocessError,
672
+ subprocess.TimeoutExpired,
673
+ ):
674
+ continue
675
+ return False
676
+
677
+
678
+ # ---------------------------------------------------------------------------
679
+ # Device-flow login (RFC 8628 via MSAL Python)
680
+ # ---------------------------------------------------------------------------
681
+
682
+
683
+ def device_login(
684
+ *,
685
+ scope: list[str] | None = None,
686
+ open_browser: bool = True,
687
+ copy_code: bool = True,
688
+ ) -> dict[str, Any] | None:
689
+ """Run RFC 8628 device authorization grant.
690
+
691
+ Returns dict with ``access_token`` (and optional ``refresh_token``) on
692
+ success; ``None`` on failure or cancellation. Prints stage JSON to stdout
693
+ and human prompts to stderr. The caller is responsible for persisting the
694
+ resulting MSAL token cache via :func:`save_msal_auth`.
695
+ """
696
+
697
+ client_id = get_client_id()
698
+ device_url = get_device_url()
699
+
700
+ cache = msal.SerializableTokenCache()
701
+ existing = load_auth()
702
+ if existing and existing.get("msal_cache"):
703
+ with contextlib.suppress(Exception):
704
+ cache.deserialize(existing["msal_cache"])
705
+
706
+ app = msal.PublicClientApplication(
707
+ client_id=client_id,
708
+ oidc_authority=device_url, # non-Azure OIDC discovery
709
+ token_cache=cache,
710
+ instance_discovery=False, # openEuler is not Azure; skip Azure domain check
711
+ )
712
+
713
+ # If OIDC discovery didn't provide device_authorization_endpoint,
714
+ # inject it from defaults.toml (oneid doesn't publish it in discovery).
715
+ # MSAL stores it in two places: authority attribute AND client.configuration
716
+ # dict (the latter is what initiate_device_flow actually reads).
717
+ device_auth_url = _get_device_authorization_url()
718
+ if device_auth_url:
719
+ authority = getattr(app, "authority", None)
720
+ if authority and not getattr(authority, "device_authorization_endpoint", None):
721
+ authority.device_authorization_endpoint = device_auth_url
722
+ client = getattr(app, "client", None)
723
+ cfg = getattr(client, "configuration", None)
724
+ if isinstance(cfg, dict) and not cfg.get("device_authorization_endpoint"):
725
+ cfg["device_authorization_endpoint"] = device_auth_url
726
+
727
+ flow = app.initiate_device_flow(scopes=scope if scope is not None else get_scopes())
728
+ if not flow or "user_code" not in flow:
729
+ err = (flow or {}).get("error_description") or (flow or {}).get("error") or "unknown"
730
+ click.echo(
731
+ json.dumps(
732
+ {
733
+ "ok": False,
734
+ "stage": "device_flow_init_failed",
735
+ "error": str(err),
736
+ "hint": (
737
+ "openEuler usercenter may not yet support device "
738
+ "authorization grant. Try `oed auth login --manual` "
739
+ "or set OED_TOKEN=<bearer>."
740
+ ),
741
+ },
742
+ ensure_ascii=False,
743
+ ),
744
+ err=True,
745
+ )
746
+ return None
747
+
748
+ user_code = flow["user_code"]
749
+ verification_uri = flow.get("verification_uri", "")
750
+ expires_in = int(flow.get("expires_in", 1800))
751
+ interval = int(flow.get("interval", 5))
752
+
753
+ click.echo(
754
+ json.dumps(
755
+ {
756
+ "ok": True,
757
+ "stage": "device_code_issued",
758
+ "user_code": user_code,
759
+ "verification_uri": verification_uri,
760
+ "verification_uri_complete": flow.get("verification_uri_complete"),
761
+ "expires_in": expires_in,
762
+ "interval": interval,
763
+ },
764
+ ensure_ascii=False,
765
+ )
766
+ )
767
+
768
+ # stderr human prompts
769
+ click.echo(
770
+ flow.get("message")
771
+ or f"Visit {verification_uri} and enter code: {user_code}",
772
+ err=True,
773
+ )
774
+ if copy_code and _copy_to_clipboard(user_code):
775
+ click.echo("(user_code copied to clipboard)", err=True)
776
+
777
+ # Best-effort auto-open the verification URL.
778
+ if open_browser and verification_uri:
779
+ _try_open_browser(verification_uri)
780
+
781
+ # MSAL handles slow_down + anti-fast-poll + 5xx-keep-polling internally.
782
+ # Its default exit_condition uses flow["expires_at"], set in
783
+ # initiate_device_flow as ``time.time() + expires_in``.
784
+ result = app.acquire_token_by_device_flow(flow)
785
+ # Thread user_code through so _fetch_user_allowlist can send it as
786
+ # ?user_code=... (oneid-specific, see _fetch_user_allowlist).
787
+ return _finalize_device_result(result, cache, user_code=user_code)
788
+
789
+
790
+ def _summarize_token_response(result: dict[str, Any]) -> dict[str, Any]:
791
+ """Project MSAL device-flow result to a minimal user-facing dict.
792
+
793
+ Surfaces only the fields a user / agent cares about at login time:
794
+ whether the server granted a token, what scopes survived round-trip,
795
+ and when it expires. Token values stay in ``auth.json`` only — see
796
+ ``oed auth status`` for a redacted fingerprint.
797
+ """
798
+ return {
799
+ "ok": True,
800
+ "stage": "token_received",
801
+ "token_type": result.get("token_type"),
802
+ "scope": result.get("scope"),
803
+ "expires_in": result.get("expires_in"),
804
+ "has_access_token": bool(result.get("access_token")),
805
+ "has_refresh_token": bool(result.get("refresh_token")),
806
+ "has_id_token": bool(result.get("id_token")),
807
+ }
808
+
809
+
810
+ def _fetch_user_allowlist(
811
+ access_token: str,
812
+ user_code: str | None = None,
813
+ ) -> list[str] | None:
814
+ """GET the per-user CLI service allow-list from oneid.
815
+
816
+ Called ONCE per login (right after /token returns) by
817
+ :func:`_finalize_device_result`. The response is cached in
818
+ ``auth.json`` and consulted locally on every subsequent CLI invocation —
819
+ no per-call HTTP. ``access_token`` is sent as ``Authorization: Bearer``.
820
+
821
+ ``user_code`` (when supplied) is sent as a ``user_code`` query param.
822
+ This is a **oneid-specific deviation** from RFC 8628: oneid's
823
+ ``/device/user-data`` test endpoint uses the public user-facing code
824
+ (the ABCD-EFGH string shown in the browser) to look up the user, rather
825
+ than the bearer token's ``sub`` claim. RFC 8628 §3.5 considers user_code
826
+ a public display value (it can be shown to other humans at a shared
827
+ device), so passing it over a TLS connection is acceptable, but the
828
+ bearer token alone should normally suffice. Kept as a temporary
829
+ accommodation for the test deployment; revisit when oneid aligns with
830
+ RFC 8628 (drop the ``user_code`` param).
831
+
832
+ Returns:
833
+ ``list[str]`` of allowed service names on success.
834
+ ``None`` on any failure (network / non-2xx / parse / missing field) —
835
+ the caller treats ``None`` as "no allow-list available, don't block"
836
+ (fail-open).
837
+
838
+ Response shape tolerance:
839
+ oneid's current envelope wraps the payload as
840
+ ``{"msg": {...}, "code": 200, "data": {"data": "a,b,c"}}``
841
+ (two layers of ``data``). The parser peels both layers and also
842
+ accepts the flat shape ``{"data": "a,b,c"}`` in case the envelope
843
+ is dropped in a future revision. Anything else fails open.
844
+
845
+ The endpoint URL comes from ``defaults.toml [oauth].cli_user_data_url``
846
+ with an ``OED_USER_DATA_URL`` env override (useful for fork builds).
847
+
848
+ Each branch emits a one-line diagnostic to stderr (keyed by ``stage``)
849
+ so an operator running ``oed auth login`` can see what the server
850
+ returned without grepping the source. Stdout stays reserved for the
851
+ success-JSON envelope — these prints never break ``| jq``.
852
+ """
853
+ url = os.environ.get("OED_USER_DATA_URL") or _get_user_data_url()
854
+ if not url:
855
+ click.echo(
856
+ json.dumps(
857
+ {"ok": True, "stage": "user_data_skipped", "reason": "no_user_data_url"},
858
+ ensure_ascii=False,
859
+ ),
860
+ err=True,
861
+ )
862
+ return None
863
+ # oneid /device/user-data expects ?user_code=<ABCD-EFGH> as a query param.
864
+ # When ``user_code`` is None (manual flow path), we still call without it —
865
+ # manual-login tokens are unlikely to be recognized by oneid's user-data
866
+ # endpoint, but sending the call surfaces a server-side error rather than
867
+ # silently skipping.
868
+ params: dict[str, str] = {}
869
+ if user_code:
870
+ params["user_code"] = user_code
871
+ try:
872
+ resp = httpx.get(
873
+ url,
874
+ params=params or None,
875
+ headers={"Authorization": f"Bearer {access_token}"},
876
+ timeout=10,
877
+ )
878
+ resp.raise_for_status()
879
+ except httpx.HTTPStatusError as exc:
880
+ # Server returned 4xx/5xx — surface status + a short body preview so
881
+ # an operator can tell apart auth (401/403) from missing endpoint
882
+ # (404) from upstream errors (5xx) without re-running the curl.
883
+ click.echo(
884
+ json.dumps(
885
+ {
886
+ "ok": False,
887
+ "stage": "user_data_fetch_failed",
888
+ "url": url,
889
+ "status": exc.response.status_code,
890
+ "reason": exc.response.reason_phrase,
891
+ "body_preview": exc.response.text[:512],
892
+ },
893
+ ensure_ascii=False,
894
+ ),
895
+ err=True,
896
+ )
897
+ return None
898
+ except httpx.HTTPError:
899
+ # Connect / read / DNS / timeout — no response object.
900
+ click.echo(
901
+ json.dumps(
902
+ {"ok": False, "stage": "user_data_fetch_failed", "url": url},
903
+ ensure_ascii=False,
904
+ ),
905
+ err=True,
906
+ )
907
+ return None
908
+
909
+ raw_body = resp.text
910
+ try:
911
+ body = resp.json()
912
+ except ValueError:
913
+ click.echo(
914
+ json.dumps(
915
+ {
916
+ "ok": False,
917
+ "stage": "user_data_parse_failed",
918
+ "url": url,
919
+ "status": resp.status_code,
920
+ "body_preview": raw_body[:512],
921
+ },
922
+ ensure_ascii=False,
923
+ ),
924
+ err=True,
925
+ )
926
+ return None
927
+ # oneid's /device/user-data wraps the payload in an envelope:
928
+ # {"msg": {...}, "code": 200, "data": {"data": "search,cve"}}
929
+ # The CSV string lives at ``body.data.data`` (two levels). Tolerate the
930
+ # flat shape ``{"data": "search,cve"}`` too in case the envelope is
931
+ # dropped in a future revision. Anything else → None (fail-open).
932
+ data: Any = None
933
+ if isinstance(body, dict):
934
+ outer = body.get("data")
935
+ if isinstance(outer, str):
936
+ data = outer # flat shape
937
+ elif isinstance(outer, dict):
938
+ inner = outer.get("data")
939
+ if isinstance(inner, str):
940
+ data = inner # enveloped shape
941
+ if not isinstance(data, str):
942
+ click.echo(
943
+ json.dumps(
944
+ {
945
+ "ok": False,
946
+ "stage": "user_data_unexpected_shape",
947
+ "url": url,
948
+ "status": resp.status_code,
949
+ "body": body,
950
+ },
951
+ ensure_ascii=False,
952
+ ),
953
+ err=True,
954
+ )
955
+ return None
956
+ parsed = [s.strip() for s in data.split(",") if s.strip()]
957
+ click.echo(
958
+ json.dumps(
959
+ {
960
+ "ok": True,
961
+ "stage": "user_data_fetched",
962
+ "url": url,
963
+ "status": resp.status_code,
964
+ "raw_data_field": data,
965
+ "parsed_allowlist": parsed,
966
+ "count": len(parsed),
967
+ "sent_user_code_param": bool(user_code),
968
+ "response_envelope": "wrapped" if isinstance(body.get("data"), dict) else "flat",
969
+ },
970
+ ensure_ascii=False,
971
+ ),
972
+ err=True,
973
+ )
974
+ # Empty list is preserved (caller treats [] the same as None — fail-open).
975
+ return parsed
976
+
977
+
978
+ def _finalize_device_result(
979
+ result: dict[str, Any] | None,
980
+ cache: Any,
981
+ user_code: str | None = None,
982
+ ) -> dict[str, Any] | None:
983
+ """Process MSAL device-flow result: persist cache, emit stages, return dict.
984
+
985
+ ``user_code`` (the ABCD-EFGH display string from the device flow response)
986
+ is forwarded to :func:`_fetch_user_allowlist` as a query param because
987
+ oneid's /device/user-data endpoint uses it for user lookup. See
988
+ :func:`_fetch_user_allowlist` for the full note on this deviation from
989
+ RFC 8628.
990
+ """
991
+
992
+ if not result:
993
+ click.echo(
994
+ json.dumps(
995
+ {
996
+ "ok": False,
997
+ "stage": "device_code_timeout",
998
+ "hint": "Run `oed auth login` again.",
999
+ },
1000
+ ensure_ascii=False,
1001
+ ),
1002
+ err=True,
1003
+ )
1004
+ return None
1005
+
1006
+ if "access_token" in result:
1007
+ # Fetch per-user service allow-list from oneid (one-shot at login
1008
+ # success). Persist alongside the MSAL cache. ``None`` (network /
1009
+ # parse failure, or endpoint not configured) is a fail-open signal
1010
+ # — caller will not block any service.
1011
+ allowlist = _fetch_user_allowlist(result["access_token"], user_code=user_code)
1012
+ save_msal_auth(cache, allowlist=allowlist)
1013
+ summary = _summarize_token_response(result)
1014
+ summary["allowlist"] = allowlist
1015
+ click.echo(
1016
+ json.dumps(
1017
+ summary,
1018
+ ensure_ascii=False,
1019
+ )
1020
+ )
1021
+ return result
1022
+
1023
+ err = result.get("error") or "unknown"
1024
+ desc = result.get("error_description") or ""
1025
+ click.echo(
1026
+ json.dumps(
1027
+ {
1028
+ "ok": False,
1029
+ "stage": "device_token_error",
1030
+ "error": str(err),
1031
+ "error_description": str(desc),
1032
+ "hint": "Run `oed auth login` again.",
1033
+ },
1034
+ ensure_ascii=False,
1035
+ ),
1036
+ err=True,
1037
+ )
1038
+ return None
1039
+
1040
+
1041
+ # ---------------------------------------------------------------------------
1042
+ # Manual login (TTY paste; unchanged behavior from v0.4)
1043
+ # ---------------------------------------------------------------------------
1044
+
1045
+
1046
+ def _is_tty() -> bool:
1047
+ """True when stdout is a real terminal (not piped / redirected)."""
1048
+
1049
+ try:
1050
+ return os.isatty(1)
1051
+ except (ValueError, OSError):
1052
+ return False
1053
+
1054
+
1055
+ def manual_login() -> dict[str, Any] | None:
1056
+ """Prompt for a token + cookie on stdin. Fail to ``UserError`` when not a TTY."""
1057
+
1058
+ from .errors import UserError
1059
+
1060
+ if not _is_tty():
1061
+ raise UserError(
1062
+ "`oed auth login --manual` requires an interactive terminal. "
1063
+ "Pipe mode should use `oed auth token <token>` instead.",
1064
+ kind="not_tty",
1065
+ hint=(
1066
+ "Use `oed auth token <token>` to set the token directly from "
1067
+ "browser DevTools (Network → request headers → token)."
1068
+ ),
1069
+ )
1070
+
1071
+ click.echo("Manual login: paste credentials from your browser's DevTools.")
1072
+ click.echo("Network tab → request headers → look for `token` and `Cookie`.")
1073
+ token = click.prompt("token", hide_input=True)
1074
+ cookie = click.prompt("cookie (optional)", default="", hide_input=True)
1075
+ return {"token": token, "cookie": cookie or None}
1076
+
1077
+
1078
+ # ---------------------------------------------------------------------------
1079
+ # Internal helpers (file IO + MSAL cache extraction)
1080
+ # ---------------------------------------------------------------------------
1081
+
1082
+
1083
+ def _read_existing(path: Path) -> dict[str, Any]:
1084
+ """Read existing ``auth.json``; return empty dict if missing or corrupt."""
1085
+
1086
+ if not path.is_file():
1087
+ return {}
1088
+ try:
1089
+ return json.loads(path.read_text(encoding="utf-8"))
1090
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
1091
+ # Corrupt file — wrong encoding / truncated / half-written. Drop it
1092
+ # rather than crash the login flow. Caller treats {} as
1093
+ # unauthenticated, then a fresh save() overwrites the bad file.
1094
+ with contextlib.suppress(OSError):
1095
+ path.unlink()
1096
+ return {}
1097
+
1098
+
1099
+ def _atomic_write_json_plaintext(path: Path, data: dict[str, Any]) -> None:
1100
+ """Write ``data`` as JSON to ``path`` atomically with 0600 perms.
1101
+
1102
+ Plaintext fallback path used by :class:`_SecureStore` when ``keyring``
1103
+ is unreachable. Production callers go through
1104
+ :func:`save_auth` / :func:`save_msal_auth` / :func:`update_auth_from_response_headers`,
1105
+ not this helper directly.
1106
+ """
1107
+
1108
+ tmp = path.with_suffix(path.suffix + ".tmp")
1109
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
1110
+ with contextlib.suppress(OSError):
1111
+ os.chmod(tmp, 0o600)
1112
+ tmp.replace(path)
1113
+
1114
+
1115
+ def _synth_msal_cache_json(token: str, refresh_token: str | None) -> str:
1116
+ """Build a minimal MSAL cache JSON containing a single access_token.
1117
+
1118
+ MSAL's ``AccessToken`` map is keyed by a composite string (type, home
1119
+ account, env, client, scope) and the value is the entry dict directly —
1120
+ no extra nesting. Used by :func:`save_auth` so manual
1121
+ ``oed auth token <bearer>`` produces a cache file readable by
1122
+ :func:`get_token` / :func:`auth_headers_from_storage`.
1123
+
1124
+ Token values are written under the ``secret`` key to match the current
1125
+ MSAL :class:`SerializableTokenCache` schema (older MSAL used the
1126
+ map-specific ``access_token`` / ``refresh_token`` field names; the
1127
+ readers in :func:`_first_token_secret` accept both for back-compat).
1128
+ """
1129
+
1130
+ expires_on = int(time.time()) + TOKEN_MAX_AGE
1131
+ cache_dict: dict[str, Any] = {
1132
+ "AccessToken": {
1133
+ "manual::oed-cli:": {
1134
+ "credential_type": "AccessToken",
1135
+ "secret": token,
1136
+ "token_type": "Bearer",
1137
+ "expires_on": expires_on,
1138
+ "extended_expires_on": expires_on,
1139
+ }
1140
+ },
1141
+ "Account": {},
1142
+ "IdToken": {},
1143
+ "AppMetadata": {},
1144
+ }
1145
+ if refresh_token:
1146
+ cache_dict["RefreshToken"] = {
1147
+ "manual::oed-cli:": {"credential_type": "RefreshToken", "secret": refresh_token}
1148
+ }
1149
+ return json.dumps(cache_dict)
1150
+
1151
+
1152
+ def _first_token_secret(
1153
+ cache_json: str, map_name: str, legacy_field: str | None = None
1154
+ ) -> str | None:
1155
+ """Pull the freshest token value out of an MSAL cache ``map_name`` section.
1156
+
1157
+ MSAL's :class:`SerializableTokenCache` stores the token value under the
1158
+ key ``secret`` in every entry of ``AccessToken`` / ``RefreshToken`` /
1159
+ ``IdToken`` maps (this is the current MSAL schema — older versions used
1160
+ the map-specific field name ``access_token`` / ``refresh_token`` /
1161
+ ``id_token``). Read ``secret`` first, then ``legacy_field`` for backward
1162
+ compat with caches / test fixtures written to the old schema.
1163
+
1164
+ The cache accumulates one entry per (home_account, environment, client_id,
1165
+ scope) tuple — a re-login against a different environment (e.g. oneid test
1166
+ vs prod) leaves the old entry in place. Returning the *first* entry (dict
1167
+ insertion order) could therefore surface a stale token from the wrong
1168
+ environment. Pick the entry with the newest ``expires_on`` (fallback
1169
+ ``cached_at``) so the just-issued token wins; entries without a timestamp
1170
+ (legacy / manually synthesized caches) keep the original first-match
1171
+ behavior.
1172
+ """
1173
+
1174
+ if not cache_json:
1175
+ return None
1176
+ try:
1177
+ cache = json.loads(cache_json)
1178
+ except (json.JSONDecodeError, TypeError):
1179
+ return None
1180
+ section = cache.get(map_name)
1181
+ if not isinstance(section, dict):
1182
+ return None
1183
+
1184
+ def _token_of(entry: dict[str, Any]) -> str | None:
1185
+ token = entry.get("secret")
1186
+ if not isinstance(token, str) or not token:
1187
+ if legacy_field:
1188
+ token = entry.get(legacy_field)
1189
+ if not isinstance(token, str) or not token:
1190
+ return None
1191
+ return token
1192
+
1193
+ def _sort_key(entry: dict[str, Any]) -> float:
1194
+ # MSAL writes ``expires_on`` / ``cached_at`` as Unix-second ints (or
1195
+ # numeric strings). Anything unparseable sorts as -inf so timestamped
1196
+ # entries always win; an all-untimestamped section degrades to taking
1197
+ # the first entry (``max`` is stable on ties → first wins).
1198
+ for field in ("expires_on", "cached_at"):
1199
+ val = entry.get(field)
1200
+ if val is None:
1201
+ continue
1202
+ try:
1203
+ return float(val)
1204
+ except (TypeError, ValueError):
1205
+ continue
1206
+ return float("-inf")
1207
+
1208
+ best_token: str | None = None
1209
+ best_key = float("-inf")
1210
+ for entry in section.values():
1211
+ if not isinstance(entry, dict):
1212
+ continue
1213
+ token = _token_of(entry)
1214
+ if token is None:
1215
+ continue
1216
+ key = _sort_key(entry)
1217
+ if best_token is None or key > best_key:
1218
+ best_token = token
1219
+ best_key = key
1220
+ return best_token
1221
+
1222
+
1223
+ def _extract_access_token(cache_json: str) -> str | None:
1224
+ """Pull the freshest ``access_token`` out of an MSAL cache JSON blob."""
1225
+
1226
+ return _first_token_secret(cache_json, "AccessToken", legacy_field="access_token")
1227
+
1228
+
1229
+ def _extract_refresh_token(cache_json: str) -> str | None:
1230
+ """Pull the first ``refresh_token`` out of an MSAL cache JSON blob.
1231
+
1232
+ Mirrors :func:`_extract_access_token` but reads the ``RefreshToken`` map.
1233
+ Used by ``oed auth status`` — the refresh_token never lives at the
1234
+ auth.json top level, only inside the serialized MSAL cache.
1235
+ """
1236
+
1237
+ return _first_token_secret(cache_json, "RefreshToken", legacy_field="refresh_token")
1238
+
1239
+
1240
+ def _decode_jwt_claims(jwt: str) -> dict[str, Any] | None:
1241
+ """Decode the payload claims of a JWT without verifying signature."""
1242
+
1243
+ try:
1244
+ payload = jwt.split(".")[1]
1245
+ payload += "=" * (-len(payload) % 4)
1246
+ return json.loads(b64decode(payload.encode("ascii")).decode("utf-8"))
1247
+ except (IndexError, ValueError, TypeError):
1248
+ return None
1249
+
1250
+
1251
+ def _extract_id_token_claims(cache_json: str) -> dict[str, Any] | None:
1252
+ """Decode ``id_token`` claims from the MSAL cache, or ``None`` if absent.
1253
+
1254
+ Mirrors :func:`_extract_access_token` but reads the ``IdToken`` map MSAL
1255
+ populates when the token endpoint response carries an ``id_token``. When
1256
+ the IdP omits ``id_token`` (as oneid does unless OIDC id-token signing is
1257
+ enabled for the client), this map is empty and we return ``None``.
1258
+ """
1259
+
1260
+ id_tok = _first_token_secret(cache_json, "IdToken", legacy_field="id_token")
1261
+ if not id_tok:
1262
+ return None
1263
+ return _decode_jwt_claims(id_tok)
1264
+
1265
+
1266
+ def _msal_username() -> str | None:
1267
+ """Best-effort: read MSAL cache from disk, return ``username`` if any.
1268
+
1269
+ Falls back to the ``id_token`` claims (``preferred_username`` / ``email``)
1270
+ when MSAL did not populate the ``Account`` map — which happens when the
1271
+ IdP returns an ``id_token`` but MSAL's account extraction is skipped for
1272
+ non-Azure authorities.
1273
+ """
1274
+
1275
+ cache = msal.SerializableTokenCache()
1276
+ data = load_auth()
1277
+ if not (data and data.get("msal_cache")):
1278
+ return None
1279
+ with contextlib.suppress(Exception):
1280
+ cache.deserialize(data["msal_cache"])
1281
+ try:
1282
+ accounts = list(cache.search("Account"))
1283
+ except Exception:
1284
+ accounts = []
1285
+ if accounts:
1286
+ return accounts[0].get("username")
1287
+ # Fallback: pull a human-readable identifier straight out of the id_token.
1288
+ claims = _extract_id_token_claims(data.get("msal_cache") or "")
1289
+ if claims:
1290
+ return claims.get("preferred_username") or claims.get("email") or claims.get("name")
1291
+ return None
1292
+
1293
+
1294
+ # ---------------------------------------------------------------------------
1295
+ # Click sub-group
1296
+ # ---------------------------------------------------------------------------
1297
+
1298
+
1299
+ @click.group(name="auth")
1300
+ def auth_group() -> None:
1301
+ """Manage openEuler authentication state.
1302
+
1303
+ Default ``auth login`` uses RFC 8628 device authorization grant — no
1304
+ local HTTP server, works headless. Use ``--manual`` to paste a token
1305
+ from a terminal.
1306
+ """
1307
+
1308
+
1309
+ @auth_group.command("status")
1310
+ def auth_status() -> None:
1311
+ """Print login status as JSON. Token is redacted to a fingerprint."""
1312
+
1313
+ stored = load_auth()
1314
+ if not stored:
1315
+ click.echo(
1316
+ json.dumps(
1317
+ {"ok": True, "logged_in": False},
1318
+ ensure_ascii=False,
1319
+ )
1320
+ )
1321
+ return
1322
+
1323
+ token = get_token() or ""
1324
+ created_at = float(stored.get("created_at", 0))
1325
+ allowlist = stored.get("allowlist") if isinstance(stored, dict) else None
1326
+ if not isinstance(allowlist, list):
1327
+ allowlist = None
1328
+ payload = {
1329
+ "ok": True,
1330
+ "logged_in": bool(token),
1331
+ "token_present": bool(token),
1332
+ "token_fingerprint": _token_fingerprint(token) if token else "",
1333
+ "created_at": created_at,
1334
+ "expired": is_token_expired(stored),
1335
+ # None → never fetched (legacy auth.json, or fetch failed at login)
1336
+ # [] → user explicitly cleared in oneid (fail-open in dispatcher)
1337
+ # [...] → per-user allow-list, dispatcher blocks any service_name
1338
+ # not in the list.
1339
+ "allowlist": allowlist,
1340
+ }
1341
+ click.echo(json.dumps(payload, ensure_ascii=False, indent=2))
1342
+
1343
+
1344
+ @auth_group.command("token")
1345
+ @click.argument("token_value")
1346
+ @click.option(
1347
+ "--cookie",
1348
+ "-c",
1349
+ default="",
1350
+ help="Optional cookie string (e.g. 'name1=value1; name2=value2').",
1351
+ )
1352
+ def auth_token_cmd(token_value: str, cookie: str) -> None:
1353
+ """Save a token (and optionally a cookie) to the local auth file."""
1354
+
1355
+ path = save_auth(token_value, cookie=cookie or None)
1356
+ click.echo(
1357
+ json.dumps(
1358
+ {
1359
+ "ok": True,
1360
+ "path": str(path),
1361
+ "has_cookie": bool(cookie),
1362
+ },
1363
+ ensure_ascii=False,
1364
+ indent=2,
1365
+ )
1366
+ )
1367
+
1368
+
1369
+ @auth_group.command("logout")
1370
+ def auth_logout_cmd() -> None:
1371
+ """Clear the stored auth.json (logout)."""
1372
+
1373
+ cleared = clear_auth()
1374
+ click.echo(
1375
+ json.dumps(
1376
+ {
1377
+ "ok": True,
1378
+ "cleared": cleared,
1379
+ "path": str(auth_token_path()),
1380
+ },
1381
+ ensure_ascii=False,
1382
+ indent=2,
1383
+ )
1384
+ )
1385
+
1386
+
1387
+ def run_login(manual: bool) -> None:
1388
+ """Public entry for the top-level ``oed login`` shortcut.
1389
+
1390
+ Thin wrapper over :func:`_run_login` so :mod:`oed_cli.cli` can register
1391
+ a ``login`` command on the root group without reaching into private API.
1392
+ """
1393
+
1394
+ _run_login(manual)
1395
+
1396
+
1397
+ def _run_login(manual: bool) -> None:
1398
+ """Shared body for ``oed auth login`` and the top-level ``oed login`` shortcut.
1399
+
1400
+ Device-flow login (default) or manual paste (``manual=True``). Both entry
1401
+ points funnel through here so the stage JSON, persistence, and exit codes
1402
+ stay identical regardless of which command name the user typed.
1403
+ """
1404
+
1405
+ from .errors import UserError
1406
+
1407
+ if manual:
1408
+ try:
1409
+ creds = manual_login()
1410
+ except UserError as exc:
1411
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
1412
+ raise SystemExit(exc.code) from None
1413
+ if not creds:
1414
+ click.echo(
1415
+ json.dumps({"ok": False, "error": "manual_login_aborted"}, ensure_ascii=False),
1416
+ err=True,
1417
+ )
1418
+ raise SystemExit(1)
1419
+ token = creds.get("token")
1420
+ cookie = creds.get("cookie")
1421
+ refresh_token = None
1422
+ id_token = None
1423
+ else:
1424
+ # device_login() reads get_scopes() internally; pass nothing and let
1425
+ # it fall back to _BASE_SCOPES. Passing scope=[] would override the
1426
+ # default with an empty list — MSAL would then decorate it to just
1427
+ # the reserved 'openid profile offline_access' set, dropping email
1428
+ # and id_token from the wire request. Oneid would still accept the
1429
+ # flow, but the resulting token would have no id_token, no email
1430
+ # claim, and no refresh_token (offline_access comes from MSAL
1431
+ # decoration but the cached account metadata would be incomplete).
1432
+ result = device_login()
1433
+ if not result:
1434
+ click.echo(
1435
+ json.dumps({"ok": False, "error": "device_login_failed"}, ensure_ascii=False),
1436
+ err=True,
1437
+ )
1438
+ raise SystemExit(1)
1439
+ token = result.get("access_token")
1440
+ cookie = None
1441
+ refresh_token = result.get("refresh_token")
1442
+ id_token = result.get("id_token")
1443
+
1444
+ if not token:
1445
+ click.echo(
1446
+ json.dumps({"ok": False, "error": "no_token_in_response"}, ensure_ascii=False),
1447
+ err=True,
1448
+ )
1449
+ raise SystemExit(1)
1450
+
1451
+ # Both branches already persisted to auth.json; this is informational.
1452
+ path = auth_token_path()
1453
+
1454
+ click.echo(
1455
+ json.dumps(
1456
+ {
1457
+ "ok": True,
1458
+ "stage": "saved",
1459
+ "path": str(path),
1460
+ "has_cookie": bool(cookie),
1461
+ "has_refresh_token": bool(refresh_token),
1462
+ "has_id_token": bool(id_token),
1463
+ "token_fingerprint": _token_fingerprint(token),
1464
+ },
1465
+ ensure_ascii=False,
1466
+ indent=2,
1467
+ )
1468
+ )
1469
+
1470
+
1471
+ @auth_group.command("login")
1472
+ @click.option(
1473
+ "--manual",
1474
+ "-m",
1475
+ is_flag=True,
1476
+ help="Paste token + cookie from terminal instead of using device-flow.",
1477
+ )
1478
+ def auth_login_cmd(manual: bool) -> None:
1479
+ """Device-flow login (default) or manual paste (``--manual``)."""
1480
+
1481
+ _run_login(manual)
1482
+
1483
+
1484
+ __all__ = [
1485
+ "TOKEN_MAX_AGE",
1486
+ "_copy_to_clipboard",
1487
+ "_fetch_user_allowlist",
1488
+ "_has_display",
1489
+ "_token_fingerprint",
1490
+ "_try_open_browser",
1491
+ "auth_group",
1492
+ "auth_headers_from_storage",
1493
+ "clear_auth",
1494
+ "device_login",
1495
+ "extract_set_cookie",
1496
+ "get_client_id",
1497
+ "get_cookie",
1498
+ "get_device_url",
1499
+ "get_token",
1500
+ "is_token_expired",
1501
+ "load_auth",
1502
+ "load_defaults",
1503
+ "manual_login",
1504
+ "save_auth",
1505
+ "save_msal_auth",
1506
+ "run_login",
1507
+ "update_auth_from_response_headers",
1508
+ ]
1509
+
1510
+
1511
+ # ---------------------------------------------------------------------------
1512
+ # AtomGit (``ag``) personal-access-token storage
1513
+ # ---------------------------------------------------------------------------
1514
+ #
1515
+ # The AtomGit PAT is persisted through a *second* :class:`_SecureStore` instance
1516
+ # namespaced by ``username="ag"`` (the oneid credential uses ``"default"``), so
1517
+ # the two secrets never collide in the OS keystore and fall back to separate
1518
+ # plaintext files (``tokens/ag.json`` vs ``auth.json``). Storage semantics are
1519
+ # identical to the oneid credential: keyring (macOS Keychain / Windows DPAPI /
1520
+ # Linux SecretService) preferred, 0600 plaintext fallback otherwise. The public
1521
+ # API (``store_token`` / ``read_token`` / ``token_info`` / ``clear_token`` /
1522
+ # ``token_path``) stays stable so :mod:`oed_cli.main` and
1523
+ # :mod:`oed_cli.invoke` need no changes.
1524
+
1525
+ # Per-service AtomGit stores, keyed by ``service`` so a future general token
1526
+ # store can share this code. ``"ag"`` is the only wired service today.
1527
+ _ag_stores: dict[str, _SecureStore] = {}
1528
+
1529
+
1530
+ def _ag_store(service: str = "ag") -> _SecureStore:
1531
+ """Return the namespaced :class:`_SecureStore` for ``service``."""
1532
+
1533
+ store = _ag_stores.get(service)
1534
+ if store is None:
1535
+ store = _SecureStore(
1536
+ username=f"ag:{service}",
1537
+ fallback_path=lambda s=service: ag_token_path(s),
1538
+ )
1539
+ _ag_stores[service] = store
1540
+ return store
1541
+
1542
+
1543
+ def token_path(service: str = "ag") -> Path:
1544
+ """Return the plaintext-fallback path for ``service``'s AtomGit token.
1545
+
1546
+ The real secret prefers the OS keystore (see :class:`_SecureStore`); this
1547
+ path is only the 0600 fallback when keyring is unreachable. Exposed for
1548
+ diagnostics (``oed ag login --status``) and for ``oed cache`` isolation.
1549
+ """
1550
+
1551
+ return ag_token_path(service)
1552
+
1553
+
1554
+ def store_token(token: str, *, service: str = "ag") -> Path:
1555
+ """Persist ``token`` for ``service`` via :class:`_SecureStore`.
1556
+
1557
+ Writes through the keyring when reachable (OS-encrypted), otherwise a
1558
+ 0600 plaintext file. Returns the fallback path. Never raises on a
1559
+ keystore failure — it degrades to plaintext so ``oed ag login`` keeps
1560
+ working in headless / CI / Docker.
1561
+ """
1562
+
1563
+ if not token:
1564
+ from .errors import UserError
1565
+
1566
+ raise UserError("token must be a non-empty string", kind="missing_token")
1567
+ payload: dict[str, Any] = {
1568
+ "service": service,
1569
+ "access_token": token,
1570
+ "created_at": time.time(),
1571
+ }
1572
+ store = _ag_store(service)
1573
+ store.save(payload)
1574
+ return token_path(service)
1575
+
1576
+
1577
+ def read_token(service: str = "ag") -> str | None:
1578
+ """Return the stored AtomGit token for ``service``, or ``None``.
1579
+
1580
+ Any read failure (no token stored, corrupt entry, undecryptable blob)
1581
+ degrades silently to ``None`` so callers fall through to the
1582
+ missing-token path rather than crashing.
1583
+ """
1584
+
1585
+ stored = _ag_store(service).load()
1586
+ if not isinstance(stored, dict):
1587
+ return None
1588
+ token = stored.get("access_token")
1589
+ return token if isinstance(token, str) else None
1590
+
1591
+
1592
+ def token_backend(service: str = "ag") -> str:
1593
+ """The storage backend actually used for ``service``'s last write/read.
1594
+
1595
+ Reflects the cached verdict from the most recent :meth:`_SecureStore.save`
1596
+ / :meth:`_SecureStore.load` (``"keyring"`` / ``"plaintext"`` / ``"unprobed"``)
1597
+ without re-probing. Use it right after :func:`store_token` to tell the user
1598
+ *where* their token landed — the OS credential manager (no on-disk file) or
1599
+ the 0600 plaintext fallback (the file at :func:`token_path`).
1600
+ """
1601
+
1602
+ return _ag_store(service).backend_label()
1603
+
1604
+
1605
+ def token_info(service: str = "ag") -> dict[str, Any] | None:
1606
+ """Return ``{encryption, created_at}`` metadata for ``service``'s token.
1607
+
1608
+ ``encryption`` reports the backend actually used (``"keyring"`` or
1609
+ ``"plaintext"``), not a hand-rolled cipher marker. Returns ``None`` when
1610
+ no token is stored.
1611
+ """
1612
+
1613
+ store = _ag_store(service)
1614
+ stored = store.load()
1615
+ if not isinstance(stored, dict):
1616
+ return None
1617
+ return {
1618
+ "encryption": store.backend_label(),
1619
+ "created_at": stored.get("created_at"),
1620
+ }
1621
+
1622
+
1623
+ def clear_token(service: str = "ag") -> bool:
1624
+ """Delete ``service``'s stored token from both backends; return if set."""
1625
+
1626
+ store = _ag_store(service)
1627
+ had_data = store.load() is not None
1628
+ store.clear()
1629
+ return had_data