b4bef65079
After PR4 every JWT must carry wid (workspace_id). decode_token now returns the new TokenError.WORKSPACE_MISSING when the signature is valid but the payload lacks wid; expired tokens still report EXPIRED first so /auth/refresh logic stays correct. AuthErrorCode gains a matching WORKSPACE_REQUIRED for middleware to surface to clients. Updates 13 existing test sites that issued tokens without wid to pass workspace_id="ws-test" + role="owner", reflecting the new contract. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
"""Typed error definitions for auth module.
|
|
|
|
AuthErrorCode: exhaustive enum of all auth failure conditions.
|
|
TokenError: exhaustive enum of JWT decode failures.
|
|
AuthErrorResponse: structured error payload for HTTP responses.
|
|
"""
|
|
|
|
from enum import StrEnum
|
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
class AuthErrorCode(StrEnum):
|
|
"""Exhaustive list of auth error conditions."""
|
|
|
|
INVALID_CREDENTIALS = "invalid_credentials"
|
|
TOKEN_EXPIRED = "token_expired"
|
|
TOKEN_INVALID = "token_invalid"
|
|
USER_NOT_FOUND = "user_not_found"
|
|
EMAIL_ALREADY_EXISTS = "email_already_exists"
|
|
PROVIDER_NOT_FOUND = "provider_not_found"
|
|
NOT_AUTHENTICATED = "not_authenticated"
|
|
SYSTEM_ALREADY_INITIALIZED = "system_already_initialized"
|
|
WORKSPACE_REQUIRED = "workspace_required"
|
|
|
|
|
|
class TokenError(StrEnum):
|
|
"""Exhaustive list of JWT decode failure reasons."""
|
|
|
|
EXPIRED = "expired"
|
|
INVALID_SIGNATURE = "invalid_signature"
|
|
MALFORMED = "malformed"
|
|
WORKSPACE_MISSING = "workspace_missing"
|
|
|
|
|
|
class AuthErrorResponse(BaseModel):
|
|
"""Structured error response — replaces bare `detail` strings."""
|
|
|
|
code: AuthErrorCode
|
|
message: str
|
|
|
|
|
|
def token_error_to_code(err: TokenError) -> AuthErrorCode:
|
|
"""Map TokenError to AuthErrorCode — single source of truth."""
|
|
if err == TokenError.EXPIRED:
|
|
return AuthErrorCode.TOKEN_EXPIRED
|
|
if err == TokenError.WORKSPACE_MISSING:
|
|
return AuthErrorCode.WORKSPACE_REQUIRED
|
|
return AuthErrorCode.TOKEN_INVALID
|