auth_ephemeral.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. class EventType(str, Enum):
  36. """T3: Enumerated event types for AuthRateLimitEvent.event_type.
  37. Using str-based Enum keeps the stored values human-readable and
  38. backward-compatible with existing rows.
  39. """
  40. TWO_FA_ATTEMPT = "2fa_attempt"
  41. EMAIL_SEND = "email_send"
  42. LOGIN_ATTEMPT = "login_attempt"
  43. LOGIN_IP = "login_ip"
  44. PASSWORD_RESET_SEND = "password_reset_send"
  45. PASSWORD_RESET_IP = "password_reset_ip"
  46. CONNECT_TOKEN_CLIENT = "connect_client"
  47. CONNECT_TOKEN_IP = "connect_ip"
  48. class AuthEphemeralToken(Base):
  49. """Single-use, time-limited token for pre-auth / OIDC flows."""
  50. __tablename__ = "auth_ephemeral_tokens"
  51. id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
  52. token: Mapped[str] = mapped_column(String(128), unique=True, nullable=False, index=True)
  53. token_type: Mapped[str] = mapped_column(String(20), nullable=False) # 'pre_auth' | 'oidc_state' | 'oidc_exchange'
  54. # pre_auth + oidc_exchange: which user this session belongs to
  55. username: Mapped[str | None] = mapped_column(String(150), nullable=True)
  56. # oidc_state: which provider initiated the flow
  57. provider_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  58. # oidc_state: replay-protection nonce embedded in the ID token
  59. nonce: Mapped[str | None] = mapped_column(String(128), nullable=True)
  60. # oidc_state: PKCE code verifier (S256 method)
  61. code_verifier: Mapped[str | None] = mapped_column(String(128), nullable=True)
  62. # pre_auth: HttpOnly cookie value bound to this token to prevent token theft
  63. # (XSS can read JS memory but cannot read HttpOnly cookies).
  64. challenge_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
  65. expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
  66. created_at: Mapped[datetime] = mapped_column(
  67. DateTime(timezone=True),
  68. nullable=False,
  69. default=lambda: datetime.now(timezone.utc),
  70. )
  71. # ------------------------------------------------------------------
  72. # T1: Classmethod factories — enforce required fields per token type
  73. # and prevent accidentally leaving optional fields at their defaults.
  74. # ------------------------------------------------------------------
  75. @classmethod
  76. def new_pre_auth(
  77. cls,
  78. token: str,
  79. username: str,
  80. expires_at: datetime,
  81. challenge_id: str | None = None,
  82. ) -> AuthEphemeralToken:
  83. """Create a pre-auth token (issued after password check, before 2FA)."""
  84. return cls(
  85. token=token,
  86. token_type=TokenType.PRE_AUTH,
  87. username=username,
  88. expires_at=expires_at,
  89. challenge_id=challenge_id,
  90. )
  91. @classmethod
  92. def new_oidc_state(
  93. cls,
  94. token: str,
  95. provider_id: int,
  96. nonce: str,
  97. code_verifier: str,
  98. expires_at: datetime,
  99. ) -> AuthEphemeralToken:
  100. """Create an OIDC state token (CSRF protection + PKCE for authorize redirect)."""
  101. return cls(
  102. token=token,
  103. token_type=TokenType.OIDC_STATE,
  104. provider_id=provider_id,
  105. nonce=nonce,
  106. code_verifier=code_verifier,
  107. expires_at=expires_at,
  108. )
  109. @classmethod
  110. def new_oidc_exchange(
  111. cls,
  112. token: str,
  113. username: str,
  114. expires_at: datetime,
  115. ) -> AuthEphemeralToken:
  116. """Create an OIDC exchange token (bridge from callback to SPA)."""
  117. return cls(
  118. token=token,
  119. token_type=TokenType.OIDC_EXCHANGE,
  120. username=username,
  121. expires_at=expires_at,
  122. )
  123. @classmethod
  124. def new_password_reset(
  125. cls,
  126. token: str,
  127. username: str,
  128. expires_at: datetime,
  129. ) -> AuthEphemeralToken:
  130. """Create a password-reset token (single-use link emailed to the user)."""
  131. return cls(
  132. token=token,
  133. token_type=TokenType.PASSWORD_RESET,
  134. username=username,
  135. expires_at=expires_at,
  136. )
  137. @classmethod
  138. def new_email_otp_setup(
  139. cls,
  140. token: str,
  141. username: str,
  142. code_hash: str,
  143. expires_at: datetime,
  144. ) -> AuthEphemeralToken:
  145. """Create an email-OTP setup token.
  146. The ``code_hash`` is stored in the ``nonce`` column (field reuse
  147. documented inline in the enable_email_otp endpoint).
  148. """
  149. return cls(
  150. token=token,
  151. token_type=TokenType.EMAIL_OTP_SETUP,
  152. username=username,
  153. nonce=code_hash,
  154. expires_at=expires_at,
  155. )
  156. @classmethod
  157. def new_connect_code(
  158. cls,
  159. code_hash: str,
  160. username: str,
  161. app_id: int,
  162. code_challenge: str,
  163. expires_at: datetime,
  164. ) -> AuthEphemeralToken:
  165. """Create a connected-app authorization code.
  166. Only the SHA-256 of the code is stored (``token``), so a database read
  167. does not yield a usable code. Field reuse: ``provider_id`` holds the
  168. connected app's id and ``nonce`` the PKCE S256 challenge.
  169. """
  170. return cls(
  171. token=code_hash,
  172. token_type=TokenType.CONNECT_CODE,
  173. username=username,
  174. provider_id=app_id,
  175. nonce=code_challenge,
  176. expires_at=expires_at,
  177. )
  178. class AuthRateLimitEvent(Base):
  179. """Timestamped events used for sliding-window rate limiting."""
  180. __tablename__ = "auth_rate_limit_events"
  181. id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
  182. username: Mapped[str] = mapped_column(String(150), nullable=False, index=True)
  183. event_type: Mapped[str] = mapped_column(String(20), nullable=False) # '2fa_attempt' | 'email_send'
  184. occurred_at: Mapped[datetime] = mapped_column(
  185. DateTime(timezone=True),
  186. nullable=False,
  187. default=lambda: datetime.now(timezone.utc),
  188. )