Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions core/api/v1/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@
from sqlalchemy import select

if TYPE_CHECKING:
from fastapi.security import HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession

from core.auth.blacklist import token_blacklist
from core.auth.jwt import (
TokenType,
_bearer_scheme,
create_access_token,
create_refresh_token,
verify_token,
Expand Down Expand Up @@ -253,7 +256,7 @@ async def refresh(
Raises:
HTTPException 401: Invalid, expired, or wrong-type token.
"""
token_data = verify_token(payload.refresh_token)
token_data = await verify_token(payload.refresh_token)

# Ensure this is actually a refresh token, not an access token
if token_data.token_type != TokenType.REFRESH:
Expand Down Expand Up @@ -299,19 +302,22 @@ async def refresh(
"/logout",
response_model=MessageResponse,
)
async def logout() -> MessageResponse:
"""Log out the current user.
async def logout(
credentials: HTTPAuthorizationCredentials = Depends(_bearer_scheme),
) -> MessageResponse:
"""Revoke the current access token.

.. note::
This is a placeholder. Actual token revocation (server-side
blocklist) will be implemented in REN-72.
Decodes the Bearer token and adds its JTI to a Redis blacklist
with a TTL matching the token's remaining lifetime. Subsequent
calls to ``verify_token`` will reject the blacklisted token.

Returns:
Confirmation message.
Confirmation message (always succeeds from the caller's perspective).
"""
# TODO(REN-72): Implement token revocation via Redis blocklist.
# Accept the Authorization header, decode the token, and add its
# ``jti`` to a Redis set with TTL matching the token's remaining
# lifetime. ``verify_token`` should then check the blocklist.
logger.info("logout_placeholder_called")
token_data = await verify_token(credentials.credentials)
revoked = await token_blacklist.revoke(token_data.jti, token_data.exp)
if revoked:
logger.info("token_revoked", jti=token_data.jti)
else:
logger.warning("token_revocation_failed_redis", jti=token_data.jti)
return MessageResponse(message="Logged out successfully")
125 changes: 125 additions & 0 deletions core/auth/blacklist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Copyright 2026 ByBren, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Redis-backed token blacklist for JWT revocation.

Uses Redis SET with TTL matching token remaining lifetime.
Fail-open: if Redis is unavailable, tokens are NOT blacklisted
(same pattern as rate_limit.py).

Usage::

from core.auth.blacklist import token_blacklist

# Revoke a token
await token_blacklist.revoke(jti="abc-123", expires_at=token_exp)

# Check if revoked
if await token_blacklist.is_revoked(jti="abc-123"):
raise HTTPException(401)
"""

from __future__ import annotations

import datetime

import structlog

from core.config import get_settings

logger = structlog.get_logger(__name__)

# Redis key prefix for blacklisted tokens
_KEY_PREFIX = "blacklist:"


class TokenBlacklist:
"""Redis-backed token blacklist for JWT revocation.

Uses Redis SET with TTL matching token remaining lifetime.
Fail-open: if Redis is unavailable, tokens are NOT blacklisted
(same pattern as rate_limit.py).
"""

async def revoke(self, jti: str, expires_at: datetime.datetime) -> bool:
"""Add token JTI to blacklist with TTL until token expiry.

Args:
jti: The JWT ID (unique token identifier).
expires_at: The token's expiration timestamp.

Returns:
True if the token was successfully blacklisted, False if
the token is already expired or Redis is unavailable.
"""
import redis.asyncio as aioredis

now = datetime.datetime.now(tz=datetime.UTC)

# Ensure expires_at is timezone-aware for comparison
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=datetime.UTC)

ttl_seconds = int((expires_at - now).total_seconds())

if ttl_seconds <= 0:
logger.debug("blacklist_skip_expired", jti=jti)
return False

settings = get_settings()
key = f"{_KEY_PREFIX}{jti}"

try:
r = aioredis.from_url(settings.redis_url)
try:
await r.setex(key, ttl_seconds, "1")
logger.info("token_blacklisted", jti=jti, ttl_seconds=ttl_seconds)
return True
finally:
await r.aclose()
except Exception:
# Fail open -- Redis unavailable should not block logout.
logger.warning("blacklist_redis_unavailable", jti=jti, operation="revoke")
return False

async def is_revoked(self, jti: str) -> bool:
"""Check if a token JTI is blacklisted.

Args:
jti: The JWT ID to check.

Returns:
True if the token is blacklisted, False if it is not or
if Redis is unavailable (fail-open).
"""
import redis.asyncio as aioredis

settings = get_settings()
key = f"{_KEY_PREFIX}{jti}"

try:
r = aioredis.from_url(settings.redis_url)
try:
exists: bool = bool(await r.exists(key))
return exists
finally:
await r.aclose()
except Exception:
# Fail open -- Redis unavailable means token is NOT considered revoked.
logger.warning("blacklist_redis_unavailable", jti=jti, operation="is_revoked")
return False


# Module-level singleton
token_blacklist = TokenBlacklist()
32 changes: 26 additions & 6 deletions core/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,27 @@
Tokens are never logged or exposed in error messages.
"""

from __future__ import annotations

import datetime
import uuid
from enum import StrEnum
from typing import Any
from typing import TYPE_CHECKING, Any

import structlog
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import JWTError, jwt
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from core.config import get_settings
from core.database import get_db_session
from core.models.base import User

if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession

logger = structlog.get_logger(__name__)

# Security scheme for OpenAPI docs
Expand All @@ -55,12 +60,14 @@ class TokenPayload(BaseModel):
exp: Expiration timestamp.
iat: Issued-at timestamp.
token_type: Discriminator for access vs. refresh tokens.
jti: JWT ID -- unique token identifier for revocation.
"""

sub: str
exp: datetime.datetime
iat: datetime.datetime
token_type: TokenType
jti: str


def create_access_token(data: dict[str, Any]) -> str:
Expand All @@ -80,6 +87,7 @@ def create_access_token(data: dict[str, Any]) -> str:
"exp": expires,
"iat": now,
"token_type": TokenType.ACCESS.value,
"jti": str(uuid.uuid4()),
}
encoded: str = jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
return encoded
Expand All @@ -102,12 +110,13 @@ def create_refresh_token(data: dict[str, Any]) -> str:
"exp": expires,
"iat": now,
"token_type": TokenType.REFRESH.value,
"jti": str(uuid.uuid4()),
}
encoded: str = jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
return encoded


def verify_token(token: str) -> TokenPayload:
async def verify_token(token: str) -> TokenPayload:
"""Verify and decode a JWT token.

Args:
Expand All @@ -117,7 +126,7 @@ def verify_token(token: str) -> TokenPayload:
Validated TokenPayload.

Raises:
HTTPException: If the token is invalid, expired, or malformed.
HTTPException: If the token is invalid, expired, malformed, or revoked.
"""
settings = get_settings()
credentials_exception = HTTPException(
Expand All @@ -135,16 +144,27 @@ def verify_token(token: str) -> TokenPayload:
if sub is None:
logger.warning("jwt_verification_failed", reason="missing_sub")
raise credentials_exception
return TokenPayload(

payload_data = TokenPayload(
sub=sub,
exp=payload["exp"],
iat=payload["iat"],
token_type=payload.get("token_type", TokenType.ACCESS.value),
jti=payload.get("jti", ""),
)
except JWTError as err:
logger.warning("jwt_verification_failed", reason="decode_error")
raise credentials_exception from err

# Check blacklist (after decode, before return)
from core.auth.blacklist import token_blacklist

if payload_data.jti and await token_blacklist.is_revoked(payload_data.jti):
logger.warning("revoked_token_used", jti=payload_data.jti)
raise credentials_exception

return payload_data


async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(_bearer_scheme),
Expand All @@ -166,7 +186,7 @@ async def get_current_user(
Raises:
HTTPException: 401 if authentication fails.
"""
token_data = verify_token(credentials.credentials)
token_data = await verify_token(credentials.credentials)

# Reject refresh tokens used as access tokens (OWASP A01)
if token_data.token_type != TokenType.ACCESS:
Expand Down
2 changes: 1 addition & 1 deletion core/auth/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async def dispatch(
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[len("Bearer ") :]
try:
payload = verify_token(token)
payload = await verify_token(token)
request.state.user_id = payload.sub
except (JWTError, Exception):
# Token is invalid; request.state.user_id stays None.
Expand Down
Loading
Loading