audittrail 1.0.1
Production-ready tamper-proof audit trail library with digital signatures, WORM protection, and compliance reporting for Python web frameworks.
License: MIT
Requires Python: >=3.8
Keywords: audit, logging, compliance, security, tamper-proof, blockchain, WORM, signatures, SOX, HIPAA, PCI-DSS

# audittrail

**audittrail** is a lightweight, open-source Python library for creating a **tamper-proof audit trail** of API activity. It works as a plug-and-play middleware for FastAPI (and soon Flask/Django), automatically recording each request and cryptographically linking entries to prevent undetected tampering.

---

## Features

### Core Features
- **Tamper-proof logging** — Each log entry is hashed and chained to the previous one.
- **Plug-and-play middleware** — Just import and add it to your FastAPI app.
- **Verifiable ledger** — Easily confirm the integrity of your audit log.
- **Encrypted payloads** — Request/response bodies are encrypted at rest.
- **CLI tools** — Command-line interface for verification, monitoring, and reporting.
- **Lightweight storage** — Uses SQLite backend by default.

### Compliance Features (Optional)
- **Digital signatures** — RSA signatures for non-repudiation.
- **Timestamp authorities** — Cryptographic proof of creation time.
- **WORM protection** — Write-Once-Read-Many immutability.
- **Anomaly detection** — Real-time threat monitoring with configurable alerts.
- **Role-based access** — Viewer, Verifier, and Admin roles with permissions.
- **Compliance reporting** — Professional HTML/JSON reports for auditors.

---

## Installation

```bash
pip install audittrail
```

or from source:

```bash
git clone https://github.com/ethanbonsall/audittrail-py.git
cd audittrail-py
pip install .
```

---

## ⚡ Quick Start (FastAPI Example)

```python
from fastapi import FastAPI
from audittrail import AuditTrailMiddleware, verify_ledger

app = FastAPI()
app.add_middleware(AuditTrailMiddleware, storage_path="audit_log.db")

@app.post("/create")
def create_item(item: dict):
    return {"msg": "created", "item": item}

# Verify the integrity of the log manually
print(verify_ledger("audit_log.db"))
```

Every incoming request is logged in `audit_log.db` with a cryptographic hash linking it to the previous entry.

### 🔒 Enhanced Compliance Mode

For production banking and financial applications, enable advanced compliance features:

```python
app.add_middleware(
    AuditTrailMiddleware, 
    storage_path="audit_log.db",
    enable_compliance=True  # Enables digital signatures, timestamps, and WORM protection
)
```

See [COMPLIANCE_FEATURES.md](COMPLIANCE_FEATURES.md) for full documentation.

---

## Example Log Entry

| ts | method | path | user | status | hash | prev_hash |
|----|---------|------|------|---------|------|------------|
| 2025-10-19T22:01Z | POST | /create | anonymous | 201 | `a8f92d...` | `1cd32a...` |

---

## Verify Ledger Integrity

You can verify the entire log chain to ensure no tampering:

```python
from audittrail import verify_ledger

result = verify_ledger("audit_log.db")
print(result)  # {"verified": True, "entries": 128}
```

If any record was altered, the verification will fail and return:

```json
{"verified": false, "error_at": "2025-10-19T21:52:00Z"}
```

---

## Directory Structure

```
audittrail/
├── __init__.py              # Main exports
├── middleware.py            # FastAPI middleware with compliance features
├── ledger.py                # Core ledger logic (hashing, verification)
├── cli.py                   # Command-line interface (RBAC, compliance tools)
├── auth.py                  # Role-based access control and authentication
├── signatures.py            # Digital signature management (RSA)
├── timestamp.py             # Timestamp authority integration
├── worm.py                  # Write-Once-Read-Many protection
├── anomaly.py               # Anomaly detection and alerting
└── compliance_report.py     # Compliance report generation
pyproject.toml
README.md
```

---

## CLI Commands

AuditTrail includes a comprehensive command-line interface with role-based access control:

### Authentication
```bash
audittrail login              # Login with username/password
audittrail logout             # Logout from current session
audittrail whoami             # Show current user info
```

### Verification & Monitoring
```bash
audittrail verify <db>                    # Verify ledger integrity
audittrail verify-enhanced <db>           # Enhanced verification with compliance checks
audittrail logs <db> --limit 10           # View recent logs
audittrail logs <db> --decrypt            # View with decrypted payloads (admin only)
audittrail search <db> --user <user>      # Search logs by user
audittrail stats <db>                     # Show statistics
audittrail watch <db>                     # Real-time log monitoring
```

### Compliance Features
```bash
audittrail init-signing                   # Initialize digital signature keys
audittrail compliance-status              # Show compliance features status
audittrail compliance-report <db>         # Generate compliance report
audittrail worm-status <db>               # Check WORM protection
audittrail anomalies                      # View detected anomalies
```

### User Management (Admin Only)
```bash
audittrail add-user                       # Add new user
audittrail list-users                     # List all users
audittrail remove-user <username>         # Remove user
```

See [RBAC_GUIDE.md](RBAC_GUIDE.md) for role-based access control documentation.

---

## Roadmap

### Completed 
- [x] Encrypted payload logging
- [x] CLI tool with comprehensive commands
- [x] Digital signatures for non-repudiation
- [x] Timestamp authorities
- [x] WORM (Write-Once-Read-Many) protection
- [x] Anomaly detection and alerting
- [x] Role-based access control
- [x] Compliance reporting (HTML/JSON)

### Planned Features
- [ ] Flask & Django middleware support
- [ ] Custom backends (PostgreSQL, MongoDB, etc.)
- [ ] HSM/KMS integration for production key management
- [ ] External Timestamp Authority (RFC 3161) integration
- [ ] Webhook/email alert notifications
- [ ] Real-time dashboard for log visualization
- [ ] Automated compliance report scheduling
- [ ] Multi-tenant support

---

## Compliance Standards Supported

With compliance features enabled, AuditTrail supports requirements from:

- **SOX (Sarbanes-Oxley)** — Audit trail completeness, data integrity, non-repudiation
- **HIPAA** — Healthcare audit logging, encryption, access controls
- **GDPR** — Data protection, audit trails, breach detection
- **PCI-DSS** — Payment card logging, tamper detection, access controls
- **SOC 2** — Security monitoring, change management, incident response

See [COMPLIANCE_FEATURES.md](COMPLIANCE_FEATURES.md) for detailed compliance documentation.

---

## Documentation

- **[README.md](README.md)** — This file, quick start guide
- **[QUICK_START_COMPLIANCE.md](QUICK_START_COMPLIANCE.md)** — 5-minute compliance setup
- **[COMPLIANCE_FEATURES.md](COMPLIANCE_FEATURES.md)** — Full compliance documentation
- **[RBAC_GUIDE.md](RBAC_GUIDE.md)** — Role-based access control guide
- **[CONTRIBUTING.md](CONTRIBUTING.md)** — Contribution guidelines

---

## Contributing

Contributions are welcome! We're especially interested in:
- Flask & Django middleware adapters
- HSM/KMS integration
- External timestamp authority support
- Performance optimizations
- Additional backend adapters

```bash
git checkout -b feature/your-feature
git commit -m "Add your feature"
git push origin feature/your-feature
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

---

## 📄 License

MIT License © 2025 Ethan P. Bonsall

---

## Summary

**AuditTrail** is a production-ready, tamper-proof audit logging library that brings bank-grade security to your API. With optional compliance features including digital signatures, timestamps, WORM protection, and anomaly detection, it's suitable for the most demanding regulatory environments.

**Quick Start:**
```python
from audittrail import AuditTrailMiddleware
app.add_middleware(AuditTrailMiddleware, enable_compliance=True)
```

That's it — your API now has enterprise-grade audit logging! 🎉