Skip to main content

Auth N&Z - Enterprise Identity, Authentication & Authorization Engine

PyPI Version PyPI Downloads Python Version FastAPI License Tests

"I don't care if the user exists; I care if they are authorized to perform this specific action."

Auth N&Z is a modular, production-grade, NIST-compliant Identity and Access Management (IAM) framework and multi-tenant authorization engine built with Python, FastAPI, and asynchronous SQLAlchemy 2.0 (asyncpg).


Key Capabilities

1. Authentication (AuthN)

  • Dual-Engine Password Hashing: Argon2id (OWASP recommended) & Bcrypt with transparent zero-downtime hash migration.
  • Stateless JWT Token Families: Automatic refresh token rotation with instant cascade revocation on token theft/replay attacks.
  • Stateful Redis Distributed Sessions: Sub-millisecond session validation and single-click remote multi-device revocation.
  • FIDO2 / WebAuthn Level 3 Passkeys: Platform biometrics (Apple Touch ID/Face ID, Windows Hello, Android Biometrics) & hardware keys (YubiKey).
  • RFC 6238 TOTP Multi-Factor Authentication: Authenticator app integration with single-use Base58 recovery backup codes.
  • Device Trust Binding: Cryptographic device fingerprinting with User-Agent binding for remembered MFA devices.
  • Social OAuth2 / OIDC: Google OpenID Connect and GitHub OAuth with PKCE verification and JIT user provisioning.

W3C FIDO2 and WebAuthn Passkey Ceremony Flowchart


2. Authorization (AuthZ), OPA & Multi-Tenancy

  • Hierarchical RBAC: superadmin > admin > developer > editor > viewer.
  • Open Policy Agent (OPA) & Declarative Rego Engine: Externalized policy storage with hybrid fallback and circuit breaker.
  • Fine-Grained ABAC Policy Engine: Context-aware resource evaluation based on ownership, security clearance, department, and custom rules.
  • Distributed Redis Decision Caching: High-speed L1/L2 permission caching with real-time Pub/Sub cache invalidation.
  • Multi-Tenant Workspaces: Isolated organizational tenant boundaries, scoped role clearance, and idempotent invitation lifecycles.
  • Declarative FastAPI Guards: 1-line dependency injection (require_auth(), require_role("admin"), require_permission("tasks:write")).

Distributed Policy Storage and OPA Architecture


3. Production Observability, Caching & Telemetry

  • Multi-Tier L1/L2 Profile & Metadata Caching: Sub-millisecond in-memory L1 cache with Redis L2 storage, reducing PostgreSQL read traffic by ~90–95%.
  • HTTP Conditional 304 Fast-Path: Automatic deterministic ETag generation (W/"...") and Cache-Control header negotiation on user metadata endpoints (/auth/me, /auth/webauthn/credentials, /auth/trusted-devices).
  • Distributed Multi-Worker Pub/Sub Invalidation: Instant cluster-wide cache invalidation across Uvicorn workers on user profile or role changes.
  • Zero-Polling Real-Time Push: WebSockets for live notifications (notification.received, notification.read, notification.read_all).
  • Prometheus Metrics (GET /metrics): Telemetry for authentication rates, token verification outcomes, active sessions, and request latency histograms.
  • Deep Health Probes (GET /health/live, GET /health/ready, GET /health): Asynchronous connectivity probes against PostgreSQL and Redis.
  • Tamper-Evident Audit Logging: Structured security event telemetry with severity levels (INFO, WARNING, CRITICAL).
  • Interactive Administration CLI (cli.py / authnz): Complete CLI for user management, workspace administration, and audit inspection.

Observability & Telemetry Architecture


System Architecture

Full-Stack System Architecture

Auth N&Z/
├── adapter.py                # Unified configuration & adapter layer (configure_authnz, AuthNZ)
├── models.py                 # SQLAlchemy 2.0 models & AuthNZUserMixin (BYOU pattern)
├── config.py                 # Typed configuration via pydantic-settings
├── exceptions.py             # RFC 7807 Problem Details error boundaries
├── guards.py                 # Declarative FastAPI dependency guards
├── metrics.py                # Prometheus metrics collection engine
├── server.py                 # Lean FastAPI gateway entrypoint (88 lines)
├── cli.py                    # Interactive administration CLI (authnz)
├── policy_engine.py          # Declarative local engine & distributed caching
├── opa_client.py             # Open Policy Agent async client with circuit breaker
├── webauthn_service.py       # FIDO2 / WebAuthn passkey ceremony service
├── policies/
│   ├── rules.json            # Declarative RBAC and ABAC rule definitions
│   └── authnz.rego           # Open Policy Agent Rego policy suite
├── api/
│   ├── dependencies.py       # Shared singletons and dependency injection
│   ├── schemas.py            # Pydantic v2 schemas
│   ├── router.py             # Router factory (create_authnz_router) & aggregated gateway
│   └── v1/
│       ├── auth_router.py         # /auth (login, register, refresh, me, logout)
│       ├── mfa_router.py          # /auth/mfa (setup, verify, disable, complete)
│       ├── webauthn_router.py     # /auth/webauthn (passkeys & security keys)
│       ├── device_trust_router.py # /auth/trusted-devices (CRUD & revocation)
│       ├── workspace_router.py    # /workspaces (tenants, members, roles, switch)
│       ├── team_router.py         # /team (legacy invitations & management)
│       ├── oauth_router.py        # /auth/oauth (Google OIDC & GitHub OAuth)
│       ├── audit_router.py        # /audit/logs & protected documents
│       ├── notification_router.py # /notifications (in-app notification feed)
│       ├── websocket_router.py    # /ws/workspaces/{id} real-time connection manager
│       ├── health_router.py       # /health/live, /health/ready, /metrics
│       ├── policy_router.py       # /admin/policies (inspect, reload, simulate)
│       └── task_router.py         # /tasks (sprint deliverable board)
└── examples/
    └── task_tracker_app/     # Consumer showcase microservice

JWT Token Security & Session Lifecycle

Token Security Lifecycle Flowchart

  1. Initial Authentication: User logs in via password, MFA, passkey, or OAuth 2.0 PKCE, receiving a short-lived access token and a long-lived refresh token.
  2. Token Family Lineage: Each refresh cycle rotates both tokens. Presenting an already-consumed token immediately triggers a Theft Cascade Revocation of all sessions.
  3. Proactive Client Heartbeat: Client inspects JWT exp timestamp and silently calls POST /auth/refresh before expiration.
  4. Stateful Redis Invalidation: Remote single-click logout instantly purges the user's sessions across all connected devices.

Multi-Tenant Workspace & Task Lifecycle

Team Task Workflow Diagram

  1. Workspace Provisioning: Users create workspaces or are invited by administrators.
  2. Contextual Workspace Switching: POST /auth/workspaces/switch issues scoped JWT access tokens with workspace permissions.
  3. Invitation Dispatch: Workspace Admin invites members via email with single-use cryptographic tokens.
  4. Task Deliverable Creation: Tasks are created with JSONB tags, deadlines, priority levels, and multiple assignees.
  5. Real-Time Push & Email: In-app WebSocket events and transactional SMTP emails are automatically dispatched.

Quickstart

1. Installation

Install via PyPI:

pip install l4s3r-authnz

Or install from source in editable mode:

git clone https://github.com/L4S3r/AuthN-Z.git
cd AuthN-Z
pip install -e .

2. Local Environment Configuration

Copy the template configuration and customize your secrets:

cp .env.example .env

Key variables in .env:

ENVIRONMENT=development
JWT_SECRET_KEY=your_super_secret_high_entropy_key_32_bytes_long
DATABASE_URL=postgresql+asyncpg://authnz_app:password123@localhost:5432/authnz
REDIS_HOST=localhost
REDIS_PORT=6379
REQUIRE_REDIS=false
PASSWORD_HASH_ALGORITHM=argon2id
OPA_ENABLED=false

3. Running the Standalone Gateway

Option A: Bare-Metal Python / Uvicorn (Fastest for Local Dev & Low-RAM Mini-Servers)

# Start FastAPI gateway
uvicorn server:app --host 0.0.0.0 --port 8000 --reload

Interactive Swagger docs: http://localhost:8000/docs


Option B: Self-Contained Docker Compose Stack

Launch the complete stack (FastAPI Gateway + PostgreSQL 16 + Redis 7 + Open Policy Agent):

# 1. Start all containers in detached mode
docker compose up -d

# 2. Bootstrap initial root administrator account
docker compose exec auth-api python seed_admin.py

# 3. Verify container health and table statistics
docker compose exec auth-api python db_manager.py stats

# 4. View real-time application logs
docker compose logs -f auth-api

# 5. Tear down containers and volumes
docker compose down -v

Framework & Adapter Integration Patterns

Auth N&Z is designed to integrate into external FastAPI applications at 3 architectural levels:

Pattern A: Modular Adapter & Custom User Model (BYOU)

Retain your application's own User table identity with custom columns and selectively mount only the routes you need:

from fastapi import FastAPI
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

# 1. Import Core Identity Base, Mixin, and Adapter
from auth_nz.models import Base, AuthNZUserMixin
from auth_nz.adapter import AuthNZ
from auth_nz.guards import CurrentUser, require_auth, require_role, require_permission

# 2. Define custom User model inheriting AuthNZUserMixin on shared Base
class User(Base, AuthNZUserMixin):
    __tablename__ = "users"
    company_name: Mapped[str]
    stripe_customer_id: Mapped[str | None] = mapped_column(nullable=True)

# 3. Create Async Database Session Factory
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost:5432/my_app")
session_factory = async_sessionmaker(engine)

# 4. Initialize AuthNZ Adapter with your custom model & session factory
authnz = AuthNZ(
    user_model=User,
    session_factory=session_factory,
    jwt_secret_key="custom_secret_key_here",
)

# 5. Mount ONLY the desired routes (e.g. Auth + MFA + WebAuthn, exclude turnkey tasks)
app = FastAPI(title="My SaaS Application")

app.include_router(
    authnz.create_router(
        enable_auth=True,
        enable_mfa=True,
        enable_webauthn=True,
        enable_device_trust=True,
        enable_workspaces=False,  # Exclude standalone workspace domain if not needed
        enable_tasks=False,       # Exclude standalone task tracker
    ),
    prefix="/api/v1",
)

# 6. Protect host endpoints with 1-line declarative guards
@app.get("/api/v1/profile")
async def get_profile(user: CurrentUser = Depends(require_auth())):
    return {"id": user.id, "email": user.email, "roles": user.roles}

Pattern B: Lightweight Resource Server Guards (Zero-DB Mode)

In downstream microservices (e.g. Billing, Inventory), validate incoming JWT tokens and enforce RBAC/ABAC permissions with zero database overhead:

from fastapi import FastAPI, Depends
from auth_nz.guards import require_auth, require_role, require_permission, CurrentUser
from auth_nz.exceptions import register_exception_handlers

app = FastAPI(title="Billing Microservice")
register_exception_handlers(app)

@app.get("/invoices")
async def get_invoices(user: CurrentUser = Depends(require_permission("invoices:read"))):
    return {"status": "ok", "user": user.email}

@app.delete("/invoices/{invoice_id}")
async def delete_invoice(user: CurrentUser = Depends(require_role("admin"))):
    return {"status": "deleted"}

Pattern C: Turnkey Standalone IAM Microservice

Run the standalone server out of the box with the complete suite (Auth, Passkeys, Multi-Tenant Workspaces, Task Tracker, Telemetry, and Admin CLI):

from fastapi import FastAPI
from auth_nz import api_router, register_exception_handlers

app = FastAPI(title="Turnkey Auth Gateway")
register_exception_handlers(app)
app.include_router(api_router)

💻 Administration & Control Plane Utilities

Auth N&Z includes comprehensive CLI tools for operator administration:

1. Interactive Control Plane (cli.py / authnz)

# User Management
authnz users list
authnz users create --username alice --email alice@example.com --password SecretPassword123! --role admin
authnz users reset-password --email alice@example.com --password NewSecretPassword123!
authnz users delete --email alice@example.com

# Workspace Administration
authnz workspaces list
authnz workspaces create --name "Acme Corp" --slug "acme"

# Declarative Policies & OPA
authnz policies inspect
authnz policies reload
authnz policies simulate --email alice@example.com --action read --resource-type documents

# Security Audit Inspection
authnz audit tail --limit 25 --severity CRITICAL

# Diagnostics & Observability
authnz health check
authnz metrics dump

2. Database Inspection & Maintenance (db_manager.py)

python db_manager.py stats                    # Record counts across all tables
python db_manager.py audit -n 50 -s CRITICAL   # Filter security audit logs
python db_manager.py workspaces               # List workspaces with member counts
python db_manager.py users -r admin           # Filter registered users by role
python db_manager.py devices                  # Inspect enrolled trusted devices
python db_manager.py purge-audit --yes        # Safely purge telemetry logs

3. Bootstrap & Promotion Utilities

# Bootstrap root administrator without exposing HTTP endpoints
python seed_admin.py

# Promote existing user account to Superadmin
python promote_admin.py -i admin@example.com --super --clearance 5

Mini-Server & VPS Production Optimization

Auth N&Z and TaskTracker are engineered to run seamlessly on bare-metal mini-servers and low-RAM VPS instances (1–2 vCPU, 3–4 GB RAM) natively via systemd without Docker overhead:

  • Disk Exhaustion Protection: Native logrotate and systemd-journald log capping (SystemMaxUse=300M) plus weekly automated audit log trimming.
  • OOM-Killer Safety Net: Systemd cgroups v2 resource capping (MemoryMax=512M, MemoryHigh=384M), 2–4 GB swapfile with swappiness=10, and Redis overcommit tuning.
  • Database Connection Pooling: Async SQLAlchemy bounded pools (pool_size=10, max_overflow=5, pool_pre_ping=True) saving ~100 MB RAM.
  • Automated Encrypted Backups: Daily zero-disk pg_dump streams to Cloudflare R2 / AWS S3 via native systemd timers.
  • Reverse Proxy Edge Hardening: Native Caddy / Nginx recipes for TLS 1.3, Brotli/Gzip compression, and persistent WebSocket streams.
  • Decoupled Vercel Edge Frontend: Frontend (tasks.l4s3r.site) hosted on Vercel with global Edge CDN caching, leaving 100% of mini-server RAM for FastAPI, PostgreSQL, and Redis (<600MB total idle RAM).

For server-level infrastructure hardening, see the Mini-Server & VPS Production Quality-of-Life (QoL) Runbook.
For TaskTracker application-level optimizations, see Phase 6: TaskTracker Production & QoL Hardening.


🧪 Running the Test Suite

Execute the comprehensive offline test suite:

pytest

Result: 62 passed, 1 skipped (live PostgreSQL integration guard), 100% success.


📄 License

MIT License. Auth N&Z is built for enterprise-grade security, compliance, and developer velocity.

Metadata

Release files for l4s3r-authnz 1.1.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 l4s3r-authnz 1.1.1
File Size Uploaded Provenance Actions
l4s3r_authnz-1.1.1.tar.gz 150.1 kB With provenance Details for l4s3r_authnz-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for l4s3r-authnz 1.1.1
File Interpreter ABI Platform Actions
l4s3r_authnz-1.1.1-py3-none-any.whl Python 3 none any Details for l4s3r_authnz-1.1.1-py3-none-any.whl

Total release size: 295.0 kB

Release files / l4s3r_authnz-1.1.1.tar.gz

Download URL l4s3r_authnz-1.1.1.tar.gz
Size 150.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2ba761cad63eb51720695c2f4d2572ac7bfed3ac7f7463963953638a5a4b34bb
BLAKE2b-256 checksum
How to use checksums
5f7428d66be9ea945e41e33055251f629c122707bb26dca431c9af85fca8789a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 30, 2026.

Transparency log

Release files / l4s3r_authnz-1.1.1-py3-none-any.whl

Download URL l4s3r_authnz-1.1.1-py3-none-any.whl
Size 144.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e3274f2f6ba33f5c1969b7fa6a5087ab8f586747bfa720db2e255f88a1630209
BLAKE2b-256 checksum
How to use checksums
63d3b70b19b468f6c32d73cfe6e7f06893a1bd25a76d3e2878f96c41dcc4b0c1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 30, 2026.

Transparency log

Security for l4s3r-authnz 1.1.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for l4s3r_authnz-1.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 30, 2026.

Transparency log

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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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