auth.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import secrets
  5. from datetime import datetime, timedelta, timezone
  6. from typing import Annotated
  7. import jwt
  8. from fastapi import Depends, Header, HTTPException, status
  9. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  10. from jwt.exceptions import PyJWTError as JWTError
  11. from passlib.context import CryptContext
  12. from sqlalchemy import delete, func, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from sqlalchemy.orm import selectinload
  15. from backend.app.core.database import async_session, get_db
  16. from backend.app.core.permissions import Permission
  17. from backend.app.models.api_key import APIKey
  18. from backend.app.models.auth_ephemeral import AuthEphemeralToken, TokenType
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.user import User
  21. logger = logging.getLogger(__name__)
  22. # SETTINGS_READ is intentionally not denied — the SpoolBuddy kiosk reads settings
  23. # via API key (e.g. to sync the UI language).
  24. _APIKEY_DENIED_PERMISSIONS: frozenset[Permission] = frozenset(
  25. {
  26. Permission.SETTINGS_UPDATE,
  27. Permission.SETTINGS_BACKUP,
  28. Permission.SETTINGS_RESTORE,
  29. Permission.USERS_READ,
  30. Permission.USERS_CREATE,
  31. Permission.USERS_UPDATE,
  32. Permission.USERS_DELETE,
  33. Permission.GROUPS_READ,
  34. Permission.GROUPS_CREATE,
  35. Permission.GROUPS_UPDATE,
  36. Permission.GROUPS_DELETE,
  37. Permission.API_KEYS_CREATE,
  38. Permission.API_KEYS_UPDATE,
  39. Permission.API_KEYS_DELETE,
  40. Permission.API_KEYS_READ,
  41. Permission.GITHUB_BACKUP,
  42. Permission.GITHUB_RESTORE,
  43. Permission.FIRMWARE_UPDATE,
  44. }
  45. )
  46. def _check_apikey_permissions(perm_strings: list[str]) -> None:
  47. """Raise 403 if any required permission is admin-only (not accessible via API key)."""
  48. denied = _APIKEY_DENIED_PERMISSIONS.intersection(perm_strings)
  49. if denied:
  50. raise HTTPException(
  51. status_code=status.HTTP_403_FORBIDDEN,
  52. detail="API keys cannot be used for administrative operations",
  53. )
  54. def require_energy_cost_update():
  55. """Dependency for ``POST /settings/electricity-price`` (#1356).
  56. Bypasses the ``_APIKEY_DENIED_PERMISSIONS`` ``SETTINGS_UPDATE`` block for
  57. API keys that explicitly opt into ``can_update_energy_cost``. Full
  58. ``SETTINGS_UPDATE`` for API keys stays denied — this is a narrowly-scoped
  59. door for the Home Assistant dynamic-tariff use case documented in
  60. ``wiki/features/energy.md``, not a general settings-write capability.
  61. Accepts:
  62. * Auth disabled → always allowed (matches other settings routes)
  63. * JWT user with ``SETTINGS_UPDATE`` permission
  64. * API key with ``can_update_energy_cost = True``
  65. """
  66. async def permission_checker(
  67. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  68. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  69. ) -> User | None:
  70. async with async_session() as db:
  71. if not await is_auth_enabled(db):
  72. return None
  73. credentials_exception = HTTPException(
  74. status_code=status.HTTP_401_UNAUTHORIZED,
  75. detail="Could not validate credentials",
  76. headers={"WWW-Authenticate": "Bearer"},
  77. )
  78. # API key path — X-API-Key header or Bearer bb_xxx
  79. api_key_value: str | None = None
  80. if x_api_key:
  81. api_key_value = x_api_key
  82. elif credentials is not None and credentials.credentials.startswith("bb_"):
  83. api_key_value = credentials.credentials
  84. if api_key_value is not None:
  85. api_key = await _validate_api_key(db, api_key_value)
  86. if api_key is None:
  87. raise HTTPException(
  88. status_code=status.HTTP_401_UNAUTHORIZED,
  89. detail="Invalid API key",
  90. headers={"WWW-Authenticate": "Bearer"},
  91. )
  92. if not api_key.can_update_energy_cost:
  93. raise HTTPException(
  94. status_code=status.HTTP_403_FORBIDDEN,
  95. detail="API key does not have 'update_energy_cost' permission",
  96. )
  97. return None
  98. # JWT path
  99. if credentials is None:
  100. raise credentials_exception
  101. try:
  102. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  103. username: str = payload.get("sub")
  104. if username is None:
  105. raise credentials_exception
  106. jti: str | None = payload.get("jti")
  107. if not jti or await is_jti_revoked(jti):
  108. raise credentials_exception
  109. iat: int | float | None = payload.get("iat")
  110. except JWTError:
  111. raise credentials_exception
  112. user = await get_user_by_username(db, username)
  113. if user is None or not user.is_active:
  114. raise credentials_exception
  115. if not _is_token_fresh(iat, user):
  116. raise credentials_exception
  117. if not user.has_all_permissions(Permission.SETTINGS_UPDATE.value):
  118. raise HTTPException(
  119. status_code=status.HTTP_403_FORBIDDEN,
  120. detail=f"Missing required permissions: {Permission.SETTINGS_UPDATE.value}",
  121. )
  122. return user
  123. return permission_checker
  124. # Password hashing
  125. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  126. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  127. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  128. def _get_jwt_secret() -> str:
  129. """Get the JWT secret key from environment, file, or generate a new one.
  130. Priority:
  131. 1. JWT_SECRET_KEY environment variable
  132. 2. .jwt_secret file in data directory
  133. 3. Generate new random secret and save to file
  134. Returns:
  135. The JWT secret key
  136. """
  137. # 1. Check environment variable first
  138. env_secret = os.environ.get("JWT_SECRET_KEY")
  139. if env_secret:
  140. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  141. return env_secret
  142. # 2. Check for secret file in data directory
  143. from backend.app.core.paths import resolve_data_dir
  144. data_dir = resolve_data_dir()
  145. secret_file = data_dir / ".jwt_secret"
  146. if secret_file.exists():
  147. try:
  148. secret = secret_file.read_text().strip()
  149. if secret and len(secret) >= 32:
  150. logger.info("Using JWT secret from %s", secret_file)
  151. return secret
  152. except OSError as e:
  153. logger.warning("Failed to read JWT secret file: %s", e)
  154. # 3. Generate new random secret
  155. new_secret = secrets.token_urlsafe(64)
  156. # Try to save it
  157. try:
  158. data_dir.mkdir(parents=True, exist_ok=True)
  159. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  160. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  161. # and this is standard practice for self-hosted applications (same as .env files).
  162. secret_file.write_text(new_secret) # nosec B105
  163. # Restrict permissions (owner read/write only)
  164. secret_file.chmod(0o600)
  165. logger.info("Generated new JWT secret and saved to %s", secret_file)
  166. except OSError as e:
  167. logger.warning(
  168. "Could not save JWT secret to file (%s). "
  169. "Secret will be regenerated on restart, invalidating existing tokens. "
  170. "Set JWT_SECRET_KEY environment variable for persistence.",
  171. e,
  172. )
  173. return new_secret
  174. # JWT settings
  175. SECRET_KEY = _get_jwt_secret()
  176. ALGORITHM = "HS256"
  177. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours (M-2: reduced from 7 days)
  178. # HTTP Bearer token
  179. security = HTTPBearer(auto_error=False)
  180. # --- Slicer download tokens ---
  181. # Short-lived, single-use tokens for slicer protocol handlers that can't send
  182. # auth headers. Stored in AuthEphemeralToken (token_type=TokenType.SLICER_DOWNLOAD)
  183. # so they survive server restarts and work in multi-worker deployments (M-3).
  184. SLICER_TOKEN_EXPIRE_MINUTES = 5
  185. async def create_slicer_download_token(resource_type: str, resource_id: int) -> str:
  186. """Create a short-lived, single-use download token for slicer protocol handlers."""
  187. now = datetime.now(timezone.utc)
  188. expires_at = now + timedelta(minutes=SLICER_TOKEN_EXPIRE_MINUTES)
  189. token = secrets.token_urlsafe(24)
  190. resource_key = f"{resource_type}:{resource_id}"
  191. async with async_session() as db:
  192. # Prune expired tokens opportunistically
  193. await db.execute(
  194. delete(AuthEphemeralToken).where(
  195. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  196. AuthEphemeralToken.expires_at < now,
  197. )
  198. )
  199. db.add(
  200. AuthEphemeralToken(
  201. token=token,
  202. token_type=TokenType.SLICER_DOWNLOAD,
  203. nonce=resource_key,
  204. expires_at=expires_at,
  205. )
  206. )
  207. await db.commit()
  208. return token
  209. async def verify_slicer_download_token(token: str, resource_type: str, resource_id: int) -> bool:
  210. """Verify and atomically consume a slicer download token.
  211. Returns True only if the token is valid, unexpired, and bound to the given resource.
  212. DELETE...RETURNING ensures the token is single-use even under concurrent requests.
  213. M-NEW-1 fix: nonce (resource key) is included in the WHERE clause so the DELETE
  214. only succeeds when the token is presented to the *correct* resource endpoint.
  215. Previously the token was consumed (committed) even when stored_key != expected_key,
  216. permanently invalidating it while returning False to the caller.
  217. """
  218. expected_key = f"{resource_type}:{resource_id}"
  219. now = datetime.now(timezone.utc)
  220. async with async_session() as db:
  221. result = await db.execute(
  222. delete(AuthEphemeralToken)
  223. .where(
  224. AuthEphemeralToken.token == token,
  225. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  226. AuthEphemeralToken.nonce == expected_key,
  227. AuthEphemeralToken.expires_at > now,
  228. )
  229. .returning(AuthEphemeralToken.id)
  230. )
  231. if result.one_or_none() is None:
  232. return False
  233. await db.commit()
  234. return True
  235. # --- Camera stream tokens ---
  236. # Reusable tokens for camera stream/snapshot endpoints loaded via <img>/<video>
  237. # tags (these cannot send Authorization headers). Unlike slicer tokens they are
  238. # NOT single-use — streams reconnect on errors. Stored in AuthEphemeralToken
  239. # (token_type="camera_stream") for multi-worker compatibility (M-3).
  240. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  241. async def create_camera_stream_token() -> str:
  242. """Create a reusable token for camera stream/snapshot access."""
  243. now = datetime.now(timezone.utc)
  244. expires_at = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  245. token = secrets.token_urlsafe(24)
  246. async with async_session() as db:
  247. # Prune expired tokens opportunistically
  248. await db.execute(
  249. delete(AuthEphemeralToken).where(
  250. AuthEphemeralToken.token_type == "camera_stream",
  251. AuthEphemeralToken.expires_at < now,
  252. )
  253. )
  254. db.add(
  255. AuthEphemeralToken(
  256. token=token,
  257. token_type="camera_stream",
  258. expires_at=expires_at,
  259. )
  260. )
  261. await db.commit()
  262. return token
  263. async def verify_camera_stream_token(token: str) -> bool:
  264. """Verify a camera stream token is valid (reusable — does not consume it).
  265. Tries the ephemeral 60-minute token first (the common, browser-bound case)
  266. and falls through to long-lived tokens (#1108) for HA / kiosk integrations
  267. that paste a token once and expect it to keep working for days.
  268. """
  269. now = datetime.now(timezone.utc)
  270. async with async_session() as db:
  271. result = await db.execute(
  272. select(AuthEphemeralToken).where(
  273. AuthEphemeralToken.token == token,
  274. AuthEphemeralToken.token_type == "camera_stream",
  275. AuthEphemeralToken.expires_at > now,
  276. )
  277. )
  278. if result.scalar_one_or_none() is not None:
  279. return True
  280. # Long-lived path. Imported lazily so the auth module stays importable
  281. # at startup before the long_lived_tokens model is registered.
  282. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  283. record = await verify_long_lived(db, token, scope="camera_stream")
  284. return record is not None
  285. def verify_password(plain_password: str, hashed_password: str) -> bool:
  286. """Verify a password against a hash.
  287. Uses pbkdf2_sha256 which handles long passwords automatically.
  288. """
  289. return pwd_context.verify(plain_password, hashed_password)
  290. def get_password_hash(password: str) -> str:
  291. """Hash a password.
  292. Uses pbkdf2_sha256 which is secure and has no password length limit.
  293. """
  294. return pwd_context.hash(password)
  295. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  296. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  297. to_encode = data.copy()
  298. now = datetime.now(timezone.utc)
  299. if expires_delta:
  300. expire = now + expires_delta
  301. else:
  302. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  303. jti = secrets.token_hex(16)
  304. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  305. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  306. return encoded_jwt
  307. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  308. """Return False if the token was issued before the user's last password change.
  309. Used to invalidate all sessions after a password reset/change (M-R7-B).
  310. All tokens without an iat claim are unconditionally rejected — every token
  311. issued by this server carries iat, so absence means the token is forged or
  312. from a pre-iat code path whose max TTL (24 h) has long since expired.
  313. """
  314. if iat is None:
  315. return False
  316. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  317. return True # No password change recorded yet (I2 migration handles this)
  318. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  319. pca = user.password_changed_at
  320. if pca.tzinfo is None:
  321. pca = pca.replace(tzinfo=timezone.utc)
  322. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  323. pca = pca.replace(microsecond=0)
  324. return token_issued_at >= pca
  325. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  326. """Store a revoked JWT jti so it is rejected on future requests.
  327. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  328. """
  329. from sqlalchemy.exc import IntegrityError
  330. async with async_session() as db:
  331. revoked = AuthEphemeralToken(
  332. token=jti,
  333. token_type="revoked_jti",
  334. username=username,
  335. expires_at=expires_at,
  336. )
  337. db.add(revoked)
  338. try:
  339. await db.commit()
  340. except IntegrityError:
  341. await db.rollback() # jti already revoked — desired state, ignore
  342. async def is_jti_revoked(jti: str) -> bool:
  343. """Return True if the given jti has been revoked."""
  344. async with async_session() as db:
  345. result = await db.execute(
  346. select(AuthEphemeralToken).where(
  347. AuthEphemeralToken.token == jti,
  348. AuthEphemeralToken.token_type == "revoked_jti",
  349. )
  350. )
  351. return result.scalar_one_or_none() is not None
  352. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  353. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  354. result = await db.execute(
  355. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  356. )
  357. return result.scalar_one_or_none()
  358. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  359. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  360. result = await db.execute(
  361. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  362. )
  363. return result.scalar_one_or_none()
  364. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  365. """Authenticate a user by username and password.
  366. Username lookup is case-insensitive. Password is case-sensitive.
  367. LDAP and OIDC users must authenticate via their respective providers.
  368. """
  369. user = await get_user_by_username(db, username)
  370. if not user:
  371. return None
  372. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  373. return None # LDAP/OIDC users must authenticate via their provider
  374. if not user.password_hash or not verify_password(password, user.password_hash):
  375. return None
  376. if not user.is_active:
  377. return None
  378. return user
  379. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  380. """Authenticate a user by email and password.
  381. Email lookup is case-insensitive. Password is case-sensitive.
  382. LDAP and OIDC users must authenticate via their respective providers.
  383. """
  384. user = await get_user_by_email(db, email)
  385. if not user:
  386. return None
  387. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  388. return None # LDAP/OIDC users must authenticate via their provider
  389. if not user.password_hash or not verify_password(password, user.password_hash):
  390. return None
  391. if not user.is_active:
  392. return None
  393. return user
  394. async def is_auth_enabled(db: AsyncSession) -> bool:
  395. """Check if authentication is enabled.
  396. Fails CLOSED on database errors. A previous version of this function
  397. caught every exception and returned False — silently treating an
  398. unavailable database as "auth is disabled" and granting unauthenticated
  399. access to every endpoint that called it (GHSA-6mf4-q26m-47pv, CVSS 9.8).
  400. An attacker could trigger that fail-open by flooding /api/v1/auth/login
  401. to exhaust the process's file-descriptor budget, then hit a protected
  402. endpoint during the window where the next DB op raised.
  403. Legitimate "auth was never configured" still returns False — the
  404. settings row is simply absent, ``scalar_one_or_none`` returns None,
  405. no exception. Any OTHER failure (connection error, fd exhaustion,
  406. schema mismatch, …) propagates so the caller can deny the request
  407. (503 / 500). Fail-closed is the only safe default for an auth probe.
  408. """
  409. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  410. setting = result.scalar_one_or_none()
  411. if setting is None:
  412. return False
  413. return setting.value.lower() == "true"
  414. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  415. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  416. Cloud routes (and any route that needs caller identity) read the returned
  417. User to look up per-user state like ``cloud_token``. Legacy keys created
  418. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  419. against non-cloud routes for backward compatibility, but cloud routes will
  420. surface a "recreate this key" error rather than 200 with empty results.
  421. """
  422. if api_key.user_id is None:
  423. return None
  424. result = await db.execute(select(User).where(User.id == api_key.user_id))
  425. user = result.scalar_one_or_none()
  426. if user is None or not user.is_active:
  427. # CASCADE on user delete should prevent a dangling user_id, but if
  428. # someone manually deactivates the owner the key shouldn't suddenly
  429. # gain an "anonymous" identity — drop the request to None so cloud
  430. # access fails closed.
  431. return None
  432. return user
  433. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  434. """Validate an API key and return the APIKey object if valid, None otherwise.
  435. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  436. O(1) candidate rows are hashed instead of the full key table. The prefix is
  437. not secret (it is shown in the admin UI), so this does not reduce security.
  438. """
  439. try:
  440. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  441. # Matching on the first 8 chars of the submitted key reduces the scan to
  442. # at most one row in practice (2^40 collision space for 5 base64 chars).
  443. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  444. result = await db.execute(
  445. select(APIKey).where(
  446. APIKey.enabled.is_(True),
  447. APIKey.key_prefix.like(
  448. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  449. ),
  450. )
  451. )
  452. api_keys = result.scalars().all()
  453. for api_key in api_keys:
  454. if verify_password(api_key_value, api_key.key_hash):
  455. # Check expiration
  456. if api_key.expires_at:
  457. expires = api_key.expires_at
  458. if expires.tzinfo is None:
  459. expires = expires.replace(tzinfo=timezone.utc)
  460. if expires < datetime.now(timezone.utc):
  461. return None # Expired
  462. # Update last_used timestamp
  463. api_key.last_used = datetime.now(timezone.utc)
  464. await db.commit()
  465. return api_key
  466. except Exception as e:
  467. logger.warning("API key validation error: %s", e)
  468. return None
  469. async def get_current_user_optional(
  470. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  471. ) -> User | None:
  472. """Get the current authenticated user from JWT token, or None if not authenticated.
  473. Returns None only when NO credentials are supplied. If a token is supplied
  474. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  475. access (I6).
  476. """
  477. if credentials is None:
  478. return None
  479. _unauthorized = HTTPException(
  480. status_code=status.HTTP_401_UNAUTHORIZED,
  481. detail="Could not validate credentials",
  482. headers={"WWW-Authenticate": "Bearer"},
  483. )
  484. try:
  485. token = credentials.credentials
  486. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  487. username: str = payload.get("sub")
  488. if username is None:
  489. raise _unauthorized
  490. jti: str | None = payload.get("jti")
  491. if not jti or await is_jti_revoked(jti):
  492. raise _unauthorized # I6: revoked token → 401, not anonymous
  493. iat: int | float | None = payload.get("iat")
  494. except JWTError:
  495. raise _unauthorized
  496. async with async_session() as db:
  497. user = await get_user_by_username(db, username)
  498. if user is None or not user.is_active:
  499. raise _unauthorized
  500. if not _is_token_fresh(iat, user):
  501. raise _unauthorized
  502. return user
  503. async def get_current_user(
  504. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  505. ) -> User:
  506. """Get the current authenticated user from JWT token."""
  507. credentials_exception = HTTPException(
  508. status_code=status.HTTP_401_UNAUTHORIZED,
  509. detail="Could not validate credentials",
  510. headers={"WWW-Authenticate": "Bearer"},
  511. )
  512. if credentials is None:
  513. raise credentials_exception
  514. try:
  515. token = credentials.credentials
  516. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  517. username: str = payload.get("sub")
  518. if username is None:
  519. raise credentials_exception
  520. jti: str | None = payload.get("jti")
  521. if not jti or await is_jti_revoked(jti):
  522. raise credentials_exception
  523. iat: int | float | None = payload.get("iat")
  524. except JWTError:
  525. raise credentials_exception
  526. async with async_session() as db:
  527. user = await get_user_by_username(db, username)
  528. if user is None:
  529. raise credentials_exception
  530. if not user.is_active:
  531. raise HTTPException(
  532. status_code=status.HTTP_403_FORBIDDEN,
  533. detail="User account is disabled",
  534. )
  535. if not _is_token_fresh(iat, user):
  536. raise credentials_exception
  537. return user
  538. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  539. """Get the current active user (alias for clarity)."""
  540. return current_user
  541. async def require_auth_if_enabled(
  542. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  543. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  544. ) -> User | None:
  545. """Require authentication if auth is enabled, otherwise return None.
  546. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  547. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  548. None for backward compatibility — routes that need the API-key owner (i.e.
  549. cloud routes for #1182) resolve it via their own router-level dependency
  550. that stashes ``request.state.api_key_owner``. Returning the owner here
  551. instead would silently grant API-keyed callers access to every route that
  552. fences via ``if current_user is None``, which is a wider surface than
  553. #1182 was designed to expose.
  554. """
  555. async with async_session() as db:
  556. auth_enabled = await is_auth_enabled(db)
  557. if not auth_enabled:
  558. return None
  559. # Check for API key first (X-API-Key header)
  560. if x_api_key:
  561. api_key = await _validate_api_key(db, x_api_key)
  562. if api_key:
  563. return None # API key valid, allow access
  564. # Check for Bearer token (could be JWT or API key)
  565. if credentials is not None:
  566. token = credentials.credentials
  567. # Check if it's an API key (starts with bb_)
  568. if token.startswith("bb_"):
  569. api_key = await _validate_api_key(db, token)
  570. if api_key:
  571. return None # API key valid, allow access
  572. raise HTTPException(
  573. status_code=status.HTTP_401_UNAUTHORIZED,
  574. detail="Invalid API key",
  575. headers={"WWW-Authenticate": "Bearer"},
  576. )
  577. # Otherwise treat as JWT
  578. try:
  579. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  580. username: str = payload.get("sub")
  581. if username is None:
  582. raise HTTPException(
  583. status_code=status.HTTP_401_UNAUTHORIZED,
  584. detail="Could not validate credentials",
  585. headers={"WWW-Authenticate": "Bearer"},
  586. )
  587. jti: str | None = payload.get("jti")
  588. if not jti or await is_jti_revoked(jti):
  589. raise HTTPException(
  590. status_code=status.HTTP_401_UNAUTHORIZED,
  591. detail="Could not validate credentials",
  592. headers={"WWW-Authenticate": "Bearer"},
  593. )
  594. iat: int | float | None = payload.get("iat")
  595. except JWTError:
  596. raise HTTPException(
  597. status_code=status.HTTP_401_UNAUTHORIZED,
  598. detail="Could not validate credentials",
  599. headers={"WWW-Authenticate": "Bearer"},
  600. )
  601. user = await get_user_by_username(db, username)
  602. if user is None or not user.is_active:
  603. raise HTTPException(
  604. status_code=status.HTTP_401_UNAUTHORIZED,
  605. detail="Could not validate credentials",
  606. headers={"WWW-Authenticate": "Bearer"},
  607. )
  608. if not _is_token_fresh(iat, user):
  609. raise HTTPException(
  610. status_code=status.HTTP_401_UNAUTHORIZED,
  611. detail="Could not validate credentials",
  612. headers={"WWW-Authenticate": "Bearer"},
  613. )
  614. return user
  615. # No credentials provided
  616. raise HTTPException(
  617. status_code=status.HTTP_401_UNAUTHORIZED,
  618. detail="Authentication required",
  619. headers={"WWW-Authenticate": "Bearer"},
  620. )
  621. def require_role(required_role: str):
  622. """Dependency factory for role-based access control."""
  623. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  624. if current_user.role != required_role:
  625. raise HTTPException(
  626. status_code=status.HTTP_403_FORBIDDEN,
  627. detail=f"Requires {required_role} role",
  628. )
  629. return current_user
  630. return role_checker
  631. def require_admin_if_auth_enabled():
  632. """Dependency factory that requires admin role if auth is enabled."""
  633. async def admin_checker(
  634. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  635. ) -> User | None:
  636. if current_user is None:
  637. return None # Auth not enabled, allow access
  638. if current_user.role != "admin":
  639. raise HTTPException(
  640. status_code=status.HTTP_403_FORBIDDEN,
  641. detail="Requires admin role",
  642. )
  643. return current_user
  644. return admin_checker
  645. def generate_api_key() -> tuple[str, str, str]:
  646. """Generate a new API key.
  647. Returns:
  648. tuple: (full_key, key_hash, key_prefix)
  649. - full_key: The complete API key (only shown once on creation)
  650. - key_hash: Hashed version for storage and verification
  651. - key_prefix: First 8 characters for display purposes
  652. """
  653. # Generate a secure random API key (32 bytes = 64 hex characters)
  654. full_key = f"bb_{secrets.token_urlsafe(32)}"
  655. key_hash = get_password_hash(full_key)
  656. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  657. return full_key, key_hash, key_prefix
  658. async def get_api_key(
  659. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  660. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  661. db: AsyncSession = Depends(get_db),
  662. ) -> APIKey:
  663. """Get and validate API key from request headers.
  664. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  665. """
  666. api_key_value = None
  667. if x_api_key:
  668. api_key_value = x_api_key
  669. elif authorization and authorization.startswith("Bearer "):
  670. api_key_value = authorization.replace("Bearer ", "")
  671. if not api_key_value:
  672. raise HTTPException(
  673. status_code=status.HTTP_401_UNAUTHORIZED,
  674. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  675. )
  676. # Pre-filter by key_prefix to avoid O(n) pbkdf2 hashes across all enabled keys.
  677. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  678. result = await db.execute(
  679. select(APIKey).where(
  680. APIKey.enabled.is_(True),
  681. APIKey.key_prefix.like(
  682. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  683. escape="\\",
  684. ),
  685. )
  686. )
  687. api_keys = result.scalars().all()
  688. for api_key in api_keys:
  689. # Check if key matches (verify against hash)
  690. if verify_password(api_key_value, api_key.key_hash):
  691. # Check expiration
  692. if api_key.expires_at:
  693. expires = api_key.expires_at
  694. if expires.tzinfo is None:
  695. expires = expires.replace(tzinfo=timezone.utc)
  696. if expires < datetime.now(timezone.utc):
  697. raise HTTPException(
  698. status_code=status.HTTP_401_UNAUTHORIZED,
  699. detail="API key has expired",
  700. )
  701. # Update last_used timestamp
  702. api_key.last_used = datetime.now(timezone.utc)
  703. await db.commit()
  704. return api_key
  705. raise HTTPException(
  706. status_code=status.HTTP_401_UNAUTHORIZED,
  707. detail="Invalid API key",
  708. )
  709. async def caller_is_api_key(
  710. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  711. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  712. ) -> bool:
  713. """Return True when the request is authenticated via API key (X-API-Key or Bearer bb_xxx)."""
  714. if x_api_key:
  715. return True
  716. return credentials is not None and credentials.credentials.startswith("bb_")
  717. def check_permission(api_key: APIKey, permission: str) -> None:
  718. """Check if API key has the required permission.
  719. Args:
  720. api_key: The API key object
  721. permission: One of 'queue', 'control_printer', 'read_status'
  722. Raises:
  723. HTTPException: If permission is not granted
  724. """
  725. permission_map = {
  726. "queue": "can_queue",
  727. "control_printer": "can_control_printer",
  728. "read_status": "can_read_status",
  729. }
  730. if permission not in permission_map:
  731. raise HTTPException(
  732. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  733. detail=f"Unknown permission: {permission}",
  734. )
  735. attr_name = permission_map[permission]
  736. if not getattr(api_key, attr_name, False):
  737. raise HTTPException(
  738. status_code=status.HTTP_403_FORBIDDEN,
  739. detail=f"API key does not have '{permission}' permission",
  740. )
  741. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  742. """Check if API key has access to the specified printer.
  743. Args:
  744. api_key: The API key object
  745. printer_id: The printer ID to check access for
  746. Raises:
  747. HTTPException: If access is denied
  748. """
  749. # None = global key, access to all printers
  750. if api_key.printer_ids is None:
  751. return
  752. # Empty list or printer not in allowed list = no access
  753. if printer_id not in api_key.printer_ids:
  754. raise HTTPException(
  755. status_code=status.HTTP_403_FORBIDDEN,
  756. detail=f"API key does not have access to printer {printer_id}",
  757. )
  758. # Convenience dependencies - these are functions that return Depends objects
  759. def RequireAdmin():
  760. """Dependency that requires admin role."""
  761. return Depends(require_role("admin"))
  762. def RequireAdminIfAuthEnabled():
  763. """Dependency that requires admin role if auth is enabled."""
  764. return Depends(require_admin_if_auth_enabled())
  765. def require_permission(*permissions: str | Permission):
  766. """Dependency factory that requires user to have ALL specified permissions.
  767. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  768. (via X-API-Key header or Authorization: Bearer bb_xxx).
  769. Args:
  770. *permissions: Permission strings or Permission enum values to require
  771. Returns:
  772. A dependency function that validates permissions
  773. """
  774. # Convert Permission enums to strings
  775. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  776. async def permission_checker(
  777. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  778. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  779. ) -> User | None:
  780. async with async_session() as db:
  781. # Check for API key first (X-API-Key header)
  782. if x_api_key:
  783. api_key = await _validate_api_key(db, x_api_key)
  784. if api_key:
  785. _check_apikey_permissions(perm_strings)
  786. return None # API key valid, allow access
  787. credentials_exception = HTTPException(
  788. status_code=status.HTTP_401_UNAUTHORIZED,
  789. detail="Could not validate credentials",
  790. headers={"WWW-Authenticate": "Bearer"},
  791. )
  792. if credentials is None:
  793. raise credentials_exception
  794. token = credentials.credentials
  795. # Check if it's an API key (starts with bb_)
  796. if token.startswith("bb_"):
  797. api_key = await _validate_api_key(db, token)
  798. if api_key:
  799. _check_apikey_permissions(perm_strings)
  800. return None # API key valid, allow access
  801. raise HTTPException(
  802. status_code=status.HTTP_401_UNAUTHORIZED,
  803. detail="Invalid API key",
  804. headers={"WWW-Authenticate": "Bearer"},
  805. )
  806. # Otherwise treat as JWT
  807. try:
  808. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  809. username: str = payload.get("sub")
  810. if username is None:
  811. raise credentials_exception
  812. jti: str | None = payload.get("jti")
  813. if not jti or await is_jti_revoked(jti):
  814. raise credentials_exception
  815. iat: int | float | None = payload.get("iat")
  816. except JWTError:
  817. raise credentials_exception
  818. user = await get_user_by_username(db, username)
  819. if user is None or not user.is_active:
  820. raise credentials_exception
  821. if not _is_token_fresh(iat, user):
  822. raise credentials_exception
  823. if not user.has_all_permissions(*perm_strings):
  824. raise HTTPException(
  825. status_code=status.HTTP_403_FORBIDDEN,
  826. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  827. )
  828. return user
  829. return permission_checker
  830. def require_permission_if_auth_enabled(*permissions: str | Permission):
  831. """Dependency factory that checks permissions only if auth is enabled.
  832. This provides backward compatibility - when auth is disabled, all access is allowed.
  833. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  834. (via X-API-Key header or Authorization: Bearer bb_xxx).
  835. Args:
  836. *permissions: Permission strings or Permission enum values to require
  837. Returns:
  838. A dependency function that validates permissions if auth is enabled
  839. """
  840. # Convert Permission enums to strings
  841. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  842. async def permission_checker(
  843. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  844. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  845. ) -> User | None:
  846. async with async_session() as db:
  847. auth_enabled = await is_auth_enabled(db)
  848. if not auth_enabled:
  849. return None # Auth disabled, allow access
  850. # Check for API key first (X-API-Key header). API-keyed requests
  851. # bypass the JWT permission check entirely — their scopes live on
  852. # the APIKey row (can_queue / can_control_printer / can_read_status
  853. # / can_access_cloud / printer_ids), and the dep returns None so
  854. # routes don't gain a synthetic User identity that would grant
  855. # access to fenced surfaces like long-lived-token management.
  856. # Cloud routes (#1182) resolve the API-key owner separately via
  857. # their own router-level dependency; see ``cloud.py``.
  858. if x_api_key:
  859. api_key = await _validate_api_key(db, x_api_key)
  860. if api_key:
  861. _check_apikey_permissions(perm_strings)
  862. return None # API key valid, allow access
  863. # Check for Bearer token (could be JWT or API key)
  864. if credentials is not None:
  865. token = credentials.credentials
  866. # Check if it's an API key (starts with bb_)
  867. if token.startswith("bb_"):
  868. api_key = await _validate_api_key(db, token)
  869. if api_key:
  870. _check_apikey_permissions(perm_strings)
  871. return None # API key valid, allow access
  872. raise HTTPException(
  873. status_code=status.HTTP_401_UNAUTHORIZED,
  874. detail="Invalid API key",
  875. headers={"WWW-Authenticate": "Bearer"},
  876. )
  877. # Otherwise treat as JWT
  878. try:
  879. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  880. username: str = payload.get("sub")
  881. if username is None:
  882. raise HTTPException(
  883. status_code=status.HTTP_401_UNAUTHORIZED,
  884. detail="Could not validate credentials",
  885. headers={"WWW-Authenticate": "Bearer"},
  886. )
  887. jti: str | None = payload.get("jti")
  888. if not jti or await is_jti_revoked(jti):
  889. raise HTTPException(
  890. status_code=status.HTTP_401_UNAUTHORIZED,
  891. detail="Could not validate credentials",
  892. headers={"WWW-Authenticate": "Bearer"},
  893. )
  894. iat: int | float | None = payload.get("iat")
  895. except JWTError:
  896. raise HTTPException(
  897. status_code=status.HTTP_401_UNAUTHORIZED,
  898. detail="Could not validate credentials",
  899. headers={"WWW-Authenticate": "Bearer"},
  900. )
  901. user = await get_user_by_username(db, username)
  902. if user is None or not user.is_active:
  903. raise HTTPException(
  904. status_code=status.HTTP_401_UNAUTHORIZED,
  905. detail="Could not validate credentials",
  906. headers={"WWW-Authenticate": "Bearer"},
  907. )
  908. if not _is_token_fresh(iat, user):
  909. raise HTTPException(
  910. status_code=status.HTTP_401_UNAUTHORIZED,
  911. detail="Could not validate credentials",
  912. headers={"WWW-Authenticate": "Bearer"},
  913. )
  914. if not user.has_all_permissions(*perm_strings):
  915. raise HTTPException(
  916. status_code=status.HTTP_403_FORBIDDEN,
  917. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  918. )
  919. return user
  920. # No credentials provided
  921. raise HTTPException(
  922. status_code=status.HTTP_401_UNAUTHORIZED,
  923. detail="Authentication required",
  924. headers={"WWW-Authenticate": "Bearer"},
  925. )
  926. return permission_checker
  927. def RequirePermission(*permissions: str | Permission):
  928. """Convenience dependency that requires ALL specified permissions."""
  929. return Depends(require_permission(*permissions))
  930. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  931. """Convenience dependency that requires permissions if auth is enabled."""
  932. return Depends(require_permission_if_auth_enabled(*permissions))
  933. def require_any_permission_if_auth_enabled(*permissions: str | Permission):
  934. """Dependency factory that requires AT LEAST ONE of the given permissions when auth is enabled."""
  935. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  936. async def checker(
  937. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  938. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  939. ) -> User | None:
  940. async with async_session() as db:
  941. auth_enabled = await is_auth_enabled(db)
  942. if not auth_enabled:
  943. return None
  944. if x_api_key:
  945. api_key = await _validate_api_key(db, x_api_key)
  946. if api_key:
  947. return None
  948. if credentials is not None:
  949. token = credentials.credentials
  950. if token.startswith("bb_"):
  951. api_key = await _validate_api_key(db, token)
  952. if api_key:
  953. return None
  954. raise HTTPException(
  955. status_code=status.HTTP_401_UNAUTHORIZED,
  956. detail="Invalid API key",
  957. headers={"WWW-Authenticate": "Bearer"},
  958. )
  959. try:
  960. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  961. username: str = payload.get("sub")
  962. if username is None:
  963. raise HTTPException(
  964. status_code=status.HTTP_401_UNAUTHORIZED,
  965. detail="Could not validate credentials",
  966. headers={"WWW-Authenticate": "Bearer"},
  967. )
  968. jti: str | None = payload.get("jti")
  969. if not jti or await is_jti_revoked(jti):
  970. raise HTTPException(
  971. status_code=status.HTTP_401_UNAUTHORIZED,
  972. detail="Could not validate credentials",
  973. headers={"WWW-Authenticate": "Bearer"},
  974. )
  975. iat: int | float | None = payload.get("iat")
  976. except JWTError:
  977. raise HTTPException(
  978. status_code=status.HTTP_401_UNAUTHORIZED,
  979. detail="Could not validate credentials",
  980. headers={"WWW-Authenticate": "Bearer"},
  981. )
  982. user = await get_user_by_username(db, username)
  983. if user is None or not user.is_active:
  984. raise HTTPException(
  985. status_code=status.HTTP_401_UNAUTHORIZED,
  986. detail="Could not validate credentials",
  987. headers={"WWW-Authenticate": "Bearer"},
  988. )
  989. if not _is_token_fresh(iat, user):
  990. raise HTTPException(
  991. status_code=status.HTTP_401_UNAUTHORIZED,
  992. detail="Could not validate credentials",
  993. headers={"WWW-Authenticate": "Bearer"},
  994. )
  995. if not user.has_any_permission(*perm_strings):
  996. raise HTTPException(
  997. status_code=status.HTTP_403_FORBIDDEN,
  998. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  999. )
  1000. return user
  1001. raise HTTPException(
  1002. status_code=status.HTTP_401_UNAUTHORIZED,
  1003. detail="Authentication required",
  1004. headers={"WWW-Authenticate": "Bearer"},
  1005. )
  1006. return checker
  1007. def RequireAnyPermissionIfAuthEnabled(*permissions: str | Permission):
  1008. """Convenience dependency that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1009. return Depends(require_any_permission_if_auth_enabled(*permissions))
  1010. def require_camera_stream_token_if_auth_enabled():
  1011. """Dependency that validates a camera stream token query param when auth is enabled.
  1012. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  1013. which cannot send Authorization headers. The frontend obtains a token from
  1014. POST /printers/camera/stream-token and appends it as ?token=xxx.
  1015. """
  1016. async def checker(token: str | None = None) -> None:
  1017. async with async_session() as db:
  1018. if not await is_auth_enabled(db):
  1019. return # Auth disabled, allow access
  1020. if not token or not await verify_camera_stream_token(token):
  1021. raise HTTPException(
  1022. status_code=status.HTTP_401_UNAUTHORIZED,
  1023. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  1024. )
  1025. return checker
  1026. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  1027. def require_ownership_permission(
  1028. all_permission: str | Permission,
  1029. own_permission: str | Permission,
  1030. ):
  1031. """Dependency factory for ownership-based permission checks.
  1032. - User with `all_permission` can modify any item
  1033. - User with `own_permission` can only modify items where created_by_id == user.id
  1034. - Ownerless items (created_by_id = null) require `all_permission`
  1035. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  1036. Returns:
  1037. A dependency function that returns (user, can_modify_all).
  1038. - can_modify_all=True: user can modify any item
  1039. - can_modify_all=False: user can only modify their own items
  1040. """
  1041. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  1042. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  1043. async def checker(
  1044. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1045. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1046. ) -> tuple[User | None, bool]:
  1047. """Returns (user, can_modify_all).
  1048. - can_modify_all=True: user can modify any item
  1049. - can_modify_all=False: user can only modify their own items
  1050. """
  1051. async with async_session() as db:
  1052. auth_enabled = await is_auth_enabled(db)
  1053. if not auth_enabled:
  1054. return None, True # Auth disabled, allow all
  1055. # Check for API key first (X-API-Key header)
  1056. if x_api_key:
  1057. api_key = await _validate_api_key(db, x_api_key)
  1058. if api_key:
  1059. return None, True # API key valid, allow all
  1060. # Check for Bearer token (could be JWT or API key)
  1061. if credentials is not None:
  1062. token = credentials.credentials
  1063. # Check if it's an API key (starts with bb_)
  1064. if token.startswith("bb_"):
  1065. api_key = await _validate_api_key(db, token)
  1066. if api_key:
  1067. return None, True # API key valid, allow all
  1068. raise HTTPException(
  1069. status_code=status.HTTP_401_UNAUTHORIZED,
  1070. detail="Invalid API key",
  1071. headers={"WWW-Authenticate": "Bearer"},
  1072. )
  1073. # Otherwise treat as JWT
  1074. try:
  1075. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1076. username: str = payload.get("sub")
  1077. if username is None:
  1078. raise HTTPException(
  1079. status_code=status.HTTP_401_UNAUTHORIZED,
  1080. detail="Could not validate credentials",
  1081. headers={"WWW-Authenticate": "Bearer"},
  1082. )
  1083. jti: str | None = payload.get("jti")
  1084. if not jti or await is_jti_revoked(jti):
  1085. raise HTTPException(
  1086. status_code=status.HTTP_401_UNAUTHORIZED,
  1087. detail="Could not validate credentials",
  1088. headers={"WWW-Authenticate": "Bearer"},
  1089. )
  1090. iat: int | float | None = payload.get("iat")
  1091. except JWTError:
  1092. raise HTTPException(
  1093. status_code=status.HTTP_401_UNAUTHORIZED,
  1094. detail="Could not validate credentials",
  1095. headers={"WWW-Authenticate": "Bearer"},
  1096. )
  1097. user = await get_user_by_username(db, username)
  1098. if user is None or not user.is_active:
  1099. raise HTTPException(
  1100. status_code=status.HTTP_401_UNAUTHORIZED,
  1101. detail="Could not validate credentials",
  1102. headers={"WWW-Authenticate": "Bearer"},
  1103. )
  1104. if not _is_token_fresh(iat, user):
  1105. raise HTTPException(
  1106. status_code=status.HTTP_401_UNAUTHORIZED,
  1107. detail="Could not validate credentials",
  1108. headers={"WWW-Authenticate": "Bearer"},
  1109. )
  1110. if user.has_permission(all_perm):
  1111. return user, True
  1112. if user.has_permission(own_perm):
  1113. return user, False
  1114. raise HTTPException(
  1115. status_code=status.HTTP_403_FORBIDDEN,
  1116. detail=f"Missing permission: {own_perm} or {all_perm}",
  1117. )
  1118. # No credentials provided
  1119. raise HTTPException(
  1120. status_code=status.HTTP_401_UNAUTHORIZED,
  1121. detail="Authentication required",
  1122. headers={"WWW-Authenticate": "Bearer"},
  1123. )
  1124. return checker