Skip to main content

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

pip install audittrail

or from source:

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

⚡ Quick Start (FastAPI Example)

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:

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

See 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:

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:

{"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

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

Verification & Monitoring

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

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)

audittrail add-user                       # Add new user
audittrail list-users                     # List all users
audittrail remove-user <username>         # Remove user

See RBAC_GUIDE.md for role-based access control documentation.


Roadmap

Completed

  • Encrypted payload logging
  • CLI tool with comprehensive commands
  • Digital signatures for non-repudiation
  • Timestamp authorities
  • WORM (Write-Once-Read-Many) protection
  • Anomaly detection and alerting
  • Role-based access control
  • 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 for detailed compliance documentation.


Documentation


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
git checkout -b feature/your-feature
git commit -m "Add your feature"
git push origin feature/your-feature

See 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:

from audittrail import AuditTrailMiddleware
app.add_middleware(AuditTrailMiddleware, enable_compliance=True)

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

Metadata

Release files for audittrail 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for audittrail 1.0.1
File Size Uploaded Provenance
audittrail-1.0.1.tar.gz 31.0 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for audittrail 1.0.1
File Interpreter ABI Platform
audittrail-1.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 65.1 kB

Release files / audittrail-1.0.1.tar.gz

Download URL audittrail-1.0.1.tar.gz
Size 31.0 kB
Tags Source
SHA-256 checksum
How to use checksums
7209bc284bce14fc7341d466347d8cd20f86529e131d9b229a057a054de365d7
BLAKE2b-256 checksum
How to use checksums
42b4aeb9e167458245b1948e268ed46d509bde83976624194486f99e64133c9c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.4

Release files / audittrail-1.0.1-py3-none-any.whl

Download URL audittrail-1.0.1-py3-none-any.whl
Size 34.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
074899bd40d63cd14f90542ef96c453cc997ce651095eec9de520e578a788a82
BLAKE2b-256 checksum
How to use checksums
44dde9d28cac653271d005077bc44b9ae9f887ac32fc9816d02270159d18ee71
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.4

Security for audittrail 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page