Skip to main content

A scalable, framework-agnostic Python authentication library with JWT token management and password reset functionality

Project description

🛡️ AgentAuth — Enterprise AI Agent Security

Python License Tests Coverage PyPI Status

🚀 Ship AI Agents with Enterprise-Grade Security in Minutes

📚 Documentation🚀 Quick Start💡 Examples🤝 Contributing


AgentAuth is a battle-tested, production-ready Python authentication & authorization framework built specifically for AI agents, autonomous systems, and agent-to-agent (A2A) communication. Zero framework coupling. Maximum security.

Used by teams building the future of AI


Features

🔐 Core Authentication

  • AI Agent Identity Management — Register, verify, and trust AI agents with cryptographic key pairs (Ed25519, RSA)
  • Ephemeral Token Issuance — Issue short-lived, cryptographically signed JWT tokens with configurable TTL and scope binding
  • One-Time-Use Tokens — Prevent token replay attacks with secure tracking
  • Token Binding — Bind tokens to specific URLs or IP addresses

🛡️ Authorization & Scopes

  • Per-Action Scope Management — Define fine-grained, application-specific scopes (e.g., db:read, email:send)
  • Trust Level Validation — Enforce trust level requirements (low, medium, high) alongside scopes
  • Decorator-Based Access Control — Simple @require_scope decorator for function-level authorization
  • Context-Aware Verification — Thread-safe context variables for per-request token management

🚨 Security & Compliance

  • Prompt Injection Guard — Detect and block prompt injection attempts with multi-layer heuristics:
    • Suspicious phrase detection
    • Zero-width and RTL character detection
    • Excessive field length validation
    • Dangerous JSON key detection
    • Encoded payload analysis
  • Tamper-Evident Audit Logging — SHA-256 hash chain ensuring audit trail integrity
  • Cryptographic Verification — HMAC-based token signing and verification
  • Password Security — bcrypt hashing with configurable complexity rounds

📊 Auditability

  • Complete Event Logging — Log all authentication, authorization, and security events
  • Chain Integrity Verification — Detect and alert on log tampering
  • Queryable Audit Trail — Filter events by agent, timestamp, event type, and outcome
  • Metadata Support — Attach arbitrary metadata to audit entries

🔧 Framework Agnostic

  • Zero Framework Coupling — Use with FastAPI, Flask, Django, or async Python applications
  • Multiple Storage Backends — SQLAlchemy ORM compatible with PostgreSQL, MySQL, SQLite, and more
  • Extensible Design — Pluggable audit logger, token storage, and custom validators

Installation

From PyPI

pip install agentauth-agents

With Framework Integrations

# FastAPI + Uvicorn support
pip install agentauth-agents[fastapi]

# Flask support
pip install agentauth-agents[flask]

# PostgreSQL support
pip install agentauth-agents[psycopg]

From Source

git clone https://github.com/MrunalHedau4102/agentauth.git
cd agentauth
pip install -e ".[dev]"

Quick Start

1. Setup Database & Models

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from agentauth.db import Base

# Create engine and initialize schema
engine = create_engine("postgresql://user:pass@localhost/agentdb")
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()

2. Register an AI Agent

from agentauth import AgentIdentity, AgentRegistry

# Create agent identity
agent = AgentIdentity(
    agent_id="agent-claude-001",
    display_name="Claude AI Assistant",
    owner="anthropic",
    scopes_requested=["knowledge:search", "tools:execute"]
)

# Generate cryptographic key pair
private_key, public_key = AgentIdentity.generate_keypair(algorithm="ed25519")
agent.public_key = public_key
agent.private_key = private_key

# Register in database
registry = AgentRegistry(session)
registered = registry.register_agent(agent)
print(f"Registered: {registered['agent_id']} with trust level: {registered['trust_level']}")

3. Grant Scopes to Agent

from agentauth import ScopeManager

scope_manager = ScopeManager(session)

# Grant scopes with trust requirements
scope_manager.grant_scope("agent-claude-001", "knowledge:search", trust_level_required="low")
scope_manager.grant_scope("agent-claude-001", "tools:execute", trust_level_required="high")
scope_manager.grant_scope("agent-claude-001", "data:delete", trust_level_required="high")

4. Issue Ephemeral Tokens

from agentauth import EphemeralTokenVault
import os

# Initialize token vault
vault = EphemeralTokenVault(
    secret_key=os.getenv("AGENTAUTH_SECRET_KEY"),
    session=session
)

# Issue token
token = vault.issue(
    agent_id="agent-claude-001",
    scopes=["knowledge:search", "tools:execute"],
    ttl_seconds=300,  # 5-minute lifetime
    bound_to="https://claude.anthropic.com",
    trust_level="high"
)

print(f"Token issued: {token[:20]}...")

5. Verify Tokens & Enforce Scopes

from agentauth import set_current_token, require_scope
import functools

# Verify token
payload = vault.verify(token, expected_bound_to="https://claude.anthropic.com")
print(f"Token valid for agent: {payload['agent_id']}")

# Use context to set token for scope checking
ctx_token = set_current_token(payload)

try:
    @require_scope("knowledge:search", trust_level="low")
    def search_knowledge_base(query: str):
        """This function requires 'knowledge:search' scope."""
        return f"Results for: {query}"
    
    # Function executes successfully if scope is granted
    results = search_knowledge_base("AI agents")
    print(results)

finally:
    # Clean up context
    from agentauth import clear_current_token
    clear_current_token(ctx_token)

6. Guard Against Prompt Injection

from agentauth import PromptInjectionGuard

guard = PromptInjectionGuard(strict=True, max_field_length=2000)

# Inspect tool arguments before execution
try:
    guard.inspect("search_api", {
        "query": "find documents about machine learning",
        "limit": 10
    })
    # Safe to execute tool
except Exception as e:
    print(f"Injection detected: {e}")

7. Audit Event Logging

from agentauth import AuditLogger

audit = AuditLogger(session)

# Log events
audit.log(
    event_type="token_issued",
    agent_id="agent-claude-001",
    outcome="success",
    ip_address="192.168.1.100",
    scopes=["knowledge:search", "tools:execute"],
    metadata={"request_id": "req-12345"}
)

# Verify audit chain integrity
if audit.verify_chain():
    print("Audit trail is tamper-free")

# Query events
recent_events = audit.get_events(agent_id="agent-claude-001")
for event in recent_events:
    print(f"{event['timestamp']}: {event['event_type']} - {event['outcome']}")

Core Concepts

Trust Levels

  • low: Suitable for read-only operations or low-impact actions
  • medium: For general operations with audit logging
  • high: For critical operations (deletions, schema changes, etc.)

Scopes

Scopes define what an agent can do. Examples:

  • db:read — Read from database
  • db:write — Write to database
  • db:delete — Delete from database
  • email:send — Send emails
  • api:call — Call external APIs
  • knowledge:search — Search knowledge base

Tokens

  • Issued with specific scopes and TTL
  • Cryptographically signed with HMAC-SHA256
  • Optionally bound to specific URLs/IPs
  • Can be marked for one-time-use only

Audit Events

Every security-relevant event is logged with:

  • Event type and timestamp
  • Agent and user identifiers
  • IP address and scopes involved
  • Outcome (success/failure)
  • Cryptographic hash chain for tamper detection

API Reference

AgentIdentity

AgentIdentity(
    agent_id: str,
    public_key: Optional[str] = None,
    private_key: Optional[str] = None,
    metadata_url: Optional[str] = None,
    trust_level: str = "untrusted",
    display_name: Optional[str] = None,
    owner: Optional[str] = None,
    scopes_requested: List[str] = []
)

Methods

  • generate_keypair(algorithm: str) -> Tuple[str, str] — Generate cryptographic key pair
  • from_url(url: str) -> AgentIdentity — Fetch agent from remote JSON
  • to_dict() -> Dict — Serialize to dictionary

AgentRegistry

registry = AgentRegistry(session)

# Register agent
registry.register_agent(agent: AgentIdentity) -> Dict

# Retrieve agent
registry.get_agent(agent_id: str) -> AgentIdentity

# Update trust level
registry.trust_agent(agent_id: str, trust_level: str) -> Dict

# Revoke agent
registry.revoke_agent(agent_id: str) -> Dict

# List agents
registry.list_agents(include_revoked: bool = False) -> List[Dict]

EphemeralTokenVault

vault = EphemeralTokenVault(secret_key: str, session: Optional[Session])

# Issue token
vault.issue(
    agent_id: str,
    scopes: Optional[List[str]] = None,
    ttl_seconds: int = 30,
    one_time_use: bool = False,
    bound_to: Optional[str] = None,
    trust_level: str = "low"
) -> str

# Verify token
vault.verify(
    token: str,
    expected_bound_to: Optional[str] = None
) -> Dict

ScopeManager

scope_mgr = ScopeManager(session)

# Grant scope
scope_mgr.grant_scope(agent_id: str, scope: str, trust_level_required: str = "low") -> Dict

# Revoke scope
scope_mgr.revoke_scope(agent_id: str, scope: str) -> bool

# List scopes
scope_mgr.list_scopes(agent_id: str) -> List[Dict]

# Validate scope
scope_mgr.validate_scope(token_payload: Dict, scope: str, trust_level: str = "low") -> bool

@require_scope Decorator

@require_scope("scope:name", trust_level="low")
def protected_function():
    return "This is protected"

# Before calling:
from agentauth import set_current_token, clear_current_token
token_ctx = set_current_token(token_payload)
try:
    protected_function()
finally:
    clear_current_token(token_ctx)

PromptInjectionGuard

guard = PromptInjectionGuard(
    strict: bool = True,
    audit_logger: Optional[AuditLogger] = None,
    max_field_length: int = 2000
)

# Inspect arguments
findings = guard.inspect(tool_name: str, args: Dict[str, Any]) -> List[Dict]

AuditLogger

audit = AuditLogger(session)

# Log event
audit.log(
    event_type: str,
    agent_id: Optional[str] = None,
    user_id: Optional[int] = None,
    outcome: str = "success",
    ip_address: Optional[str] = None,
    scopes: Optional[List[str]] = None,
    metadata: Optional[Dict] = None
) -> Dict

# Verify chain
audit.verify_chain() -> bool

# Query events
audit.get_events(
    agent_id: Optional[str] = None,
    event_type: Optional[str] = None,
    since: Optional[datetime] = None
) -> List[Dict]

Environment Configuration

Create a .env file:

# JWT Configuration
JWT_SECRET_KEY=your-super-secret-key-change-this-in-production
JWT_ALGORITHM=HS256

# Database Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/agentauth_db

# Token Configuration
TOKEN_EXPIRY_MINUTES=15
TOKEN_REFRESH_EXPIRY_DAYS=7

# Password Reset
PASSWORD_RESET_TOKEN_EXPIRY_MINUTES=60

# Bcrypt Configuration
BCRYPT_LOG_ROUNDS=12

See .env.example for all configuration options.

Testing

# Run all tests
pytest tests/ -v

# Run with coverage
pytest tests/ --cov=agentauth --cov-report=html

# Run specific test file
pytest tests/test_agents.py -v

# Run with markers
pytest tests/ -m "not slow" -v

Examples

See the examples/ directory for complete working examples:

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

Security

Found a security vulnerability? Please email mrunalh1234@gmail.com with details. See SECURITY.md for full disclosure policy.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


AgentAuth is maintained by the AuthLib Contributors.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agentauth_agents-1.0.0.tar.gz (75.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agentauth_agents-1.0.0-py3-none-any.whl (80.7 kB view details)

Uploaded Python 3

File details

Details for the file agentauth_agents-1.0.0.tar.gz.

File metadata

  • Download URL: agentauth_agents-1.0.0.tar.gz
  • Upload date:
  • Size: 75.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for agentauth_agents-1.0.0.tar.gz
Algorithm Hash digest
SHA256 060410180a26f5586da77460717a119ebf73c61b8ef616081186faba43218cf0
MD5 89ee6937da9f73ddd4bfd8884f4075d0
BLAKE2b-256 b2a905831e315b94f5e05bf2fd7fe623cd176a2055b697d11c5bc4ec589ee08d

See more details on using hashes here.

Provenance

The following attestation bundles were made for agentauth_agents-1.0.0.tar.gz:

Publisher: publish.yml on MrunalHedau4102/agentauth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file agentauth_agents-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agentauth_agents-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8f12df8ed678d5d59dbe718661453021e6f28a7f775afac601f2517cc96c6d73
MD5 7e02718dcb008a7261f2ed9af9105126
BLAKE2b-256 832dc0ab215645a73a0dd8e31bd11cd56f07992ae1777f726448b23cdb532ce1

See more details on using hashes here.

Provenance

The following attestation bundles were made for agentauth_agents-1.0.0-py3-none-any.whl:

Publisher: publish.yml on MrunalHedau4102/agentauth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page