auth_ephemeral.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Ephemeral authentication tokens and rate-limit events.
  2. These tables replace the module-level in-memory dicts in mfa.py, making
  3. the 2FA / OIDC flow compatible with multi-worker deployments and persistent
  4. across server restarts.
  5. Tables
  6. ------
  7. AuthEphemeralToken
  8. Short-lived, single-use tokens for:
  9. - pre_auth : issued after password check, consumed when 2FA is verified
  10. - oidc_state : CSRF nonce for the OIDC authorization-code flow
  11. - oidc_exchange : short bridge token from the OIDC callback to the SPA
  12. AuthRateLimitEvent
  13. Timestamped events used for sliding-window rate limiting:
  14. - 2fa_attempt : each failed 2FA verification attempt
  15. - email_send : each OTP email sent (prevents email flooding)
  16. """
  17. from __future__ import annotations
  18. from datetime import datetime, timezone
  19. from enum import Enum
  20. from sqlalchemy import DateTime, Integer, String
  21. from sqlalchemy.orm import Mapped, mapped_column
  22. from backend.app.core.database import Base
  23. class TokenType(str, Enum):
  24. """T3: Enumerated token types for AuthEphemeralToken.token_type.
  25. Using str-based Enum keeps the stored values human-readable and
  26. backward-compatible with existing rows.
  27. """
  28. PRE_AUTH = "pre_auth"
  29. OIDC_STATE = "oidc_state"
  30. OIDC_EXCHANGE = "oidc_exchange"
  31. PASSWORD_RESET = "password_reset"
  32. EMAIL_OTP_SETUP = "email_otp_setup"
  33. SLICER_DOWNLOAD = "slicer_download"
  34. CONNECT_CODE = "connect_code"
  35. # Written as bare strings where they are used; listed here so every kind is
  36. # known (see test_token_outlived_session).
  37. WEBSOCKET = "websocket"
  38. CAMERA_STREAM = "camera_stream"
  39. MEDIA = "media"
  40. REVOKED_JTI = "revoked_jti" # the logout list, not a credential
  41. class EventType(str, Enum):
  42. """T3: Enumerated event types for AuthRateLimitEvent.event_type.
  43. Using str-based Enum keeps the stored values human-readable and
  44. backward-compatible with existing rows.
  45. """
  46. TWO_FA_ATTEMPT = "2fa_attempt"
  47. EMAIL_SEND = "email_send"
  48. LOGIN_ATTEMPT = "login_attempt"
  49. LOGIN_IP = "login_ip"
  50. PASSWORD_RESET_SEND = "password_reset_send"
  51. PASSWORD_RESET_IP = "password_reset_ip"
  52. CONNECT_TOKEN_CLIENT = "connect_client"
  53. CONNECT_TOKEN_IP = "connect_ip"
  54. class AuthEphemeralToken(Base):
  55. """Single-use, time-limited token for pre-auth / OIDC flows."""
  56. __tablename__ = "auth_ephemeral_tokens"
  57. id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
  58. token: Mapped[str] = mapped_column(String(128), unique=True, nullable=False, index=True)
  59. token_type: Mapped[str] = mapped_column(String(20), nullable=False) # 'pre_auth' | 'oidc_state' | 'oidc_exchange'
  60. # pre_auth + oidc_exchange: which user this session belongs to
  61. username: Mapped[str | None] = mapped_column(String(150), nullable=True)
  62. # oidc_state: which provider initiated the flow
  63. provider_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  64. # camera_stream + websocket: the API key that minted the token, when one
  65. # did, so the token carries that key's printer scope (#1727)
  66. api_key_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  67. # oidc_state: replay-protection nonce embedded in the ID token
  68. nonce: Mapped[str | None] = mapped_column(String(128), nullable=True)
  69. # oidc_state: PKCE code verifier (S256 method)
  70. code_verifier: Mapped[str | None] = mapped_column(String(128), nullable=True)
  71. # pre_auth: HttpOnly cookie value bound to this token to prevent token theft
  72. # (XSS can read JS memory but cannot read HttpOnly cookies).
  73. challenge_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
  74. expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
  75. created_at: Mapped[datetime] = mapped_column(
  76. DateTime,
  77. nullable=False,
  78. default=lambda: datetime.now(timezone.utc),
  79. )
  80. # ------------------------------------------------------------------
  81. # T1: Classmethod factories — enforce required fields per token type
  82. # and prevent accidentally leaving optional fields at their defaults.
  83. # ------------------------------------------------------------------
  84. @classmethod
  85. def new_pre_auth(
  86. cls,
  87. token: str,
  88. username: str,
  89. expires_at: datetime,
  90. challenge_id: str | None = None,
  91. ) -> AuthEphemeralToken:
  92. """Create a pre-auth token (issued after password check, before 2FA)."""
  93. return cls(
  94. token=token,
  95. token_type=TokenType.PRE_AUTH,
  96. username=username,
  97. expires_at=expires_at,
  98. challenge_id=challenge_id,
  99. )
  100. @classmethod
  101. def new_oidc_state(
  102. cls,
  103. token: str,
  104. provider_id: int,
  105. nonce: str,
  106. code_verifier: str,
  107. expires_at: datetime,
  108. ) -> AuthEphemeralToken:
  109. """Create an OIDC state token (CSRF protection + PKCE for authorize redirect)."""
  110. return cls(
  111. token=token,
  112. token_type=TokenType.OIDC_STATE,
  113. provider_id=provider_id,
  114. nonce=nonce,
  115. code_verifier=code_verifier,
  116. expires_at=expires_at,
  117. )
  118. @classmethod
  119. def new_oidc_exchange(
  120. cls,
  121. token: str,
  122. username: str,
  123. expires_at: datetime,
  124. ) -> AuthEphemeralToken:
  125. """Create an OIDC exchange token (bridge from callback to SPA)."""
  126. return cls(
  127. token=token,
  128. token_type=TokenType.OIDC_EXCHANGE,
  129. username=username,
  130. expires_at=expires_at,
  131. )
  132. @classmethod
  133. def new_password_reset(
  134. cls,
  135. token: str,
  136. username: str,
  137. expires_at: datetime,
  138. ) -> AuthEphemeralToken:
  139. """Create a password-reset token (single-use link emailed to the user)."""
  140. return cls(
  141. token=token,
  142. token_type=TokenType.PASSWORD_RESET,
  143. username=username,
  144. expires_at=expires_at,
  145. )
  146. @classmethod
  147. def new_email_otp_setup(
  148. cls,
  149. token: str,
  150. username: str,
  151. code_hash: str,
  152. expires_at: datetime,
  153. ) -> AuthEphemeralToken:
  154. """Create an email-OTP setup token.
  155. The ``code_hash`` is stored in the ``nonce`` column (field reuse
  156. documented inline in the enable_email_otp endpoint).
  157. """
  158. return cls(
  159. token=token,
  160. token_type=TokenType.EMAIL_OTP_SETUP,
  161. username=username,
  162. nonce=code_hash,
  163. expires_at=expires_at,
  164. )
  165. @classmethod
  166. def new_connect_code(
  167. cls,
  168. code_hash: str,
  169. username: str,
  170. app_id: int,
  171. code_challenge: str,
  172. expires_at: datetime,
  173. created_at: datetime | None = None,
  174. ) -> AuthEphemeralToken:
  175. """Create a connected-app authorization code.
  176. Only the SHA-256 of the code is stored (``token``), so a database read
  177. does not yield a usable code. Field reuse: ``provider_id`` holds the
  178. connected app's id and ``nonce`` the PKCE S256 challenge.
  179. """
  180. return cls(
  181. token=code_hash,
  182. token_type=TokenType.CONNECT_CODE,
  183. username=username,
  184. provider_id=app_id,
  185. nonce=code_challenge,
  186. expires_at=expires_at,
  187. # When the minting session began (core/auth.session_dated), if given
  188. **({"created_at": created_at} if created_at is not None else {}),
  189. )
  190. class AuthRateLimitEvent(Base):
  191. """Timestamped events used for sliding-window rate limiting."""
  192. __tablename__ = "auth_rate_limit_events"
  193. id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
  194. username: Mapped[str] = mapped_column(String(150), nullable=False, index=True)
  195. event_type: Mapped[str] = mapped_column(String(20), nullable=False) # '2fa_attempt' | 'email_send'
  196. occurred_at: Mapped[datetime] = mapped_column(
  197. DateTime,
  198. nullable=False,
  199. default=lambda: datetime.now(timezone.utc),
  200. )