Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mdfarhankc_fastapi-fullauth /fastapi_fullauth /protection /challenges.py
| """Challenge store for WebAuthn passkey flows. | |
| Challenges are short-lived, single-use nonces that prevent replay attacks. | |
| The server generates a challenge, sends it to the browser, and the browser | |
| signs it with the user's private key. The server verifies the signature | |
| and deletes the challenge. | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| from abc import ABC, abstractmethod | |
| from typing import TYPE_CHECKING, cast | |
| if TYPE_CHECKING: | |
| from fastapi_fullauth.config import FullAuthConfig | |
| logger = logging.getLogger("fastapi_fullauth.challenges") | |
| class ChallengeStore(ABC): | |
| """Abstract challenge store. Stores challenges with a TTL.""" | |
| async def store(self, key: str, challenge: str, ttl: int = 60) -> None: ... | |
| async def pop(self, key: str) -> str | None: | |
| """Retrieve and delete a challenge. Returns None if expired or missing.""" | |
| ... | |
| async def aclose(self) -> None: # noqa: B027 | |
| """Release any held resources. No-op unless overridden.""" | |
| class InMemoryChallengeStore(ChallengeStore): | |
| """In-memory challenge store. Single-process only; use Redis for multi-worker.""" | |
| def __init__(self) -> None: | |
| self._store: dict[str, tuple[str, float]] = {} | |
| self._lock = asyncio.Lock() | |
| async def store(self, key: str, challenge: str, ttl: int = 60) -> None: | |
| self._store[key] = (challenge, time.monotonic() + ttl) | |
| async def pop(self, key: str) -> str | None: | |
| # Lock the pop+expiry-check as one atomic section so two concurrent pops | |
| # for the same key can't both see the same challenge. | |
| async with self._lock: | |
| entry = self._store.pop(key, None) | |
| if entry is None: | |
| return None | |
| challenge, expires_at = entry | |
| if time.monotonic() > expires_at: | |
| return None | |
| return challenge | |
| class RedisChallengeStore(ChallengeStore): | |
| """Redis-backed challenge store. Works across multiple workers.""" | |
| def __init__(self, redis_url: str) -> None: | |
| from fastapi_fullauth.core._redis import acquire_redis | |
| self._redis = acquire_redis(redis_url, feature="the Redis challenge store") | |
| self._redis_url: str | None = redis_url | |
| self._prefix = "fullauth:challenge:" | |
| async def store(self, key: str, challenge: str, ttl: int = 60) -> None: | |
| await self._redis.setex(f"{self._prefix}{key}", ttl, challenge) | |
| async def pop(self, key: str) -> str | None: | |
| redis_key = f"{self._prefix}{key}" | |
| # decode_responses=True, so the bytes branch of the hint can't occur. | |
| return cast("str | None", await self._redis.getdel(redis_key)) | |
| async def aclose(self) -> None: | |
| from fastapi_fullauth.core._redis import release_redis | |
| if self._redis_url is not None: | |
| await release_redis(self._redis_url) | |
| self._redis_url = None | |
| _challenge_store_registry: dict[str, type[ChallengeStore]] = { | |
| "memory": InMemoryChallengeStore, | |
| "redis": RedisChallengeStore, | |
| } | |
| def register_challenge_store_backend(name: str, cls: type[ChallengeStore]) -> None: | |
| """Register a custom challenge store backend.""" | |
| _challenge_store_registry[name] = cls | |
| def create_challenge_store(config: "FullAuthConfig") -> ChallengeStore: | |
| """Create a challenge store based on config.""" | |
| backend = config.PASSKEY_CHALLENGE_BACKEND | |
| backend_cls = _challenge_store_registry.get(backend) | |
| if backend_cls is None: | |
| raise ValueError( | |
| f"Unknown challenge store backend: {backend}. " | |
| f"Available: {', '.join(sorted(_challenge_store_registry))}." | |
| ) | |
| if backend == "redis": | |
| if not config.REDIS_URL: | |
| raise ValueError("REDIS_URL must be set when PASSKEY_CHALLENGE_BACKEND='redis'") | |
| return RedisChallengeStore(redis_url=config.REDIS_URL) | |
| return backend_cls() | |
Xet Storage Details
- Size:
- 3.89 kB
- Xet hash:
- 6b64ca1dfda60167d0f8a9ad6cc4cca02aa4c720a1bd685e40db3d40ce341d8b
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.