fix(api): hash session token with SHA-256 before DB lookup

Better-Auth v1.2+ stores SHA-256(raw_token) in the sessions.token
column. The cookie/Bearer header carries the raw token, so the API was
doing a plain-text lookup that would never match a hashed value —
causing all authenticated endpoints to return 401.

- Add hashlib import and hash token in _validate_session_token()
- Update conftest._create_test_user_and_session() to store hashed tokens
- Update test_expired_session_rejected() to store hashed tokens

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Barcode Betty
2026-04-04 19:00:09 +00:00
parent ffeae96d17
commit 89293d1811
3 changed files with 14 additions and 5 deletions
+6 -2
View File
@@ -4,6 +4,7 @@ Validates Better-Auth session tokens from cookies or Bearer header.
Sessions are verified by querying the shared sessions table directly.
"""
import hashlib
from datetime import UTC, datetime
from fastapi import Cookie, Depends, Header, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
@@ -26,11 +27,14 @@ SECURE_SESSION_COOKIE_NAME = "__Secure-better-auth.session_token"
async def _validate_session_token(token: str, db: AsyncSession) -> str:
"""Validate a Better-Auth session token against the sessions table.
Returns the user_id (as str) if the session is valid and not expired.
Better-Auth v1.2+ stores SHA-256(raw_token) in the DB.
The cookie/Bearer header carries the raw token, so we hash before lookup.
"""
token_hash = hashlib.sha256(token.encode()).hexdigest()
result = await db.execute(
text("SELECT user_id, expires_at FROM sessions WHERE token = :token"),
{"token": token},
{"token": token_hash},
)
row = result.first()