intellicrack.credentials
Credential management for Intellicrack.
This module handles loading and validating API credentials from multiple sources: - .env files (via CredentialLoader) - OS keyring (via CredentialStore) - OAuth 2.0 flows (via OAuthManager)
- class CredentialLoader[source]
Bases:
objectLoads and manages API credentials from .env file.
This class parses .env files and provides credentials for each supported LLM provider.
- Variables:
PROVIDER_MAPPINGS (ClassVar[dict[str, ProviderCredentialMapping]]) – Mapping of provider names to their credential environment variable configuration.
- PROVIDER_MAPPINGS: ClassVar[dict[str, ProviderCredentialMapping]] = {'anthropic': ProviderCredentialMapping(api_key_var='ANTHROPIC_API_KEY', api_base_var=None, organization_var=None, project_var=None, api_key_aliases=(), default_api_base=None, retired_api_hosts=frozenset()), 'google': ProviderCredentialMapping(api_key_var='GOOGLE_API_KEY', api_base_var=None, organization_var=None, project_var='GOOGLE_CLOUD_PROJECT', api_key_aliases=('GEMINI_API_KEY',), default_api_base=None, retired_api_hosts=frozenset()), 'grok': ProviderCredentialMapping(api_key_var='XAI_API_KEY', api_base_var='XAI_API_BASE', organization_var=None, project_var=None, api_key_aliases=(), default_api_base=None, retired_api_hosts=frozenset()), 'huggingface': ProviderCredentialMapping(api_key_var='HUGGINGFACE_API_TOKEN', api_base_var='HUGGINGFACE_API_BASE', organization_var=None, project_var=None, api_key_aliases=(), default_api_base='https://router.huggingface.co', retired_api_hosts=frozenset({'api-inference.huggingface.co'})), 'local_transformers': ProviderCredentialMapping(api_key_var='LOCAL_TRANSFORMERS_HF_TOKEN', api_base_var='LOCAL_TRANSFORMERS_CACHE_DIR', organization_var=None, project_var=None, api_key_aliases=('HUGGINGFACE_API_TOKEN',), default_api_base=None, retired_api_hosts=frozenset()), 'ollama': ProviderCredentialMapping(api_key_var='OLLAMA_API_KEY', api_base_var='OLLAMA_HOST', organization_var=None, project_var=None, api_key_aliases=(), default_api_base='http://localhost:11434', retired_api_hosts=frozenset()), 'openai': ProviderCredentialMapping(api_key_var='OPENAI_API_KEY', api_base_var='OPENAI_API_BASE', organization_var='OPENAI_ORGANIZATION', project_var='OPENAI_PROJECT', api_key_aliases=(), default_api_base=None, retired_api_hosts=frozenset()), 'openrouter': ProviderCredentialMapping(api_key_var='OPENROUTER_API_KEY', api_base_var='OPENROUTER_API_BASE', organization_var=None, project_var=None, api_key_aliases=(), default_api_base=None, retired_api_hosts=frozenset())}
- classmethod mapping_for(provider)[source]
Return the environment-variable mapping one instance reads.
A built-in provider keeps its historical variable names, so
.envfiles stay byte-compatible. A registered user-defined instance reads the mapping registered for it, which adds its preset’s key variable as an alias. Every other instance id derives its variables from itself, which is what lets a user-defined endpoint be configured from.envat all.- Parameters:
provider (str) – The provider instance id.
- Returns:
The instance’s variable mapping.
- Return type:
- __init__(env_path=None)[source]
Initialize the CredentialLoader with the given env file path.
- Parameters:
env_path (Path | None) – Path to the .env file. If None, searches standard locations.
- Return type:
None
- reload()[source]
Reload credentials from the .env file.
Call this method to pick up changes to the .env file without restarting the application. Variables that were removed from the file since the last load fall back to the value the operating-system environment supplied before the file overrode them.
- Return type:
None
- get_credentials(provider)[source]
Get credentials for a specific provider.
- Parameters:
provider (str) – The LLM provider to get credentials for.
- Returns:
ProviderCredentials if found and valid, None otherwise.
- Return type:
ProviderCredentials | None
- get_connect_credentials(provider, *, api_key_optional)[source]
Resolve the credentials a provider connects with.
Keyed providers resolve exactly like
get_credentials(). Providers that can connect without an API key still receive their saved endpoint settings – for example a customOLLAMA_HOST– when no key is configured, instead of an empty credential set that would silently discard them.- Parameters:
- Returns:
The resolved credentials, or
Nonewhen a required API key is missing or the provider is unknown.- Return type:
ProviderCredentials | None
- env_var_for(provider, field)[source]
Return the environment variable that stores a provider credential field.
- Parameters:
provider (str) – The provider.
field (CredentialField) – The credential field.
- Returns:
The variable name, or
Nonewhen the provider has no variable forfield.- Return type:
str | None
- get_field(provider, field)[source]
Return the effective value of a provider credential field.
The
.envfile takes precedence over the process environment, the API key also honours the provider’s alias variables, and empty values resolve toNone.- Parameters:
provider (str) – The provider.
field (CredentialField) – The credential field.
- Returns:
The effective value, or
Nonewhen unset.- Return type:
str | None
- get_saved_var(name)[source]
Return a variable’s value as held by this loader’s
.envstate.Unlike
get_env_var(), the process environment is ignored, so the result reflects only values loaded from or saved to the.envfile.
- persist_field(provider, field, value)[source]
Persist a provider credential field to the
.envfile.A non-empty value is written only when it differs from the effective value, so a value inherited from the operating-system environment is never copied into the file unchanged. An empty value – or, for a base URL, the provider’s default endpoint – clears the saved override: the variable (and, for an API key, its provider-owned aliases) is removed from the file and any value set outside the application applies again.
- Parameters:
provider (str) – The provider whose field is persisted.
field (CredentialField) – The credential field.
value (str | None) – The value entered by the user;
Noneor blank clears it.
- Returns:
Whether the file was written, a saved value was removed, or nothing changed.
- Return type:
- Raises:
ValueError – If the provider has no environment variable for
field.
- validate_credentials(provider)[source]
Validate that credentials exist and are properly formatted.
- list_configured_providers()[source]
List all providers that have credentials configured.
- list_missing_providers()[source]
List all providers that are missing credentials.
- set_env_var(name, value)[source]
Set an environment variable (in memory only).
- get_env_var(name, default=None)[source]
Get an environment variable value.
Checks the internal cache first, then falls back to os.environ.
- save_to_env_file(name, value)[source]
Save an environment variable to the .env file.
Updates an existing variable or adds a new one at the end of the file. Preserves comments and file structure, and preserves the existing end-of-line style. Uses
\nfor newly created files. Values are quoted and escaped per_quote_env_value()rules to guarantee a lossless round-trip with the parser. AnOSErrorraised while reading or writing the file propagates to the caller.
- remove_from_env_file(name)[source]
Remove a variable from the
.envfile and from this loader.Every line assigning
name(includingexportforms) is deleted while comments, other variables and the file’s end-of-line style are preserved. The process environment falls back to the value the operating system supplied before the file overrode it, so a variable set outside the application still applies. AnOSErrorraised while reading or writing the file propagates to the caller, leaving the loader’s in-memory state unchanged.
- exception CredentialNotFoundError[source]
Bases:
CredentialStoreErrorRequested credential was not found.
- class CredentialSource[source]
Bases:
EnumSource of stored credentials.
- KEYRING = 'keyring'
- ENV_FILE = 'env_file'
- ENV_VAR = 'env_var'
- OAUTH = 'oauth'
- class CredentialStore[source]
Bases:
objectSecure credential storage using OS keyring with env fallback.
This class provides thread-safe, async-compatible access to credentials stored in the operating system’s secure credential storage (Windows Credential Manager on Windows, Keychain on macOS, Secret Service on Linux).
If keyring is unavailable, falls back to CredentialLoader for .env files.
- Variables:
- SERVICE_NAME: Final[str] = 'intellicrack'
- METADATA_KEY: Final[str] = '_metadata'
- __init__(fallback_loader=None)[source]
Initialize the CredentialStore with an optional fallback loader.
- Parameters:
fallback_loader (CredentialLoader | None) – CredentialLoader instance for env-file fallback. If None, creates a new one.
- Return type:
None
- property keyring_available: bool[source]
Check if keyring backend is available and functional.
- Returns:
True if keyring can be used for credential storage.
- Return type:
- async get(provider)[source]
Get credentials for a provider.
Checks keyring first, then falls back to env loader.
- Parameters:
provider (str) – The provider to get credentials for.
- Returns:
ProviderCredentials if found, None otherwise.
- Return type:
ProviderCredentials | None
- async get_secret(key)[source]
Read one value from the keyring alone, reporting every failure.
Unlike
get(), nothing falls back to the env file and nothing is swallowed:Nonemeans the keyring was read and holds no entry underkey, and every other outcome raises. This is what a caller needs when “not stored” leads the operator to re-enter a secret. An entry that exists but cannot be read propagatesKeyringReadErrorfrom the read.- Parameters:
key (str) – The credential key.
- Returns:
The stored credentials, or
Nonewhen the keyring holds nothing underkey.- Return type:
ProviderCredentials | None
- Raises:
KeyringUnavailableError – If no usable keyring backend exists.
- async get_or_raise(provider)[source]
Get credentials for a provider, raising if not found.
- Parameters:
provider (str) – The provider to get credentials for.
- Returns:
ProviderCredentials for the provider.
- Return type:
- Raises:
CredentialNotFoundError – If no credentials are found.
- async set(provider, credentials, key_name=None, source=CredentialSource.KEYRING)[source]
Store credentials for a provider in keyring.
- Parameters:
provider (str) – The provider to store credentials for.
credentials (ProviderCredentials) – The credentials to store.
key_name (str | None) – Optional human-readable name for the credential.
source (CredentialSource) – Origin of the credentials being stored.
- Raises:
KeyringUnavailableError – If keyring is not available.
- Return type:
None
- async delete(provider)[source]
Delete credentials for a provider from keyring.
- Parameters:
provider (str) – The provider to delete credentials for.
- Returns:
True if credentials were deleted, False if not found.
- Return type:
- Raises:
KeyringUnavailableError – If keyring is not available.
- async list_providers()[source]
List all stored credential metadata.
- Returns:
List of StoredCredential with metadata for each provider.
- Return type:
- async migrate_from_env(providers=None, *, overwrite=False)[source]
Migrate credentials from .env file to keyring.
- Parameters:
- Returns:
Dict mapping provider to success status.
- Return type:
- Raises:
KeyringUnavailableError – If keyring is not available.
- async validate(provider)[source]
Validate that a credential exists and is usable.
Shape validation is deliberately minimal and delegates to
validate_key_format(). The old rule rejected a key that did not start with the prefix the built-in provider of that name uses, which was wrong as soon as a provider id could name any endpoint: a gateway in front of Anthropic, an Azure deployment or a LiteLLM proxy all issue their own keys, and refusing them made the endpoint unusable for a cosmetic reason.
- async get_source(provider)[source]
Get the source of credentials for a provider.
- Parameters:
provider (str) – The provider to check.
- Returns:
CredentialSource or None if no credentials found.
- Return type:
CredentialSource | None
- exception CredentialStoreError[source]
Bases:
IntellicrackErrorBase error for credential store operations.
- exception KeyringUnavailableError[source]
Bases:
CredentialStoreErrorKeyring backend is not available.
- exception OAuthAuthorizationError[source]
Bases:
OAuthErrorAuthorization failed or was denied.
- exception OAuthCallbackError[source]
Bases:
OAuthErrorError during OAuth callback handling.
- class OAuthConfig[source]
Bases:
objectOAuth 2.0 configuration for a provider.
- Variables:
provider (OAuthProvider) – The OAuth provider.
client_id (str) – OAuth client ID.
client_secret (str | None) – OAuth client secret (None for PKCE flows).
authorization_url (str) – URL for authorization endpoint.
token_url (str) – URL for token endpoint.
scopes (tuple[str, ...]) – Tuple of OAuth scopes to request.
redirect_uri (str) – Redirect URI for callback.
use_pkce (bool) – Whether to use PKCE (Proof Key for Code Exchange).
revoke_url (str | None) – URL for token revocation endpoint.
- provider: OAuthProvider
- client_id: str
- authorization_url: str
- token_url: str
- redirect_uri: str = 'http://localhost:8080/callback'
- use_pkce: bool = True
- __init__(provider, client_id, client_secret, authorization_url, token_url, scopes, redirect_uri='http://localhost:8080/callback', use_pkce=True, revoke_url=None)
- exception OAuthConfigurationError[source]
Bases:
OAuthErrorOAuth configuration is invalid or incomplete.
- exception OAuthError[source]
Bases:
IntellicrackErrorBase error for OAuth operations.
- class OAuthFlowType[source]
Bases:
EnumSupported OAuth 2.0 flow types.
- AUTHORIZATION_CODE = 'authorization_code'
- class OAuthManager[source]
Bases:
objectManages OAuth 2.0 flows for Intellicrack providers.
Handles authorization code flow with local callback server, token storage via CredentialStore, and automatic token refresh.
- Variables:
DEFAULT_CALLBACK_PORT (ClassVar[int]) – Default port for local callback server.
- DEFAULT_CALLBACK_PORT: ClassVar[int] = 8080
- __init__(credential_store=None, callback_port=8080)[source]
Initialize the OAuthManager with credential storage and callback configuration.
- Parameters:
credential_store (CredentialStore | None) – Store for persisting OAuth tokens. If None, tokens are not persisted.
callback_port (int) – Port for the local OAuth callback server.
- Return type:
None
- async close()[source]
Close resources.
- Return type:
None
- build_authorization_url(config)[source]
Build authorization URL for OAuth flow.
- Parameters:
config (OAuthConfig) – OAuth configuration.
- Returns:
Tuple of (authorization_url, state object).
- Return type:
- Raises:
OAuthConfigurationError – If configuration is invalid.
- async start_authorization_flow(config, *, open_browser=True)[source]
Start an OAuth authorization code flow.
Generates authorization URL and optionally opens browser.
- Parameters:
config (OAuthConfig) – OAuth configuration.
open_browser (bool) – Whether to open the browser automatically.
- Returns:
The authorization URL and its associated state object.
- Return type:
- async handle_callback(code, state)[source]
Handle the OAuth callback with authorization code.
Exchanges code for tokens and stores them. Validates the CSRF state parameter and, when PKCE is enabled, ensures the code_verifier bound to the pending state is present before exchanging the code.
- Parameters:
- Returns:
The obtained OAuth token.
- Return type:
- Raises:
OAuthCallbackError – If state is invalid, expired, or PKCE verifier is missing when required by the flow.
- async get_token(provider, config=None, *, auto_refresh=True)[source]
Get a valid OAuth token for a provider.
Uses the 10-minute
needs_refreshbuffer to refresh tokens proactively before they actually expire so callers never observe a token within the refresh window unless the refresh itself failed.- Parameters:
provider (OAuthProvider) – The OAuth provider.
config (OAuthConfig | None) – OAuth config for refresh (uses default if None).
auto_refresh (bool) – Whether to refresh expired tokens.
- Returns:
Valid OAuthToken or None if not available.
- Return type:
OAuthToken | None
- async refresh_token(provider, config)[source]
Refresh an OAuth token.
A 401 or 403 response from the token endpoint indicates the refresh token is no longer valid and is surfaced as an
OAuthTokenRefreshError. Other HTTP errors raise a genericOAuthTokenErrorso callers can retry without dropping the existing refresh token.- Parameters:
provider (OAuthProvider) – The OAuth provider.
config (OAuthConfig) – OAuth configuration.
- Returns:
The refreshed OAuthToken.
- Return type:
- Raises:
OAuthTokenError – If refresh fails for a non-authentication reason.
OAuthTokenRefreshError – If the refresh token is rejected (401/403).
- async revoke_token(provider)[source]
Revoke and delete OAuth token.
The returned bool reflects whether both the optional remote revocation call (when the provider exposes a
revoke_url) and the local keyring delete succeeded. When no remote endpoint is configured the result reflects only the keyring delete. The in-memory token cache is always cleared so subsequentget_tokencalls do not return a stale token even if revocation reports false.- Parameters:
provider (OAuthProvider) – The OAuth provider.
- Returns:
True if both the remote revocation (if any) and the keyring deletion succeeded.
- Return type:
- async to_provider_credentials(provider, config=None)[source]
Convert OAuth token to ProviderCredentials.
Gets a valid token and creates ProviderCredentials with it.
- Parameters:
provider (OAuthProvider) – The OAuth provider.
config (OAuthConfig | None) – OAuth config for refresh.
- Returns:
ProviderCredentials with OAuth token, or None.
- Return type:
ProviderCredentials | None
- async run_authorization_flow(config)[source]
Run a complete authorization code flow.
Opens browser, waits for callback, and exchanges code for tokens. The local callback server listens on the port and path the redirect URI names, so a provider registered with any loopback redirect path completes. It is always shut down and its socket closed in the
finallyblock so the bind port is released even if the user cancels or the callback times out.- Parameters:
config (OAuthConfig) – OAuth configuration.
- Returns:
The obtained OAuthToken.
- Return type:
- Raises:
OAuthCallbackError – If the redirect URI is not an
httpaddress onlocalhostor127.0.0.1, where the callback server listens.
- class OAuthProvider[source]
Bases:
EnumProviders that support OAuth authentication.
OpenAI is intentionally absent: the OpenAI Platform exposes only API keys, not a public OAuth flow for API access, so users must register a static API key via the credential store instead.
- GOOGLE = 'google'
- ANTHROPIC = 'anthropic'
- HUGGINGFACE = 'huggingface'
- class OAuthState[source]
Bases:
objectState for tracking an OAuth authorization flow.
- Variables:
state (str) – Random state parameter for CSRF protection.
code_verifier (str | None) – PKCE code verifier, or None if not using PKCE.
redirect_uri (str) – Redirect URI used for this authorization flow.
created_at (datetime) – When the authorization flow was initiated.
provider (OAuthProvider) – The OAuth provider for this flow.
config (OAuthConfig) – OAuth configuration for this flow.
- state: str
- redirect_uri: str
- created_at: datetime
- provider: OAuthProvider
- config: OAuthConfig
- is_expired_at(now)[source]
Check if this state has expired at a reference instant.
- property is_expired: bool
Check if this state has expired (10 minute timeout).
- Returns:
True if the state is older than 10 minutes.
- Return type:
- __init__(state, code_verifier, redirect_uri, created_at, provider, config)
- Parameters:
state (str)
code_verifier (str | None)
redirect_uri (str)
created_at (datetime)
provider (OAuthProvider)
config (OAuthConfig)
- Return type:
None
- class OAuthToken[source]
Bases:
objectOAuth 2.0 token data.
- Variables:
- access_token: str
- token_type: str
- is_expired_at(now)[source]
Check if the access token is expired at a reference instant.
- property is_expired: bool
Check if the access token is expired.
- Returns:
True if expired or will expire within 5 minutes.
- Return type:
- needs_refresh_at(now)[source]
Check if the token should be refreshed soon at a reference instant.
- property needs_refresh: bool
Check if the token should be refreshed soon.
- Returns:
True if token will expire within 10 minutes.
- Return type:
- to_dict()[source]
Convert token to dictionary for storage.
- classmethod from_dict(data)[source]
Create token from dictionary.
- exception OAuthTokenError[source]
Bases:
OAuthErrorToken operation failed (exchange, refresh, etc.).
- class ProviderCredentialMapping[source]
Bases:
objectMapping of environment variable names for a provider.
- Variables:
api_key_var (str) – Environment variable name for the primary API key.
api_base_var (str | None) – Environment variable name for custom API base URL.
organization_var (str | None) – Environment variable name for organization ID.
project_var (str | None) – Environment variable name for project ID.
api_key_aliases (tuple[str, ...]) – Alternative environment variable names for the API key.
default_api_base (str | None) – Endpoint the provider uses when no base URL is saved. A saved base URL equal to it is not an override and is never persisted.
retired_api_hosts (frozenset[str]) – Hosts the provider’s service has retired. A saved base URL on one of them is removed from
.envwhen the file is loaded, so the provider falls back todefault_api_base.
- api_key_var: str
- env_var_for(field)[source]
Return the primary environment variable backing a credential field.
- Parameters:
field (CredentialField) – The credential field.
- Returns:
The variable name, or
Nonewhen the provider has no variable forfield.- Return type:
str | None
- __init__(api_key_var, api_base_var=None, organization_var=None, project_var=None, api_key_aliases=(), default_api_base=None, retired_api_hosts=frozenset({}))
- class StoredCredential[source]
Bases:
objectMetadata for a stored credential.
- Variables:
provider (str) – Instance id of the provider this credential belongs to.
key_name (str) – Human-readable name or label for the credential.
created_at (datetime) – When the credential was first stored.
updated_at (datetime) – When the credential was last updated.
source (CredentialSource) – Where the credential originated from.
- provider: str
- key_name: str
- created_at: datetime
- updated_at: datetime
- source: CredentialSource
- __init__(provider, key_name, created_at, updated_at, source)
- Parameters:
provider (str)
key_name (str)
created_at (datetime)
updated_at (datetime)
source (CredentialSource)
- Return type:
None
- async authorize_google(client_id, client_secret=None, scopes=None)[source]
Authorize with Google and return provider credentials.
- Parameters:
- Returns:
ProviderCredentials with OAuth access token.
- Return type:
- get_credential_loader()[source]
Get the global credential loader instance.
The loader is bound to the same state-root
.envfile the application loads at startup (intellicrack.core.config.get_env_file()), so credentials saved through the Provider Settings dialog are the ones the next launch connects with. On an installed build that file lives under%LOCALAPPDATA%\Intellicrackrather than in the working or install directory.- Returns:
The singleton CredentialLoader instance.
- Return type:
- get_credential_store()[source]
Get the global credential store instance.
Uses double-checked locking with a module-level
threading.Lockso concurrent callers from multiple threads cannot observe a partially constructed instance or race to create duplicates.- Returns:
The singleton CredentialStore instance.
- Return type:
- async get_credentials(provider)[source]
Get credentials for a provider using the global store.
- Parameters:
provider (str) – The provider to get credentials for.
- Returns:
ProviderCredentials or None if not configured.
- Return type:
ProviderCredentials | None
- get_oauth_manager()[source]
Get the global OAuth manager instance.
Uses double-checked locking so concurrent callers construct exactly one
OAuthManager.- Returns:
The singleton OAuthManager instance.
- Return type:
Submodules
Credential management for Intellicrack. |
|
OAuth 2.0 flow handling for Intellicrack providers. |
|
Saved provider settings for Intellicrack. |
|
Secure credential storage using OS keyring. |