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
+3 -1
View File
@@ -74,6 +74,7 @@ async def test_delete_me(client, auth_headers):
@pytest.mark.asyncio
async def test_expired_session_rejected(client, db_engine):
"""Expired sessions must be rejected."""
import hashlib
import secrets
import uuid
from datetime import UTC, datetime, timedelta
@@ -82,6 +83,7 @@ async def test_expired_session_rejected(client, db_engine):
user_id = str(uuid.uuid4())
session_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(session_token.encode()).hexdigest()
now = datetime.now(UTC).isoformat()
expired = (datetime.now(UTC) - timedelta(hours=1)).isoformat()
@@ -108,7 +110,7 @@ async def test_expired_session_rejected(client, db_engine):
),
{
"id": str(uuid.uuid4()),
"token": session_token,
"token": token_hash,
"uid": user_id,
"ea": expired,
"ca": now,