auth_ephemeral.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. # camera_stream + websocket: the API key that minted the token, when one
  59. # did, so the token carries that key's printer scope (#1727)
  60. api_key_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  61. # oidc_state: replay-protection nonce embedded in the ID token
  62. nonce: Mapped[str | None] = mapped_column(String(128), nullable=True)
  63. # oidc_state: PKCE code verifier (S256 method)
  64. code_verifier: Mapped[str | None] = mapped_column(String(128), nullable=True)
  65. # pre_auth: HttpOnly cookie value bound to this token to prevent token theft
  66. # (XSS can read JS memory but cannot read HttpOnly cookies).
  67. challenge_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
  68. expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
  69. created_at: Mapped[datetime] = mapped_column(
  70. DateTime(timezone=True),
  71. nullable=False,
  72. default=lambda: datetime.now(timezone.utc),
  73. )
  74. # ------------------------------------------------------------------
  75. # T1: Classmethod factories — enforce required fields per token type
  76. # and prevent accidentally leaving optional fields at their defaults.
  77. # ------------------------------------------------------------------
  78. @classmethod
  79. def new_pre_auth(
  80. cls,
  81. token: str,
  82. username: str,
  83. expires_at: datetime,
  84. challenge_id: str | None = None,
  85. ) -> AuthEphemeralToken:
  86. """Create a pre-auth token (issued after password check, before 2FA)."""
  87. return cls(
  88. token=token,
  89. token_type=TokenType.PRE_AUTH,
  90. username=username,
  91. expires_at=expires_at,
  92. challenge_id=challenge_id,
  93. )
  94. @classmethod
  95. def new_oidc_state(
  96. cls,
  97. token: str,
  98. provider_id: int,
  99. nonce: str,
  100. code_verifier: str,
  101. expires_at: datetime,
  102. ) -> AuthEphemeralToken:
  103. """Create an OIDC state token (CSRF protection + PKCE for authorize redirect)."""
  104. return cls(
  105. token=token,
  106. token_type=TokenType.OIDC_STATE,
  107. provider_id=provider_id,
  108. nonce=nonce,
  109. code_verifier=code_verifier,
  110. expires_at=expires_at,
  111. )
  112. @classmethod
  113. def new_oidc_exchange(
  114. cls,
  115. token: str,
  116. username: str,
  117. expires_at: datetime,
  118. ) -> AuthEphemeralToken:
  119. """Create an OIDC exchange token (bridge from callback to SPA)."""
  120. return cls(
  121. token=token,
  122. token_type=TokenType.OIDC_EXCHANGE,
  123. username=username,
  124. expires_at=expires_at,
  125. )
  126. @classmethod
  127. def new_password_reset(
  128. cls,
  129. token: str,
  130. username: str,
  131. expires_at: datetime,
  132. ) -> AuthEphemeralToken:
  133. """Create a password-reset token (single-use link emailed to the user)."""
  134. return cls(
  135. token=token,
  136. token_type=TokenType.PASSWORD_RESET,
  137. username=username,
  138. expires_at=expires_at,
  139. )
  140. @classmethod
  141. def new_email_otp_setup(
  142. cls,
  143. token: str,
  144. username: str,
  145. code_hash: str,
  146. expires_at: datetime,
  147. ) -> AuthEphemeralToken:
  148. """Create an email-OTP setup token.
  149. The ``code_hash`` is stored in the ``nonce`` column (field reuse
  150. documented inline in the enable_email_otp endpoint).
  151. """
  152. return cls(
  153. token=token,
  154. token_type=TokenType.EMAIL_OTP_SETUP,
  155. username=username,
  156. nonce=code_hash,
  157. expires_at=expires_at,
  158. )
  159. @classmethod
  160. def new_connect_code(
  161. cls,
  162. code_hash: str,
  163. username: str,
  164. app_id: int,
  165. code_challenge: str,
  166. expires_at: datetime,
  167. ) -> AuthEphemeralToken:
  168. """Create a connected-app authorization code.
  169. Only the SHA-256 of the code is stored (``token``), so a database read
  170. does not yield a usable code. Field reuse: ``provider_id`` holds the
  171. connected app's id and ``nonce`` the PKCE S256 challenge.
  172. """
  173. return cls(
  174. token=code_hash,
  175. token_type=TokenType.CONNECT_CODE,
  176. username=username,
  177. provider_id=app_id,
  178. nonce=code_challenge,
  179. expires_at=expires_at,
  180. )
  181. class AuthRateLimitEvent(Base):
  182. """Timestamped events used for sliding-window rate limiting."""
  183. __tablename__ = "auth_rate_limit_events"
  184. id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
  185. username: Mapped[str] = mapped_column(String(150), nullable=False, index=True)
  186. event_type: Mapped[str] = mapped_column(String(20), nullable=False) # '2fa_attempt' | 'email_send'
  187. occurred_at: Mapped[datetime] = mapped_column(
  188. DateTime(timezone=True),
  189. nullable=False,
  190. default=lambda: datetime.now(timezone.utc),
  191. )