From ec4d8f21a93fb1c26c3a7ae9cda9a886b4527ea1 Mon Sep 17 00:00:00 2001 From: CartSnitch Engineer Bot Date: Wed, 1 Apr 2026 02:09:55 +0000 Subject: [PATCH] fix(api): hash session token before DB lookup to match Better-Auth storage Better-Auth v1.5.6+ stores session tokens as SHA-256 hashes in the sessions table. The raw token from the cookie was being queried directly, causing all authenticated /api/v1/* requests to return 401. Fixes CAR-313. Co-Authored-By: Paperclip --- src/cartsnitch_api/auth/dependencies.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cartsnitch_api/auth/dependencies.py b/src/cartsnitch_api/auth/dependencies.py index 93f8eb8..54bac74 100644 --- a/src/cartsnitch_api/auth/dependencies.py +++ b/src/cartsnitch_api/auth/dependencies.py @@ -5,6 +5,7 @@ Sessions are verified by querying the shared sessions table directly. """ from datetime import UTC, datetime +from hashlib import sha256 from uuid import UUID from fastapi import Cookie, Depends, Header, HTTPException, Request, status @@ -27,10 +28,13 @@ async def _validate_session_token(token: str, db: AsyncSession) -> UUID: """Validate a Better-Auth session token against the sessions table. Returns the user_id (as UUID) if the session is valid and not expired. + Better-Auth v1.5.6+ stores tokens as SHA-256 hashes, so we hash the + incoming raw token before querying. """ + hashed_token = sha256(token.encode("utf-8")).hexdigest() result = await db.execute( text("SELECT user_id, expires_at FROM sessions WHERE token = :token"), - {"token": token}, + {"token": hashed_token}, ) row = result.first()