Skip to main content

Lightweight policy-driven API protection and guardrails library

Project description

Hexarch Guardrails Python SDK

Stop production disasters before they happen. Lightweight policy-driven API protection for students, solo developers, and hackathons.

๐Ÿšจ Stop Disasters Before They Happen

Has this ever happened to you?

# Innocent cleanup script...
def cleanup_old_data():
    db.execute("DELETE FROM users WHERE last_login < '2023-01-01'")

cleanup_old_data()  # ๐Ÿ’ฅ Just deleted 10,000 production records

Or this?

# Weekend GPT-4 experiment...
for prompt in user_prompts:  # 1000 prompts
    openai.ChatCompletion.create(model="gpt-4", ...)
    
# Monday morning: $4,200 OpenAI bill ๐Ÿ’ธ

With Hexarch Guardrails:

from hexarch_guardrails import Guardian
guardian = Guardian()

@guardian.check("safe_delete")  # โ† Add one line
def cleanup_old_data():
    db.execute("DELETE FROM users WHERE last_login < '2023-01-01'")

# Now it blocks: โŒ [BLOCKED] Policy 'safe_delete' requires confirmation

โ†’ Try the 30-second interactive demo


Source-of-truth

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

Installation

pip install hexarch-guardrails

Optional Extras (Install by Feature)

Feature Install Command
Admin CLI (hexarch-ctl) pip install hexarch-guardrails[cli]
REST API Server pip install "hexarch-guardrails[server]"
Postgres-backed storage pip install "hexarch-guardrails[postgres]"
Dev/Test tooling pip install "hexarch-guardrails[dev]"

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)
# Optional: pass an explicit path if auto-discovery fails
guardian = Guardian(policy_file="/absolute/path/to/hexarch.yaml")

# 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!")

How Enforcement Actually Works (No Surprises)

1) Confirmation is not a CLI prompt

Guardrails does not pause for STDIN or interactive prompts. If a policy requires confirmation, you must handle confirmation in your app and only call the guarded function after confirmation is obtained.

Example pattern (explicit context flag):

from hexarch_guardrails import Guardian
from hexarch_guardrails.exceptions import PolicyViolation

guardian = Guardian()

# Require explicit confirmation in policy via input.confirm == true
@guardian.check("safe_delete", context={"confirm": True})
def delete_user_data(user_id: str):
    db.delete(user_id)

try:
    delete_user_data("user_123")
except PolicyViolation as exc:
    print(f"Blocked: {exc}")

If you need a human-in-the-loop confirmation for a headless script, collect it before calling the guarded function (CLI flag, UI confirmation, or workflow approval).

2) What happens when a policy blocks

Guardrails blocks by raising PolicyViolation before your function runs. Your app doesn't crash if you handle the exception.

from hexarch_guardrails.exceptions import PolicyViolation

try:
    call_openai("Hello AI!")
except PolicyViolation as exc:
    # Decide what to do (log, return fallback, notify, etc.)
    print(f"Denied: {exc}")

3) Budget + rate state storage

The core SDK delegates state to the policy engine (OPA by default). The Safe Automation Runner demo uses an in-process evaluator with in-memory state (non-distributed, demo only).

For production or distributed environments:

  • Run OPA as a service and back it with persistent storage (e.g., OPA bundles + data API + external state store).
  • Or replace the policy engine with your own decision service that tracks budgets centrally.

4) OPA dependency (whatโ€™s included vs external)

pip install hexarch-guardrails installs the SDK only. OPA is a separate service if you use the default evaluator. The demo uses a lightweight in-process evaluator to avoid external dependencies.

5) Auto-discovery vs explicit policy file path

Auto-discovery walks up from your current working directory to find hexarch.yaml. If your app runs in Docker or from a different working directory, pass the path explicitly:

guardian = Guardian(policy_file="/app/config/hexarch.yaml")

Features

  • โœ… Zero-config - Auto-discovers hexarch.yaml
  • โœ… Decorator-based - Drop in @guardian.check(policy_id)
  • โœ… Policy-driven - YAML-based rules, no code changes
  • โœ… Local-first - Works offline or with local OPA
  • โœ… Pluggable - Works with any API/SDK
  • โœ… Async-First - Full support for async def functions
  • โœ… Fail-Safe - Denials don't crash your app (logged gracefully)
  • โœ… Test-Friendly - Bypass policies in test environments
  • โœ… Production-Ready - Used in live systems handling millions of requests

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)

Prevent API Bill Shock (Async)

@guardian.check("openai_budget")
async def generate_content_batch(prompts: list[str]):
    return await asyncio.gather(*[
        openai.ChatCompletion.acreate(
            model="gpt-4",
            messages=[{"role": "user", "content": p}]
        ) for p in prompts
    ])

# hexarch.yaml enforces: max $100/month, warn at 80%

Business Hours Enforcement

@guardian.check("business_hours_only")
def send_customer_email_blast(emails: list[str]):
    for email in emails:
        send_marketing_email(email)

# Blocks execution outside 9am-5pm EST
# (Prevents accidental 3am customer notifications)

Discord/Slack Rate Limiting

@guardian.check("webhook_rate_limit")
def send_discord_alert(message: str):
    webhook.send(message)

# Automatically throttles to 5 msg/min (TOS compliant)

Database Migration Safety

@guardian.check("migration_safety")
def run_schema_migration(migration_file: str):
    db.execute_migration(migration_file)

# Requires: production env flag + confirmation + backup verified

Safe Automation Runner (CLI demo app)

A minimal, self-contained example that shows rate limits, budgets, and destructive safeguards enforced at the function boundary.


Who Uses Hexarch?

  • Solo Developers โ€” Prevent accidental production disasters
  • Hackathon Teams โ€” Ship fast without breaking things
  • Startups โ€” Enforce compliance before you have a DevOps team
  • AI/ML Engineers โ€” Control GPU/API costs without code changes
  • Enterprises โ€” Policy-as-code for regulated industries (HIPAA, SOC 2)

"Saved us from a $3k Anthropic bill when an intern accidentally ran a batch job with Claude Opus instead of Haiku."
โ€” Startup CTO using Hexarch in production

"We enforce 'no destructive operations after 4pm Friday' as policy. Game changer for weekend on-call."
โ€” Platform Engineer


Why Not Just Use Try/Catch or Environment Variables?

Try/catch โ€” Reactive. Runs code first, handles errors after damage is done.
Hexarch Guardrails โ€” Proactive. Blocks execution before the function body runs.

Environment variables โ€” Scattered across codebase, easy to bypass.
Hexarch Guardrails โ€” Centralized policies in hexarch.yaml, enforced at the decorator boundary.

Manual checks in every function โ€” Brittle, gets skipped during refactors.
Hexarch Guardrails โ€” One decorator, policies evolve without touching code.


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

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.

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:

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:

License

MIT ยฉ Noir Stack LLC

See LICENSE for full details.


Publishing to PyPI (Maintainers Only)

Prerequisites

  1. Install build tools:

    pip install --upgrade pip build twine
    
  2. PyPI Account Setup:

  3. Configure PyPI credentials:

    Option A: Token in .pypirc (recommended):

    # Create/edit ~/.pypirc (Linux/Mac) or %USERPROFILE%\.pypirc (Windows)
    [pypi]
    username = __token__
    password = pypi-YOUR_API_TOKEN_HERE
    

    Option B: Environment variable:

    # Linux/Mac
    export TWINE_USERNAME=__token__
    export TWINE_PASSWORD=pypi-YOUR_API_TOKEN_HERE
    
    # Windows PowerShell
    $env:TWINE_USERNAME = "__token__"
    $env:TWINE_PASSWORD = "pypi-YOUR_API_TOKEN_HERE"
    

Pre-Publish Checklist

  • Update version in setup.py or pyproject.toml (use semantic versioning: 0.4.0, 1.0.0, etc.)
  • Update CHANGELOG.md with release notes
  • Ensure README.md renders correctly (PyPI uses this as long description)
  • Run tests: pytest tests/
  • Build locally to verify: python -m build
  • Check package metadata: twine check dist/*
  • Tag release in git: git tag v0.4.0 && git push origin v0.4.0

Publishing Steps

1. Navigate to package directory

cd hexarch-guardrails-py

2. Clean previous builds

# Linux/Mac
rm -rf build/ dist/ *.egg-info

# Windows PowerShell
Remove-Item -Recurse -Force build, dist, *.egg-info -ErrorAction SilentlyContinue

3. Build distribution packages

python -m build

This creates:

  • dist/hexarch_guardrails-0.4.0-py3-none-any.whl (wheel - preferred)
  • dist/hexarch-guardrails-0.4.0.tar.gz (source distribution)

4. Verify package contents

# Check metadata and README rendering
twine check dist/*

# Expected output:
# Checking dist/hexarch_guardrails-0.4.0-py3-none-any.whl: PASSED
# Checking dist/hexarch-guardrails-0.4.0.tar.gz: PASSED

5. Test upload to TestPyPI (optional but recommended)

# Upload to TestPyPI
twine upload --repository testpypi dist/*

# Test install from TestPyPI
pip install --index-url https://test.pypi.org/simple/ hexarch-guardrails==0.4.0

# Verify it works
python -c "from hexarch_guardrails import Guardian; print('โœ“ Package OK')"

6. Upload to production PyPI

twine upload dist/*

You'll see:

Uploading distributions to https://upload.pypi.org/legacy/
Uploading hexarch_guardrails-0.4.0-py3-none-any.whl
100% โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 25.2/25.2 kB โ€ข 00:00
Uploading hexarch-guardrails-0.4.0.tar.gz
100% โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 22.8/22.8 kB โ€ข 00:00

View at:
https://pypi.org/project/hexarch-guardrails/0.4.0/

7. Verify live package

# Wait 1-2 minutes for PyPI CDN propagation, then:
pip install --upgrade hexarch-guardrails

# Test
python -c "from hexarch_guardrails import Guardian; print(Guardian.__version__)"

8. Announce release

Troubleshooting

Error: 403 Forbidden during upload

  • Check API token is valid and not expired
  • Ensure you have maintainer/owner role on the package
  • Verify .pypirc formatting (no spaces around =)

Error: File already exists

  • PyPI does not allow re-uploading the same version
  • Increment version number in setup.py/pyproject.toml
  • Rebuild: python -m build

Error: Invalid distribution metadata

  • Run twine check dist/* to see specific errors
  • Common issues:
    • Missing README.md reference in setup.py
    • Invalid classifiers in setup.py
    • Non-UTF-8 characters in README.md

README not rendering on PyPI

  • Ensure setup.py has long_description_content_type="text/markdown"
  • Check for unsupported Markdown extensions (PyPI uses CommonMark)
  • Test locally: python -m readme_renderer README.md -o /tmp/output.html

Package installs but imports fail

  • Verify packages=find_packages() in setup.py includes all submodules
  • Check MANIFEST.in includes necessary non-Python files
  • Test in clean virtualenv: python -m venv test_env && source test_env/bin/activate

Automation (GitHub Actions)

For automated PyPI releases on git tags, see .github/workflows/publish-pypi.yml (if configured).

Example workflow trigger:

git tag v0.4.0
git push origin v0.4.0
# GitHub Actions automatically builds and publishes to PyPI

Security Best Practices

  • Never commit .pypirc or API tokens to git
  • Use PyPI API tokens (not password) โ€” tokens are scoped and revocable
  • Enable 2FA on PyPI account
  • Use different tokens for TestPyPI vs production PyPI
  • Rotate tokens quarterly or after team member departures
  • Consider using GitHub's OIDC trusted publisher (no tokens needed)

Rollback Procedure

PyPI does not support deleting releases. If you need to rollback:

  1. Yank the bad release (hides from pip install but keeps historical link):

    # Via PyPI web UI: Project โ†’ Releases โ†’ Manage โ†’ Yank
    
  2. Publish fixed version:

    # Increment version: 0.4.0 โ†’ 0.4.1
    python -m build
    twine upload dist/*
    
  3. Notify users:

    โš ๏ธ **Security Advisory**: hexarch-guardrails 0.4.0 has been yanked due to [issue].
    Please upgrade to 0.4.1 immediately:
    
    pip install --upgrade hexarch-guardrails
    

Questions? Open an issue: https://github.com/no1rstack/Hexarch/issues
Want to contribute? See CONTRIBUTING.md

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.3.tar.gz (100.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.3-py3-none-any.whl (104.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for hexarch_guardrails-0.4.3.tar.gz
Algorithm Hash digest
SHA256 d82d20d6bd82f129c543ed5ef52f98d89a5b537fb195ffd832224c9ded4a6f68
MD5 d44c01b0f6375d8da60c5a187d1db149
BLAKE2b-256 69ea82ebfe384dd7182d04494742f2de0cc24b41204bb47beae59cf79e157aaa

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for hexarch_guardrails-0.4.3-py3-none-any.whl
Algorithm Hash digest
SHA256 bc3010dac49721f35b72d8928a3169e1e35c81a16040670147c509c200685e3a
MD5 610af81ae763c9a24ae57f0a45141c84
BLAKE2b-256 9724b5f30458b298dac52324583b2de009bf5921ddd5305d0f59bfed3c6dd043

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