Metadata-Version: 2.4
Name: fastapi-identity-kit
Version: 0.2.0
Summary: A production-grade OAuth2/OpenID Connect identity provider built with FastAPI, featuring comprehensive security, multi-factor authentication, and enterprise-ready deployment options.
Author-email: Atnatewoshw <icodeyt21@gmail.com>
Requires-Python: >=3.11
Requires-Dist: argon2-cffi>=25.1.0
Requires-Dist: cryptography>=46.0.5
Requires-Dist: fastapi>=0.131.0
Requires-Dist: pydantic>=2.12.5
Requires-Dist: pyjwt>=2.11.0
Requires-Dist: pyotp>=2.9.0
Requires-Dist: python-multipart>=0.0.22
Requires-Dist: sqlalchemy[asyncio]>=2.0.46
Description-Content-Type: text/markdown

# FastAPI Identity Provider

A production-grade OAuth2/OpenID Connect identity provider built with FastAPI, featuring comprehensive security, multi-factor authentication, and enterprise-ready deployment options.

## Quick Start

### Installation

```bash
# Install with uv (recommended)
uv add fastapi-identity-kit

# Or with pip
pip install fastapi-identity-kit
```

### Basic Usage

```python
from fastapi_identity_kit import create_identity_app, IdentityConfig

# Quick setup with defaults
app = create_identity_app(
    database_url="postgresql://user:password@localhost/identity",
    redis_url="redis://localhost:6379/0",
    secret_key="your-secret-key"
)

# Run the app
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

### Add to Existing FastAPI App

```python
from fastapi import FastAPI
from fastapi_identity_kit import add_identity_provider, IdentityConfig

app = FastAPI(title="My Application")

# Add identity provider
identity_config = IdentityConfig(
    database_url="postgresql://user:password@localhost/identity",
    redis_url="redis://localhost:6379/0",
    secret_key="your-secret-key"
)

identity_app = add_identity_provider(app, config=identity_config)

@app.get("/")
async def root():
    return {"message": "My Application with Identity"}
```

## Features

### Security Features
- **OAuth2 Authorization Code Flow** with PKCE (S256)
- **OpenID Connect Core 1.0** compliance
- **JWT RS256 signing** with automated key rotation
- **Refresh token rotation** with replay attack prevention
- **Multi-factor authentication** (TOTP) with distributed lockout
- **Risk-based adaptive authentication** and device fingerprinting
- **HTTPS enforcement** with HSTS preload
- **Database column-level encryption** with key rotation
- **Secret management integration** (Vault, AWS Secrets Manager)

### Architecture
- **Microservices-ready** with clear separation of concerns
- **Multi-tenant support** with RBAC and tenant isolation
- **Scalable design** with Redis caching and connection pooling
- **Comprehensive monitoring** with Prometheus metrics and structured logging
- **Flexible deployment** (direct Python, Docker, cloud-native)

### Testing & Security
- **Comprehensive security testing** with automated CI/CD pipeline
- **Token fuzzing** and replay attack prevention tests
- **Static analysis** with Bandit, Safety, and Semgrep
- **Container security** scanning with Trivy and Grype
- **Dynamic security testing** with OWASP ZAP and Nuclei

## Documentation

- **[Usage Guide](USAGE.md)** - Complete integration guide and examples
- **[Architecture](ARCHITECTURE.md)** - System architecture and security controls
- **[Security](SECURITY.md)** - Security policy and disclosure procedures
- **[Threat Model](THREAT_MODEL.md)** - Comprehensive threat analysis
- **[Production Deployment](PRODUCTION_DEPLOYMENT.md)** - Production setup guide

## Configuration

### Environment Variables

```bash
# Database
DATABASE_URL=postgresql://user:password@localhost/identity
REDIS_URL=redis://localhost:6379/0

# Security
SECRET_KEY=your-super-secret-key
ENFORCE_HTTPS=true
JWT_EXPIRY_MINUTES=60
REFRESH_TOKEN_DAYS=30

# Secret Management
SECRET_PROVIDER=environment  # or vault, aws
VAULT_URL=https://vault.example.com
VAULT_TOKEN=your-vault-token
```

### Configuration Object

```python
from fastapi_identity_kit import IdentityConfig

config = IdentityConfig(
    database_url="postgresql://user:password@localhost/identity",
    redis_url="redis://localhost:6379/0",
    secret_key="your-secret-key",
    enforce_https=True,
    jwt_expiry_minutes=60,
    refresh_token_days=30,
    mfa_issuer="MyApp",
    rate_limit_requests=100,
    key_rotation_enabled=True,
    database_encryption_enabled=True
)
```

## OAuth2/OIDC Endpoints

### OAuth2 Endpoints
```
POST   /oauth/authorize          # Authorization endpoint
POST   /oauth/token             # Token endpoint
POST   /oauth/revoke            # Token revocation
POST   /oauth/introspect        # Token introspection
```

### OpenID Connect Endpoints
```
GET    /.well-known/openid-configuration  # OIDC discovery
GET    /.well-known/jwks.json             # JWKS endpoint
GET    /oauth/userinfo                    # User information
```

### Management Endpoints
```
POST   /auth/login              # Login endpoint
POST   /auth/logout             # Logout endpoint
POST   /auth/register           # User registration
POST   /auth/mfa/setup          # MFA setup
POST   /auth/mfa/verify         # MFA verification
```

## Deployment Options

### Option 1: Direct Python Deployment
```bash
uv add fastapi-identity-kit
uvicorn main:app --host 0.0.0.0 --port 8000 --ssl-keyfile key.pem --ssl-certfile cert.pem
```

### Option 2: Docker Containerization
```dockerfile
FROM python:3.11-slim
RUN pip install uv
WORKDIR /app
COPY requirements.txt .
RUN uv pip install --no-cache -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```

### Option 3: Cloud Native
- **Serverless**: AWS Lambda, Vercel, Railway
- **PaaS**: Heroku, Render, DigitalOcean App Platform
- **Kubernetes**: Full orchestration support

## Development

### Setup Development Environment

```bash
# Clone repository
git clone https://github.com/your-repo/fastapi-identity-kit.git
cd fastapi-identity-kit

# Install dependencies
uv sync

# Run tests
uv run pytest

# Run security tests
uv run pytest -m security

# Run with coverage
uv run pytest --cov=fastapi_identity_kit
```

### Project Structure

```
fastapi_identity_kit/
├── config/                 # Configuration management
│   ├── settings.py         # Environment-based configuration
│   └── secret_manager.py   # Secret management abstraction
├── identity_core/          # Core identity functionality
│   ├── auth_service.py     # Authentication logic
│   ├── password_service.py # Password hashing and validation
│   └── models.py           # SQLAlchemy models
├── identity_server/        # OAuth2/OIDC server
│   ├── router.py           # OAuth2 endpoints
│   └── token_service.py    # JWT token management
├── mfa/                    # Multi-factor authentication
│   ├── totp.py            # TOTP implementation
│   └── lockout.py         # Distributed lockout
├── authorization/         # Authorization and RBAC
│   └── rbac.py            # Role-based access control
├── risk_engine/           # Risk analysis and adaptive auth
│   └── analyzer.py        # Risk scoring engine
├── shared_security/        # Shared security components
│   ├── jwt_engine.py       # JWT signing/verification
│   ├── key_manager.py      # Key management
│   ├── pkce.py            # PKCE implementation
│   ├── crypto_utils.py     # Cryptographic utilities
│   ├── middleware.py       # Security middleware
│   ├── https_middleware.py # HTTPS enforcement
│   ├── key_rotation.py    # Automated key rotation
│   └── database_encryption.py # Database encryption
└── app_factory.py         # Application factory
```

## Security

This identity provider implements comprehensive security measures:

- **Defense in Depth**: Multiple security layers with independent controls
- **Zero Trust**: All requests are authenticated and authorized
- **Encryption**: Data encrypted at rest and in transit
- **Key Management**: Automated key rotation with secure storage
- **Audit Logging**: Comprehensive security event logging
- **Rate Limiting**: Protection against brute force attacks
- **Input Validation**: Comprehensive input sanitization and validation

For detailed security information, see [SECURITY.md](SECURITY.md) and [THREAT_MODEL.md](THREAT_MODEL.md).

## Monitoring & Observability

### Prometheus Metrics
```
# Authentication metrics
auth_requests_total{status="success|failure"}
auth_duration_seconds
mfa_attempts_total{result="success|failure"}

# Token metrics
tokens_issued_total{type="access|refresh"}
tokens_validated_total{result="valid|invalid"}
key_rotation_events_total

# Security metrics
security_events_total{type="replay|brute_force|suspicious"}
rate_limit_hits_total
encryption_operations_total
```

### Health Checks
```
GET /health                    # Application health
GET /health/database          # Database connectivity
GET /health/redis             # Redis connectivity
GET /health/vault             # Secret store connectivity
```

## Testing

### Run All Tests
```bash
uv run pytest
```

### Run Security Tests Only
```bash
uv run pytest -m security
```

### Run with Coverage
```bash
uv run pytest --cov=fastapi_identity_kit --cov-report=html
```

### Performance Testing
```bash
uv run locust -f tests/performance/locustfile.py
```

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Security Contributions
For security vulnerabilities, please follow the disclosure policy in [SECURITY.md](SECURITY.md).

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- [FastAPI](https://fastapi.tiangolo.com/) - Modern, fast web framework for building APIs
- [OAuth 2.0](https://oauth.net/2/) - The OAuth 2.0 authorization framework
- [OpenID Connect](https://openid.net/connect/) - OpenID Connect Core 1.0 specification
- [PyJWT](https://pyjwt.readthedocs.io/) - JSON Web Token implementation in Python

## Support

- **Documentation**: [Full documentation](https://fastapi-identity-kit.readthedocs.io/)
- **Usage Guide**: [Complete integration examples](USAGE.md)
- **Issues**: [GitHub Issues](https://github.com/your-repo/fastapi-identity-kit/issues)
- **Discussions**: [GitHub Discussions](https://github.com/your-repo/fastapi-identity-kit/discussions)
- **Security**: Report security issues to security@example.com

---

**Built for secure, scalable identity management**