native_flow.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. """Gateway-brokered RFC 8252 (OAuth 2.0 for Native Apps) authorization store.
  2. The desktop cannot be a direct OAuth client of the upstream IDP (the Portal
  3. ``client_id`` is per gateway and only accepts the gateway's ``/auth/callback``),
  4. so the gateway brokers: authorization server *to the desktop*, OAuth client
  5. *to the Portal*. Desktop PKCE pair (cv_d, cc_d) + state -> ``/auth/native/authorize``
  6. stashes a pending entry (:func:`register_pending`) keyed by an opaque
  7. ``broker_state`` riding in the gateway's own PKCE cookie -> upstream callback
  8. or password login mints a one-time code bound to cc_d (:func:`complete_pending`)
  9. -> desktop redeems it with cv_d at ``/auth/native/token`` (:func:`redeem_code`).
  10. PKCE binding, single use, short TTLs, 256-bit handles compared in constant time,
  11. no secret logging; in-memory, process-local, ``time.time`` patchable in tests.
  12. """
  13. from __future__ import annotations
  14. import base64
  15. import hashlib
  16. import hmac
  17. import secrets
  18. import threading
  19. import time
  20. from dataclasses import dataclass
  21. from typing import Dict, Optional
  22. from hermes_cli.dashboard_auth.base import Session
  23. _PENDING_TTL_SECONDS = 600 # whole interactive login (mirrors the PKCE cookie)
  24. _CODE_TTL_SECONDS = 120 # loopback redirect + immediate token POST only
  25. _MAX_ENTRIES = 256 # global cap so a misbehaving client cannot grow the store unbounded
  26. # Per-IP cap on PENDING entries: /auth/native/authorize is a public pre-auth route, so one
  27. # spammer must not fill the global store and lock out logins.
  28. _MAX_PENDING_PER_IP = 8
  29. _lock = threading.Lock()
  30. @dataclass
  31. class _Pending:
  32. """In-flight native authorization awaiting the upstream callback."""
  33. code_challenge: str # the DESKTOP's S256 challenge (cc_d), base64url no-pad
  34. redirect_uri: str # the desktop's loopback redirect (127.0.0.1:<port>/...)
  35. client_state: str # the desktop's own ``state`` (echoed back on redirect)
  36. client_ip: str # requester IP at authorize time (per-IP pending cap)
  37. expires_at: int
  38. @dataclass
  39. class _IssuedCode:
  40. """A minted one-time gateway authorization code bound to a Session."""
  41. code_challenge: str # cc_d — verified against cv_d at redemption
  42. session: Session
  43. expires_at: int
  44. _pending: dict[str, _Pending] = {} # broker_state -> _Pending
  45. _issued: dict[str, _IssuedCode] = {} # gw_code -> _IssuedCode
  46. class NativeFlowError(Exception):
  47. """Base for native-flow failures (bad/expired/replayed handle, PKCE fail)."""
  48. class PendingNotFound(NativeFlowError):
  49. """The broker_state is unknown or expired (login window lapsed)."""
  50. class CodeInvalid(NativeFlowError):
  51. """The gateway code is unknown, expired, already redeemed, or PKCE-mismatched."""
  52. def _s256(verifier: str) -> str:
  53. """RFC 7636 S256 transform: base64url(sha256(ascii(verifier))), no padding."""
  54. digest = hashlib.sha256(verifier.encode("ascii")).digest()
  55. return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
  56. def _gc_locked(now: int) -> None:
  57. """Drop expired pending + issued entries. Caller holds ``_lock``."""
  58. for store in (_pending, _issued):
  59. for k in [k for k, v in store.items() if v.expires_at < now]:
  60. store.pop(k, None)
  61. def _capacity_ok_locked() -> bool:
  62. return (len(_pending) + len(_issued)) < _MAX_ENTRIES
  63. def _now(now: Optional[int]) -> int:
  64. return int(time.time()) if now is None else now
  65. def _pop_pending_locked(broker_state: str, *, consume: bool) -> _Pending:
  66. """Look up (optionally consuming) a pending entry; :class:`PendingNotFound` if unknown."""
  67. entry = (_pending.pop if consume else _pending.get)(broker_state, None)
  68. if entry is None:
  69. raise PendingNotFound("unknown or expired native authorization")
  70. return entry
  71. def register_pending(
  72. *, code_challenge: str, redirect_uri: str, client_state: str, client_ip: str = "",
  73. now: Optional[int] = None) -> str:
  74. """Stash a pending native authorization; return an opaque ``broker_state``. ``code_challenge``
  75. is the DESKTOP's cc_d. Raises ``NativeFlowError`` (fail closed) at store capacity or when
  76. ``client_ip`` holds ``_MAX_PENDING_PER_IP`` entries."""
  77. now = _now(now)
  78. broker_state = secrets.token_urlsafe(32)
  79. with _lock:
  80. _gc_locked(now)
  81. if not _capacity_ok_locked():
  82. raise NativeFlowError("native-flow authorization store at capacity")
  83. per_ip = sum(1 for v in _pending.values() if v.client_ip == client_ip)
  84. if client_ip and per_ip >= _MAX_PENDING_PER_IP:
  85. raise NativeFlowError("too many pending native authorizations from this address")
  86. _pending[broker_state] = _Pending(
  87. code_challenge=code_challenge, redirect_uri=redirect_uri, client_state=client_state,
  88. client_ip=client_ip, expires_at=now + _PENDING_TTL_SECONDS)
  89. return broker_state
  90. def get_pending(broker_state: str, *, now: Optional[int] = None) -> _Pending:
  91. """Peek (without consuming) the pending authorization."""
  92. with _lock:
  93. _gc_locked(_now(now))
  94. return _pop_pending_locked(broker_state, consume=False)
  95. def complete_pending(broker_state: str, *, session: Session, now: Optional[int] = None) -> str:
  96. """Consume a pending authorization (single use) and mint a one-time gateway code bound to the
  97. desktop's challenge + ``session``."""
  98. now = _now(now)
  99. with _lock:
  100. _gc_locked(now)
  101. pending = _pop_pending_locked(broker_state, consume=True)
  102. if not _capacity_ok_locked():
  103. raise NativeFlowError("native-flow code store at capacity")
  104. gw_code = secrets.token_urlsafe(32)
  105. _issued[gw_code] = _IssuedCode(
  106. code_challenge=pending.code_challenge, session=session,
  107. expires_at=now + _CODE_TTL_SECONDS)
  108. return gw_code
  109. def redeem_code(*, code: str, code_verifier: str, now: Optional[int] = None) -> Session:
  110. """Verify PKCE + consume a gateway code; return the bound :class:`Session`. The entry is popped
  111. BEFORE the PKCE check so a wrong verifier cannot be retried (no oracle, no replay)."""
  112. now = _now(now)
  113. with _lock:
  114. _gc_locked(now)
  115. issued = _issued.pop(code, None)
  116. if issued is None:
  117. raise CodeInvalid("unknown, expired, or already-redeemed code")
  118. if issued.expires_at < now:
  119. raise CodeInvalid("code expired")
  120. if not hmac.compare_digest(issued.code_challenge, _s256(code_verifier)):
  121. raise CodeInvalid("PKCE verification failed")
  122. return issued.session
  123. def _reset_for_tests() -> None:
  124. """Test-only: drop all pending + issued state."""
  125. with _lock:
  126. _pending.clear()
  127. _issued.clear()