Skip to main content

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

Python Version FastAPI License Tests

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 & Telemetry

  • 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/
├── 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             # Top-level aggregated API gateway router
│   └── 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 as a Python package in any FastAPI microservice:

pip install -e .

Or install runtime dependencies:

pip install -r requirements.txt

2. Environment Configuration

Create a .env file:

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

3. Start the API Gateway (Bare-Metal / Recommended for Mini-Servers)

uvicorn server:app --host 0.0.0.0 --port 8000 --reload

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


🐳 4. (OPTIONAL) Docker & Docker Compose Setup

[!NOTE] This Docker setup is 100% optional. For resource-constrained servers (such as mini-servers with 4GB RAM or low-spec VPS), bare-metal Python execution via systemd (Step 3 above) is strongly recommended, as it consumes only ~50 MB of RAM without Docker daemon overhead.

If you are deploying to a cloud container host or want an instant all-in-one local development stack (API + PostgreSQL + Redis + OPA):

# Spin up complete stack (Gateway + PostgreSQL + Redis + OPA)
docker compose up -d

# View container logs
docker compose logs -f auth-api

# Stop containers
docker compose down

🛡️ Consuming Auth N&Z in External Microservices

Secure external FastAPI routes in 1 line:

from fastapi import FastAPI, Depends
from auth_nz import (
    api_router as authnz_router,
    register_exception_handlers,
    require_auth,
    require_role,
    require_permission,
    get_current_workspace,
    CurrentUser,
    CurrentWorkspace,
)

app = FastAPI(title="Consumer Microservice")

# 1. Register RFC 7807 Error Boundaries
register_exception_handlers(app)

# 2. Mount Auth N&Z Endpoints
app.include_router(authnz_router)

# 3. Guard Routes with Typed Dependency Injection
@app.get("/api/me")
async def get_profile(user: CurrentUser = Depends(require_auth())):
    return {"id": user.id, "email": user.email, "clearance": user.clearance}

@app.post("/api/invoices")
async def create_invoice(
    user: CurrentUser = Depends(require_permission("billing:create")),
    workspace: CurrentWorkspace = Depends(get_current_workspace()),
):
    return {"status": "created", "workspace": workspace.name}

@app.delete("/api/projects/{project_id}")
async def delete_project(user: CurrentUser = Depends(require_role("admin"))):
    return {"status": "deleted by admin"}

💻 Administration CLI (authnz / cli.py)

Auth N&Z provides a scriptable control plane utility:

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

# Workspace Administration
python cli.py workspaces list
python cli.py workspaces create --name "Acme Corp" --slug "acme"

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

# Security Audit Inspection
python cli.py audit tail --limit 25 --severity CRITICAL

# Diagnostics & Observability
python cli.py health check
python cli.py metrics dump

🧪 Running the Test Suite

Execute the comprehensive offline test suite:

pytest

Result: 30 passed, 1 skipped (live PostgreSQL E2E), 100% success in ~6.5s.


📄 License

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

Metadata

Release files for l4s3r-authnz 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 l4s3r-authnz 1.0.1
File Size Uploaded Provenance Actions
l4s3r_authnz-1.0.1.tar.gz 126.4 kB Without provenance Details for l4s3r_authnz-1.0.1.tar.gz

Built distribution (wheel)

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

Total release size: 253.8 kB

Release files / l4s3r_authnz-1.0.1.tar.gz

Download URL l4s3r_authnz-1.0.1.tar.gz
Size 126.4 kB
Tags Source
SHA-256 checksum
How to use checksums
9bc4445d22805596859fcbe5d9c44ebdde4994607a7dfd8fd4b376aa96fd3474
BLAKE2b-256 checksum
How to use checksums
3a36cdb983254fb5fd5862648f8eabc4a0fc9bc7fae63bc2aaa217eb2298e71d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

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

Download URL l4s3r_authnz-1.0.1-py3-none-any.whl
Size 127.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
47ae4e5891aff02a359bce33bac6cf52dd050c70d5cb11ff7576ed57c0342583
BLAKE2b-256 checksum
How to use checksums
3980f1790a3236dd2fa4bd72ee94012a7cb629262fbc92c9d0ab5700e8f45398
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

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

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