Skip to content

ccproxy.auth

ccproxy.auth

Authentication module for centralized auth handling.

BearerTokenAuthManager

BearerTokenAuthManager(token)

Authentication manager for static bearer tokens.

Parameters:

Name Type Description Default
token str

Bearer token string

required
Source code in ccproxy/auth/bearer.py
def __init__(self, token: str) -> None:
    """Initialize with a static bearer token.

    Args:
        token: Bearer token string
    """
    self.token = token.strip()
    if not self.token:
        raise ValueError("Token cannot be empty")

get_access_token async

get_access_token()

Get the bearer token.

Returns:

Type Description
str

Bearer token string

Raises:

Type Description
AuthenticationError

If token is invalid

Source code in ccproxy/auth/bearer.py
async def get_access_token(self) -> str:
    """Get the bearer token.

    Returns:
        Bearer token string

    Raises:
        AuthenticationError: If token is invalid
    """
    if not self.token:
        raise AuthenticationError("No bearer token available")
    return self.token

get_credentials async

get_credentials()

Bearer tokens do not expose structured credentials.

Source code in ccproxy/auth/bearer.py
async def get_credentials(self) -> BaseCredentials:
    """Bearer tokens do not expose structured credentials."""
    raise AuthenticationError(
        "Bearer token authentication doesn't support full credentials"
    )

is_authenticated async

is_authenticated()

Check if bearer token is available.

Returns:

Type Description
bool

True if token is available, False otherwise

Source code in ccproxy/auth/bearer.py
async def is_authenticated(self) -> bool:
    """Check if bearer token is available.

    Returns:
        True if token is available, False otherwise
    """
    return bool(self.token)

get_user_profile async

get_user_profile()

Return None because bearer tokens have no profile context.

Source code in ccproxy/auth/bearer.py
async def get_user_profile(self) -> StandardProfileFields | None:
    """Return ``None`` because bearer tokens have no profile context."""
    return None

validate_credentials async

validate_credentials()

Validate that credentials are available and valid.

Returns:

Type Description
bool

True if credentials are valid, False otherwise

Source code in ccproxy/auth/bearer.py
async def validate_credentials(self) -> bool:
    """Validate that credentials are available and valid.

    Returns:
        True if credentials are valid, False otherwise
    """
    return bool(self.token)

get_provider_name

get_provider_name()

Get the provider name for logging.

Returns:

Type Description
str

Provider name string

Source code in ccproxy/auth/bearer.py
def get_provider_name(self) -> str:
    """Get the provider name for logging.

    Returns:
        Provider name string
    """
    return "bearer-token"

AuthenticationError

Bases: Exception

Base authentication error.

AuthenticationRequiredError

Bases: AuthenticationError

Authentication is required but not provided.

CredentialsError

Bases: AuthenticationError

Base credentials error.

CredentialsExpiredError

Bases: CredentialsError

Credentials expired error.

CredentialsInvalidError

Bases: CredentialsError

Credentials are invalid or malformed.

CredentialsNotFoundError

Bases: CredentialsError

Credentials not found error.

CredentialsStorageError

Bases: CredentialsError

Error occurred during credentials storage operations.

InsufficientPermissionsError

Bases: AuthenticationError

Insufficient permissions for the requested operation.

InvalidTokenError

Bases: AuthenticationError

Invalid or expired token.

OAuthError

Bases: AuthenticationError

Base OAuth error.

OAuthTokenRefreshError

Bases: OAuthError

OAuth token refresh failed.

AuthManager

Bases: Protocol

Unified authentication manager protocol for all providers.

This protocol defines the complete interface that all authentication managers must implement, supporting both provider-specific methods (like Claude credentials) and generic methods (like auth headers) for maximum flexibility.

get_access_token async

get_access_token()

Get valid access token.

Returns:

Type Description
str

Access token string

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in ccproxy/auth/manager.py
async def get_access_token(self) -> str:
    """Get valid access token.

    Returns:
        Access token string

    Raises:
        AuthenticationError: If authentication fails
    """
    ...

get_credentials async

get_credentials()

Get valid credentials.

Note: For non-Claude providers, this may return minimal/dummy credentials or raise AuthenticationError if not supported.

Returns:

Type Description
BaseCredentials

Valid credentials

Raises:

Type Description
AuthenticationError

If authentication fails or not supported

Source code in ccproxy/auth/manager.py
async def get_credentials(self) -> BaseCredentials:
    """Get valid credentials.

    Note: For non-Claude providers, this may return minimal/dummy credentials
    or raise AuthenticationError if not supported.

    Returns:
        Valid credentials

    Raises:
        AuthenticationError: If authentication fails or not supported
    """
    ...

is_authenticated async

is_authenticated()

Check if current authentication is valid.

Returns:

Type Description
bool

True if authenticated, False otherwise

Source code in ccproxy/auth/manager.py
async def is_authenticated(self) -> bool:
    """Check if current authentication is valid.

    Returns:
        True if authenticated, False otherwise
    """
    ...

get_user_profile async

get_user_profile()

Get standardized user profile information.

Returns:

Type Description
StandardProfileFields | None

Standardized profile details when available, otherwise None

StandardProfileFields | None

for providers that do not expose profile metadata.

Source code in ccproxy/auth/manager.py
async def get_user_profile(self) -> StandardProfileFields | None:
    """Get standardized user profile information.

    Returns:
        Standardized profile details when available, otherwise ``None``
        for providers that do not expose profile metadata.
    """
    ...

validate_credentials async

validate_credentials()

Validate that credentials are available and valid.

Returns:

Type Description
bool

True if credentials are valid, False otherwise

Source code in ccproxy/auth/manager.py
async def validate_credentials(self) -> bool:
    """Validate that credentials are available and valid.

    Returns:
        True if credentials are valid, False otherwise
    """
    ...

get_provider_name

get_provider_name()

Get the provider name for logging.

Returns:

Type Description
str

Provider name string (e.g., "anthropic-claude", "openai-codex")

Source code in ccproxy/auth/manager.py
def get_provider_name(self) -> str:
    """Get the provider name for logging.

    Returns:
        Provider name string (e.g., "anthropic-claude", "openai-codex")
    """
    ...

TokenStorage

Bases: ABC, Generic[CredentialsT]

Abstract interface for token storage operations.

This is a generic interface that can work with any credential type that extends BaseModel (e.g., ClaudeCredentials, OpenAICredentials).

load abstractmethod async

load()

Load credentials from storage.

Returns:

Type Description
CredentialsT | None

Parsed credentials if found and valid, None otherwise

Source code in ccproxy/auth/storage/base.py
@abstractmethod
async def load(self) -> CredentialsT | None:
    """Load credentials from storage.

    Returns:
        Parsed credentials if found and valid, None otherwise
    """
    pass

save abstractmethod async

save(credentials)

Save credentials to storage.

Parameters:

Name Type Description Default
credentials CredentialsT

Credentials to save

required

Returns:

Type Description
bool

True if saved successfully, False otherwise

Source code in ccproxy/auth/storage/base.py
@abstractmethod
async def save(self, credentials: CredentialsT) -> bool:
    """Save credentials to storage.

    Args:
        credentials: Credentials to save

    Returns:
        True if saved successfully, False otherwise
    """
    pass

exists abstractmethod async

exists()

Check if credentials exist in storage.

Returns:

Type Description
bool

True if credentials exist, False otherwise

Source code in ccproxy/auth/storage/base.py
@abstractmethod
async def exists(self) -> bool:
    """Check if credentials exist in storage.

    Returns:
        True if credentials exist, False otherwise
    """
    pass

delete abstractmethod async

delete()

Delete credentials from storage.

Returns:

Type Description
bool

True if deleted successfully, False otherwise

Source code in ccproxy/auth/storage/base.py
@abstractmethod
async def delete(self) -> bool:
    """Delete credentials from storage.

    Returns:
        True if deleted successfully, False otherwise
    """
    pass

get_location abstractmethod

get_location()

Get the storage location description.

Returns:

Type Description
str

Human-readable description of where credentials are stored

Source code in ccproxy/auth/storage/base.py
@abstractmethod
def get_location(self) -> str:
    """Get the storage location description.

    Returns:
        Human-readable description of where credentials are stored
    """
    pass

get_access_token async

get_access_token(auth_manager)

Retrieve an access token from an authenticated manager.

Source code in ccproxy/auth/dependencies.py
async def get_access_token(
    auth_manager: Annotated[AuthManager, Depends(require_auth)],
) -> str:
    """Retrieve an access token from an authenticated manager."""

    try:
        return await auth_manager.get_access_token()
    except AuthenticationError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(exc),
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc

get_auth_manager async

get_auth_manager(credentials, settings)

Return an authentication manager when credentials are required.

Source code in ccproxy/auth/dependencies.py
async def get_auth_manager(
    credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer_scheme)],
    settings: SettingsDep,
) -> AuthManager:
    """Return an authentication manager when credentials are required."""

    auth_manager = await _build_bearer_auth_manager(
        credentials,
        _expected_token(settings),
        require_credentials=True,
    )
    # require_credentials ensures auth_manager is never None here.
    assert auth_manager is not None
    return auth_manager

require_auth async

require_auth(auth_manager)

Enforce authentication, translating failures into HTTP errors.

Source code in ccproxy/auth/dependencies.py
async def require_auth(
    auth_manager: Annotated[AuthManager, Depends(get_auth_manager)],
) -> AuthManager:
    """Enforce authentication, translating failures into HTTP errors."""

    try:
        if not await auth_manager.is_authenticated():
            raise AuthenticationRequiredError("Authentication required")
        return auth_manager
    except AuthenticationError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(exc),
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc