Skip to main content

Policy-driven API protection library with OPA integration, audit trails, and FastAPI server

Project description

Hexarch Guardrails Python SDK

Lightweight policy-driven API protection for developers and small teams.

PyPI version License: MIT Python 3.8+ Code style: black

📘 Docs | 🚀 Interactive Demo | 💬 Discussions | 🎯 Templates

Source-of-truth

This SDK is synced from the private monorepo (no1rstack/Hexarch) via an automated subtree publish workflow.

Installation

pip install hexarch-guardrails

Quick Start

1. Create a policy file (hexarch.yaml)

policies:
  - id: "api_budget"
    description: "Protect against overspending"
    rules:
      - resource: "openai"
        monthly_budget: 10
        action: "warn_at_80%"

  - id: "rate_limit"
    description: "Prevent API abuse"
    rules:
      - resource: "*"
        requests_per_minute: 100
        action: "block"

  - id: "safe_delete"
    description: "Require confirmation for destructive ops"
    rules:
      - operation: "delete"
        action: "require_confirmation"

2. Use in your code

from hexarch_guardrails import Guardian

# Initialize (auto-discovers hexarch.yaml)
guardian = Guardian()

# ⚠️ Requires a running OPA server (local or remote)

# Protect API calls
@guardian.check("api_budget")
def call_openai(prompt):
    import openai
    return openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

# Use it
response = call_openai("Hello AI!")

3. Start OPA locally (if not already running)

docker run -p 8181:8181 openpolicyagent/opa:latest run --server

Then run your script as usual.

Features

  • Zero-policy-language changes - Auto-discovers hexarch.yaml; YAML + rule DSL, no code restructuring
  • Decorator-based - Drop in @guardian.check(policy_id)
  • Policy-driven - YAML-based rules, OPA-backed evaluation
  • Works with OPA - Local or remote OPA server; requires OPA connectivity
  • Per-process rate limiting - Built-in sliding-window limiter per instance
  • Pluggable - Works with any API/SDK

🎉 Try It Now (Zero Install)

→ Interactive Demo on Google Colab

See policy violations in action without installing anything. Click, run cells, and watch guardrails protect your code.

Demos

🌟 Trusted By

Building something with Hexarch? Share your story and we'll feature you here!

Early adopter signals
  • Early users report catching runaway API loops and overspend during development.
  • Adopted in initial RAG app prototypes and hackathon builds.
  • Public testimonials are added only when externally attributable.

Community Stats

  • 🏗️ Built for: Students, solo developers, hackathon teams, startups
  • 🎯 Use cases: AI API protection, budget control, rate limiting, safe deployments
  • 📦 Integrations: FastAPI, Django, LangChain, Flask (see templates)
  • 🚀 Quick start: Under 5 minutes from install to protected

Ready-to-Use Templates

Get started instantly with our integration templates:

  • FastAPI - API rate limiting and budget protection
  • Django - View decorators and Celery task protection
  • LangChain - LLM call protection and agent safeguards

Each template includes complete code, policy configs, and usage instructions.

Examples

Budget Protection (OpenAI)

@guardian.check("api_budget")
def expensive_operation():
    # This call is protected by budget limits
    return openai.ChatCompletion.create(model="gpt-4", ...)

Rate Limiting

@guardian.check("rate_limit")
def send_discord_message(msg):
    return client.send(msg)

Safe File Operations

@guardian.check("safe_delete")
def delete_file(path):
    os.remove(path)

Documentation

Admin CLI (v0.3.0+)

Hexarch includes a command-line interface for managing policies and monitoring decisions:

Installation

# Install with CLI extras
pip install hexarch-guardrails[cli]

Quick Start

# List all policies
hexarch-ctl policy list

# Export a policy
hexarch-ctl policy export ai_governance --format rego

# Validate policy syntax
hexarch-ctl policy validate ./policy.rego

# Compare policy versions
hexarch-ctl policy diff ai_governance

If hexarch-ctl resolves to the wrong Python interpreter on Windows, use:

python -m hexarch_cli policy list

Available Commands

Policy Management:

  • hexarch-ctl policy list - List all OPA policies
  • hexarch-ctl policy export - Export policy to file or stdout
  • hexarch-ctl policy validate - Validate OPA policy syntax
  • hexarch-ctl policy diff - Compare policy versions

Upcoming (Phase 3-4):

  • Decision querying and analysis
  • Metrics and performance monitoring
  • Configuration management

For detailed CLI documentation, see POLICY_COMMANDS_GUIDE.md

REST API Server (Phase 3)

Hexarch includes a hardened FastAPI server intended to back a UI/dev workflow.

Install server extras

pip install "hexarch-guardrails[server]"

Run locally (recommended)

hexarch-ctl serve api --host 127.0.0.1 --port 8099 --init-db --api-token dev-token

Notes:

  • /health is public; most endpoints require a bearer token.
  • API key management endpoints (/api-keys) are disabled by default and can be enabled explicitly with HEXARCH_API_KEY_ADMIN_ENABLED=true.

Quick demo onboarding (/demo)

For a hosted sandbox flow (for example, https://hexarch.systems/demo), use the built-in demo session bootstrap:

  1. Run hexarch-ctl init to request a short-lived bootstrap token.
  2. The browser opens /demo?token=... and exchanges that token via POST /api/demo/exchange.
  3. The exchanged token is scoped to demo session routes only (/demo/policies, /demo/evaluate).

Demo route behavior:

  • Bootstrap tokens are short-lived and one-time exchange.
  • Session tokens are short-lived and sandbox-scoped.
  • Destructive actions are denied in /demo/evaluate.
  • Demo evaluation is non-persistent by design.

Key demo environment variables:

Variable Purpose Default
HEXARCH_DEMO_TOKEN_SECRET HMAC signing secret for demo tokens generated fallback
HEXARCH_DEMO_ISSUE_RPM Per-IP rate limit for POST /api/demo/session 5
HEXARCH_DEMO_EXCHANGE_RPM Per-IP rate limit for POST /api/demo/exchange 20
HEXARCH_DEMO_SESSION_RPM Per-session rate limit for demo route usage 60
HEXARCH_DEMO_WEB_URL URL used by hexarch-ctl init for browser redirect https://hexarch.systems/demo

The current /demo UI style is adapted from Bootstrap examples (MIT).

Credibility: OpenAPI fuzz scan (Schemathesis)

This repo includes a reproducible harness that starts the local FastAPI server with docs enabled and runs a Schemathesis scan against /openapi.json.

  • Installs: pip install -e ".[server,credibility]"
  • Runs (Windows): ./scripts/run_openapi_credibility_scan.ps1 -MaxExamples 25
  • Output: evidence/credibility/openapi-schemathesis/<timestamp>/

The scan is configured with a conservative credibility check (not_a_server_error) to demonstrate resilience under generated inputs (no 5xx), without requiring that every auth error path is explicitly modeled in the OpenAPI spec.

Credibility: OWASP ZAP baseline scan (Docker)

This repo also includes an OWASP ZAP baseline scan harness (passive scan + spider) that produces HTML/JSON/XML/Markdown reports.

  • Runs (Windows): ./scripts/run_zap_baseline_credibility_scan.ps1 -Mins 1 -MaxWaitMins 5
  • Output: evidence/credibility/zap-baseline/<timestamp>/

Notes:

  • By default it keeps auth enabled (hardened posture) and does not fail the command on warnings; it always writes the reports.
  • For deeper crawling you can run with -AllowAnon (this changes server posture for the scan).
  • To propagate ZAP exit codes (WARN/FAIL), pass -Strict.

Credibility: Policy correctness evals (golden cases)

Golden-case evaluation that exercises the decision engine via POST /authorize and writes a dated report.

  • Cases file: evals/policy_cases.json (edit/extend this as you like)
  • Runs (Windows): ./scripts/run_policy_credibility_evals.ps1
  • Output: evidence/credibility/policy-evals/<timestamp>/ (report.md, results.json, server.log)

Smoke test (starts server, hits /health, stops)

PowerShell:

./scripts/smoke_api.ps1 -Port 8099

Bash:

./scripts/smoke_api.sh

n8n End-to-End (Single User Milestone)

For a complete local workflow that (1) calls /authorize, (2) calls a provider (Ollama), and (3) logs a tamper-evident provider-call event via /events/provider-calls, see:

n8n Integration Example

Technical walkthrough for pre-execution policy enforcement in n8n with an importable workflow and deterministic allow/deny routing:

GitHub Actions Integration Example

Technical walkthrough for pre-execution policy enforcement in GitHub Actions with an importable workflow pattern and deterministic allow/deny routing:

Postman Integration Example

Technical walkthrough for pre-execution policy enforcement in Postman with an importable collection, local environment, and deterministic allow/deny authorization checks:

Flowise Integration Example

Technical walkthrough for pre-execution policy enforcement in Flowise Agentflow V2 using HTTP, Condition, and Direct Reply nodes with shared $flow.state for deterministic allow/deny routing:

Langflow Integration Example

Technical walkthrough for pre-execution policy enforcement in Langflow using the native API Request component, reusable guard subflows, and an optional custom component starter for deterministic allow/deny routing:

Pipedream Integration Example

Technical walkthrough for pre-execution policy enforcement in Pipedream using two Node.js code steps — check_policy (POST to /authorize) and enforce ($.flow.exit() on deny) — to gate any downstream step with a deterministic allow/deny decision:

Zapier Integration Example

Technical walkthrough for pre-execution policy enforcement in Zapier using a Code by Zapier step (check_policy) and a built-in Filter step to gate any downstream Zap action with a deterministic allow/deny decision:

Node-RED Integration Example

Technical walkthrough for pre-execution policy enforcement in Node-RED with an importable flow and deterministic allow/deny routing:

Node-RED End-to-End (Single User Milestone)

If you prefer an Apache-2.0 OSS orchestrator for guardrails testing (authorize → echo → log provider call), see:

PyPI release checklist

Use this checklist before publishing a new package version:

  1. Confirm version metadata
  • Update version in pyproject.toml.
  • Ensure hexarch_guardrails/__init__.py exports matching __version__.
  1. Run validation locally
  • Run full test suite (python -m pytest -q).
  • Run any required smoke checks for hexarch-ctl and server mode.
  1. Build distribution artifacts
  • Build wheel/sdist (python -m build).
  1. Validate artifacts
  • Run Twine checks (python -m twine check dist/*).
  1. Publish
  • Upload to PyPI with Twine.
  1. Post-publish verification
  • Install from PyPI in a clean env and run a quick Guardian + hexarch-ctl smoke test.

License

MIT © Noir Stack LLC

See LICENSE for full details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hexarch_guardrails-0.4.2.tar.gz (103.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hexarch_guardrails-0.4.2-py3-none-any.whl (113.5 kB view details)

Uploaded Python 3

File details

Details for the file hexarch_guardrails-0.4.2.tar.gz.

File metadata

  • Download URL: hexarch_guardrails-0.4.2.tar.gz
  • Upload date:
  • Size: 103.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for hexarch_guardrails-0.4.2.tar.gz
Algorithm Hash digest
SHA256 9eaae6dd4fb6c10fa6a697cc7f77f8eadbb231e40f4abbb95b039c36c457e2df
MD5 303f829d76f10eb58c118fb76c6320f1
BLAKE2b-256 72242a604b8511a593cd141461fb8e0d2ea4d0f5a48b94f44944627a0b76d0e4

See more details on using hashes here.

File details

Details for the file hexarch_guardrails-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for hexarch_guardrails-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c3c61825fe5625ed2a80082b0363e817382c847659c54dc63d71aa11a42cba97
MD5 fc67068015f06cc980b909edfea414af
BLAKE2b-256 723a1a24b306bbfc14a602b45bcd593f84df87bf8f6d886c4b4330a3e0751125

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page