Traigent SDK Authentication Guide¶
Overview¶
The Traigent SDK provides a modern, secure authentication system that follows industry best practices from tools like GitHub CLI and AWS CLI. This guide covers how to authenticate and manage your credentials.
Quick Start¶
1. Interactive Login (Recommended)¶
The easiest way to authenticate is using the interactive CLI:
traigent auth login
This will: 1. Prompt for your email and password 2. Authenticate with the Traigent backend 3. Generate a long-lived API key 4. Store credentials securely on your system
2. Environment Variable¶
Set your API key as an environment variable:
export TRAIGENT_API_KEY=your_api_key_here
Tip: Credentials saved through
traigent auth loginare resolved by the SDK automatically via the built-in Credential Manager, so you never need to copy keys into code.
3. Direct API Key Configuration¶
If you already have an API key:
traigent auth configure
# Select option 2 and enter your API key
Custom Backend URL¶
By default the SDK and CLI target https://portal.traigent.ai. To authenticate against a different backend, use --backend-url:
traigent auth login --backend-url https://your-backend.example.com
The URL is stored in your credentials so subsequent SDK calls use it automatically.
You can also set the backend via environment variables:
export TRAIGENT_BACKEND_URL=https://your-backend.example.com
Verify which backend you're pointing to with:
traigent auth status
Authentication Commands¶
Login¶
Authenticate with the Traigent backend:
# Interactive login
traigent auth login
# Login with email
traigent auth login --email user@example.com
# Non-interactive mode (fails without prompts)
traigent auth login --email user@example.com --non-interactive
Note: Non-interactive mode does not prompt for a password. For CI/CD, use
TRAIGENT_API_KEYinstead oftraigent auth login.
Check Status¶
View your current authentication status:
traigent auth status
Output shows: - Authentication status - User email and ID - Backend URL - Whether an API key is configured (the key is never shown)
Logout¶
Clear stored credentials:
traigent auth logout
This removes all locally stored credentials. Your API key remains valid on the backend.
Refresh Tokens¶
Refresh expired JWT tokens:
traigent auth refresh
Note: API keys don't expire and don't need refresh.
Configure¶
Interactive configuration wizard:
traigent auth configure
Options: - Change backend URL - Select authentication method - Set up API key
Who Am I¶
Check that the API key the SDK sends to the backend is valid:
traigent auth whoami
Without an argument, whoami validates the key the SDK resolves:
TRAIGENT_API_KEY first, then an API key stored by traigent auth login, then
TRAIGENT_DEV_API_KEY only when development mode is explicitly enabled. JWT
sessions are not used. It prints where the key came from, never the key itself,
and exits non-zero when no key is found.
Do not pass the key as an argument: a command-line argument is visible in the process list and in shell history.
Automatic Credential Discovery¶
Unified authentication leverages the shared CredentialManager to look for credentials in a secure order. When the CLI stores an API key or refresh token, the SDK reuses it automatically during runtime. This removes the need to duplicate configuration across environments while keeping sensitive material out of source code.
The discovery order is:
- System environment variable (TRAIGENT_API_KEY)
- CLI-managed credentials saved via traigent auth login in encrypted local storage
- Development defaults only when explicit test flags are enabled
If nothing is found, the CLI will prompt you during traigent auth login; the SDK expects explicit configuration or environment variables.
Credential Storage¶
Credentials saved by traigent auth login and traigent auth configure are written through the SDK secure credential store. The legacy ~/.traigent/credentials.json plaintext file is ignored unless TRAIGENT_ALLOW_PLAINTEXT_CREDENTIALS=true is set explicitly for one-time migration.
1. Secure Local Storage¶
- Encrypted credential store managed by the SDK
- Raw API keys and refresh tokens are not written to plaintext CLI credential files
TRAIGENT_MASTER_PASSWORDis required so the SDK can derive the encryption key for file-backed credential storage
2. Environment Variables¶
TRAIGENT_API_KEY- Useful for CI/CD environments
Backend vs provider credentials¶
This guide covers Traigent backend authentication: the API key that lets the
SDK and CLI talk to the Traigent portal/backend. Model-provider credentials
such as OPENAI_API_KEY or AWS credentials for Bedrock are separate customer
credentials resolved by the provider SDKs on the local machine. They are not
Traigent API keys and are not sent to Traigent backend endpoints.
For the full boundary, including Bedrock and telemetry/content logging, see the Credential & data trust model and the telemetry documentation.
Priority Order¶
The SDK checks for credentials in this order:
1. Environment variables (highest priority)
2. CLI stored credentials (from traigent auth login)
3. Explicit dev-mode credentials — only when both of these are set:
- TRAIGENT_DEV_MODE=true (or TRAIGENT_GENERATE_MOCKS=true)
- TRAIGENT_DEV_API_KEY=<value>
Setting only the dev-mode flag (without TRAIGENT_DEV_API_KEY) returns no
credential — the SDK does not ship a hard-coded sentinel string fallback.
This keeps an accidental TRAIGENT_DEV_MODE=true in production strictly
inert rather than handing out a known string the backend may have hardcoded
for testing.
Security Features¶
Secure Token Management¶
- Tokens are wrapped in in-memory
SecureTokencontainers so raw values are never logged or persisted - Automatic memory clearing when tokens are no longer needed
- Token values masked in all string representations
- Constant-time string comparison to prevent timing attacks
- Background refresh uses the resilient HTTP client with exponential backoff to renew tokens before expiry
Rate Limiting Protection¶
- Exponential backoff after failed authentication attempts
- Maximum 3 failures before rate limiting
- Automatic jitter to prevent thundering herd
- Rate limit resets after successful authentication
SOC2 Compliance¶
- Comprehensive audit logging for authentication events
- No sensitive data in logs
- Secure credential storage
- Automatic token refresh before expiry
Integration with SDK¶
Once authenticated, the SDK automatically uses your credentials:
import asyncio
import traigent
# The SDK automatically finds credentials from:
# 1. Environment variables
# 2. CLI auth (traigent auth login)
# 3. Development defaults
@traigent.optimize(
evaluation={"eval_dataset": "data.jsonl"},
configuration_space={"model": ["gpt-4.1", "gpt-4.1-mini"]}
)
def my_function(input_text: str) -> str:
config = traigent.get_config()
return f"{config['model']}: {input_text}"
# Optimization automatically uses authenticated backend
results = asyncio.run(my_function.optimize())
Backend Integration¶
The authentication system works with the managed Traigent backend:
Supported Authentication Methods¶
- JWT Tokens
- Short-lived (1 hour default)
- Automatic refresh support
-
Used for initial authentication
-
API Keys
- Long-lived tokens
- Generated after JWT authentication
- Preferred for SDK usage
API Endpoints¶
Backend endpoints are managed and may vary by deployment. Use the CLI and SDK APIs rather than hardcoding URLs.
Troubleshooting¶
Authentication Failed¶
-
Check your credentials:
traigent auth status -
Try logging in again:
traigent auth logout traigent auth login -
Verify backend URL:
traigent auth configure
Rate Limited¶
If you see "Rate limit exceeded": - Wait for the specified retry time - Check for correct credentials - Contact support if the issue persists
Token Expired¶
JWT tokens are short-lived:
traigent auth refresh
Or switch to API keys (recommended):
traigent auth login # Generates API key automatically
CI/CD Integration¶
For automated environments:
GitHub Actions¶
- name: Configure Traigent
env:
TRAIGENT_API_KEY: ${{ secrets.TRAIGENT_API_KEY }}
run: |
# SDK automatically uses environment variable
python your_optimization_script.py
Docker¶
Inject the API key when the container starts, not when the image is built:
# Name only: Docker copies the value from the caller's environment
docker run --rm -e TRAIGENT_API_KEY your-image
You can also use docker run --env-file with a gitignored file, or your
orchestrator's secret mechanism. Never pass the key through a Dockerfile ARG
or ENV instruction or docker build --build-arg: it persists in the image
metadata and in docker history, and travels wherever the image is pushed.
# Or mount CLI-managed encrypted credentials
VOLUME /root/.traigent
When mounting CLI-managed credentials in containers, provide the same
TRAIGENT_MASTER_PASSWORD used when the file-backed encrypted store was
created. The mounted encrypted store cannot be unlocked without this
environment variable.
Jenkins¶
withCredentials([string(credentialsId: 'traigent-api-key', variable: 'TRAIGENT_API_KEY')]) {
sh 'python your_optimization_script.py'
}
Best Practices¶
- Use API Keys for Production
- More stable than JWT tokens
- No refresh needed
-
Better for long-running processes
-
Rotate Keys Regularly
- Generate new keys periodically
-
Remove unused keys from backend
-
Use Environment Variables in CI/CD
- Never commit credentials to code
-
Use secure secret management
-
Monitor Authentication Events
- Check audit logs for suspicious activity
- Review failed authentication attempts
API Reference¶
Python API¶
from traigent.cloud.credential_manager import CredentialManager
# Check if authenticated
is_auth = CredentialManager.is_authenticated()
# Get API key
api_key = CredentialManager.get_api_key()
# Get auth headers
headers = CredentialManager.get_auth_headers()
# Get full credentials
creds = CredentialManager.get_credentials()
# Clear credentials
CredentialManager.clear_credentials()
CLI Commands¶
# Main commands
traigent auth login # Authenticate
traigent auth logout # Clear credentials
traigent auth status # Check status
traigent auth refresh # Refresh tokens
traigent auth configure # Configuration wizard
traigent auth whoami # Validate the API key the SDK will send
# Options
--email EMAIL # Specify email
--non-interactive # No prompts; use API keys for CI/CD
--backend-url URL # Target a specific backend URL
--help # Show help
Migration Guide¶
If you're migrating from the old authentication system:
Old Method¶
# Manual API key management
os.environ["TRAIGENT_API_KEY"] = "your_key"
New Method¶
# Use CLI for secure storage
traigent auth login
# Or continue using environment variables
export TRAIGENT_API_KEY=your_key
The new system remains compatible with existing TRAIGENT_API_KEY workflows.
Migrating from ~/.traigent/credentials.json¶
Older CLI versions wrote credentials to ~/.traigent/credentials.json. Current
SDK releases ignore that plaintext file by default. For one-time migration:
export TRAIGENT_MASTER_PASSWORD="<new encrypted-store password>"
export TRAIGENT_ALLOW_PLAINTEXT_CREDENTIALS=true
traigent auth status # Optional: confirms the old plaintext key is still valid
traigent auth logout # Deletes the legacy plaintext file so login cannot reuse it
unset TRAIGENT_ALLOW_PLAINTEXT_CREDENTIALS
traigent auth login # Fresh login writes to the encrypted credential store
Keep TRAIGENT_MASTER_PASSWORD available for future CLI and SDK processes that
need to unlock the encrypted store. Do not leave
TRAIGENT_ALLOW_PLAINTEXT_CREDENTIALS set after the legacy file has been
removed.
If you previously relied on a local .master_password file for an older
encrypted store, set TRAIGENT_ALLOW_LEGACY_LOCAL_MASTER_PASSWORD=true only
long enough to read or clear that old store. Unset it before the fresh
traigent auth login that writes credentials with TRAIGENT_MASTER_PASSWORD.
Support¶
For authentication issues:
- Check the Troubleshooting section
- Open a GitHub issue with the CLI output and backend URL
- For security reports, follow the guidance in
docs/contributing/SECURITY.md