Authentication Guide

API Key Authentication

The simplest form of authentication:

from agentic_fleet import Agent

agent = Agent(
    name="assistant",
    api_key="your-api-key"
)

Environment Variables

Secure API key storage:

AGENTIC_FLEET_API_KEY=your_api_key
OPENAI_API_KEY=your_openai_key
ANTHROPIC_API_KEY=your_anthropic_key
import os
from agentic_fleet import Agent

agent = Agent(
    name="assistant",
    api_key=os.getenv("AGENTIC_FLEET_API_KEY")
)

Bearer Token Authentication

For web applications:

from agentic_fleet.auth import BearerAuth

auth = BearerAuth(
    token="your-token",
    scheme="Bearer"
)

agent = Agent(
    name="assistant",
    auth=auth
)

OAuth2 Integration

from agentic_fleet.auth import OAuth2Auth

auth = OAuth2Auth(
    client_id="your-client-id",
    client_secret="your-client-secret",
    auth_url="https://auth.example.com/oauth/token"
)

# Use with agent
agent = Agent(
    name="assistant",
    auth=auth
)

Custom Authentication

Create custom authentication:

from agentic_fleet.auth import BaseAuth

class CustomAuth(BaseAuth):
    def __init__(self, credentials):
        self.credentials = credentials
    
    async def authenticate(self) -> bool:
        # Implement authentication logic
        return await self.verify_credentials()
    
    async def refresh(self):
        # Implement token refresh
        pass

# Use custom auth
auth = CustomAuth(credentials)
agent = Agent(name="assistant", auth=auth)

Multi-tenant Authentication

from agentic_fleet.auth import TenantAuth

auth = TenantAuth(
    tenant_id="tenant-123",
    api_key="tenant-api-key"
)

agent = Agent(
    name="assistant",
    auth=auth
)

Role-based Authentication

from agentic_fleet.auth import RoleAuth

auth = RoleAuth(
    roles=["admin", "user"],
    permissions=["read", "write"]
)

agent = Agent(
    name="assistant",
    auth=auth
)

Secure Storage

Store credentials securely:

from agentic_fleet.auth import SecureStorage

# Initialize secure storage
storage = SecureStorage(
    encryption_key="your-key"
)

# Store credentials
await storage.store(
    "api_key",
    "your-api-key"
)

# Retrieve credentials
api_key = await storage.get("api_key")

Session Management

from agentic_fleet.auth import SessionManager

# Create session manager
sessions = SessionManager(
    timeout=3600,
    max_sessions=100
)

# Create session
session = await sessions.create(
    user_id="user123"
)

# Validate session
is_valid = await sessions.validate(
    session.token
)

Rate Limiting

from agentic_fleet.auth import RateLimiter

limiter = RateLimiter(
    limit=100,
    window=60
)

# Check rate limit
allowed = await limiter.check(
    user_id="user123"
)

Best Practices

  1. Never hardcode credentials
  2. Use environment variables
  3. Implement proper encryption
  4. Regular key rotation
  5. Monitor authentication attempts
  6. Implement rate limiting
  7. Use secure connections
  8. Log authentication events

Security Checklist

  • Use HTTPS/SSL
  • Implement rate limiting
  • Store credentials securely
  • Monitor authentication attempts
  • Regular key rotation
  • Proper error handling
  • Audit logging
  • Session management

Error Handling

from agentic_fleet.exceptions import AuthError

try:
    await auth.authenticate()
except AuthError as e:
    logger.error(f"Authentication failed: {e}")
    # Handle error

Logging

from agentic_fleet.auth import setup_auth_logging

# Configure authentication logging
setup_auth_logging(
    level="INFO",
    file="auth.log"
)

Monitoring

from agentic_fleet.auth import AuthMonitor

monitor = AuthMonitor()

# Track authentication events
await monitor.track(
    event_type="login",
    user_id="user123",
    success=True
)

# Get authentication stats
stats = await monitor.get_stats()

Advanced Authentication Scenarios

Microservices Authentication

from agentic_fleet.auth import ServiceAuth

# Create service authentication
auth = ServiceAuth(
    service_name="code-fleet",
    service_key="service-key",
    allowed_services=["data-fleet", "chat-fleet"]
)

# Use with fleet
fleet = FleetChat(
    name="development",
    auth=auth
)

JWT Authentication

from agentic_fleet.auth import JWTAuth
import jwt

# Create JWT auth
auth = JWTAuth(
    secret_key="your-secret",
    algorithm="HS256",
    token_expiry=3600
)

# Generate token
token = auth.create_token(
    user_id="user123",
    claims={
        "role": "admin",
        "tenant": "org123"
    }
)

# Verify token
payload = auth.verify_token(token)

Multi-Factor Authentication

from agentic_fleet.auth import MFAAuth

# Setup MFA
mfa = MFAAuth(
    primary_auth=api_key_auth,
    secondary_auth=totp_auth
)

# Authenticate with MFA
auth_result = await mfa.authenticate(
    primary_token="api-key",
    secondary_token="123456"
)

SSO Integration

from agentic_fleet.auth import SSOAuth

# Configure SSO
sso = SSOAuth(
    provider="okta",
    client_id="client-id",
    client_secret="client-secret",
    redirect_uri="https://api.example.com/callback"
)

# Initialize SSO flow
auth_url = sso.get_authorization_url()

# Handle callback
tokens = await sso.handle_callback(code="auth-code")

Security Tutorials

1. Secure Key Management

from agentic_fleet.auth import KeyManager
from cryptography.fernet import Fernet

# Initialize key manager
key_manager = KeyManager(
    encryption_key=Fernet.generate_key(),
    rotation_period=30  # days
)

# Store API key
await key_manager.store_key(
    key_name="openai-key",
    key_value="sk-...",
    metadata={
        "service": "openai",
        "environment": "production"
    }
)

# Rotate keys
await key_manager.rotate_keys()

2. Audit Logging

from agentic_fleet.auth import AuditLogger

# Setup audit logging
audit = AuditLogger(
    log_level="INFO",
    storage="elasticsearch"
)

# Log authentication event
await audit.log_event(
    event_type="authentication",
    user_id="user123",
    status="success",
    metadata={
        "ip": "192.168.1.1",
        "user_agent": "Mozilla/5.0..."
    }
)

3. Rate Limiting Strategies

from agentic_fleet.auth import RateLimiter
from agentic_fleet.auth.strategies import (
    TokenBucket,
    SlidingWindow,
    LeakyBucket
)

# Token bucket strategy
limiter = RateLimiter(
    strategy=TokenBucket(
        capacity=100,
        refill_rate=10
    )
)

# Sliding window strategy
limiter = RateLimiter(
    strategy=SlidingWindow(
        window_size=60,
        max_requests=100
    )
)

# Leaky bucket strategy
limiter = RateLimiter(
    strategy=LeakyBucket(
        capacity=100,
        leak_rate=1
    )
)

Production Deployment

1. Key Rotation

from agentic_fleet.auth import KeyRotation

rotation = KeyRotation(
    schedule="0 0 1 * *",  # Monthly
    notification_email="[email protected]"
)

# Add rotation hook
@rotation.on_rotate
async def handle_rotation(old_key, new_key):
    # Update services with new key
    await update_services(new_key)
    # Revoke old key after grace period
    await schedule_revocation(old_key, delay="7d")

2. Security Monitoring

from agentic_fleet.auth import SecurityMonitor

monitor = SecurityMonitor(
    alerts_webhook="https://alerts.example.com",
    rules=[
        {
            "type": "failed_auth",
            "threshold": 5,
            "window": "5m",
            "action": "block_ip"
        },
        {
            "type": "suspicious_activity",
            "indicators": ["multiple_ips", "unusual_times"],
            "action": "notify_admin"
        }
    ]
)

3. Compliance Logging

from agentic_fleet.auth import ComplianceLogger

logger = ComplianceLogger(
    retention_period="1y",
    encryption=True,
    compliance_standards=["SOC2", "GDPR"]
)

# Log sensitive operations
await logger.log_operation(
    operation="key_access",
    user="user123",
    resource="api_key",
    justification="deployment"
)