Skip to content

srex-dev/Guardian-Agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Guardian Agent

A lightweight, high-performance safety coprocessor for AI workflows and infrastructure. Guardian Agent is a drop-in sidecar that validates, reasons, and logs actions in real-time, enforcing the principle:

"Only do what you're allowed to do, and always explain why."

πŸ¦€ Built with Rust

Ultra-fast, tiny binary (4MB), production-ready, runs everywhere!

  • πŸš€ 10-100x faster than Python implementations
  • πŸ“¦ 4MB binary (50x smaller than Python containers)
  • πŸ’Ύ 5-10MB memory (10x lower than Python)
  • ⚑ 50ms startup (10x faster than Python)
  • 🌍 Cross-platform - Linux, macOS, Windows, ARM, x86_64
  • πŸ”’ Memory safe - No GC, compile-time safety guarantees

πŸ“Œ Status & Production Use

Currently in beta. Suitable for evaluation, development, and non-critical deployments.

  • Production: Use behind a reverse proxy (nginx, Caddy, Traefik) for TLS (HTTPS). Native TLS is not yet implemented; the server runs HTTP only.
  • Limitations: Per-route RBAC is planned (any authenticated user can call any protected route today). Audit log and MFA secrets are in-memory and do not persist across restarts. See docs/FULL_SYSTEM_ANALYSIS.md for a full analysis and docs/DEPLOYMENT.md for deployment guidance.

🎯 What Is Guardian Agent?

Guardian Agent is a safety coprocessor β€” a lightweight runtime that sits beside any system (AI workflow, API, infrastructure pipeline) and continuously validates, reasons, and logs what that system is doing.

Core Principle

"Only do what you're allowed to do, and always explain why."

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Your App / Agent / Model     β”‚
β”‚ (e.g. LLM, API, CI runner)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚ API / Hook
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Guardian Agent Sidecar       β”‚
β”‚ β€’ Policy validator (OPA)     β”‚
β”‚ β€’ LLM reasoner (Ollama)      β”‚
β”‚ β€’ Token gate / capability    β”‚
β”‚ β€’ Immutable local log        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
         Local or Remote
         Audit Collector

✨ Features

Core Features

  • πŸ”’ Policy Validation: OPA (Open Policy Agent) integration for rule-based validation
  • 🧠 LLM Reasoning: Local LLM (Ollama) for gray-area policy decisions
  • 🎫 Capability Gates: Short-lived JWT tokens for privileged actions
  • πŸ“ Immutable Logging: Cryptographically signed, append-only audit logs
  • ⚑ High Performance: Async I/O, 10000+ req/s throughput
  • πŸ“Š Observability: Built-in metrics collection
  • πŸ”„ Hot Reload: Zero-downtime policy updates
  • 🌍 Cross-Platform: Linux, macOS, Windows, ARM, x86_64
  • 🐳 Docker Ready: Multi-architecture Docker images
  • πŸ“¦ Single Binary: No dependencies, easy deployment

Enterprise Compliance Features (NEW!)

Phase 1: Critical Compliance

  • πŸ“… Data Retention Policies: Automatic log archival and deletion with legal hold support (HIPAA, GDPR, PCI-DSS)
  • πŸ” PII Detection & Redaction: Automatic detection and redaction of SSN, email, credit cards, etc. (HIPAA, GDPR, PCI-DSS)
  • πŸ” Encryption at Rest: AES-256-GCM encryption with KMS integration (AWS KMS, Azure Key Vault, HashiCorp Vault) (HIPAA, PCI-DSS)
  • πŸ‘₯ RBAC for Log Access: Role-based access control with audit logging (SOC 2, HIPAA, PCI-DSS, GDPR)

Phase 2: Important Compliance

  • πŸ“‹ Compliance Reporting: Automated reports for SOC 2, HIPAA, GDPR, PCI-DSS, ISO 27001
  • βš–οΈ Legal Hold: Litigation hold with log preservation (SOC 2, HIPAA, GDPR)
  • πŸ”Ž Forensic Capabilities: Log querying, search, and timeline generation (SOC 2, HIPAA, PCI-DSS)
  • 🏒 Multi-Tenancy Isolation: Tenant isolation with separate configs and keys (SOC 2, HIPAA, GDPR)

Phase 3: Advanced Compliance

  • πŸ”— Chain of Custody: RFC 3161 timestamping for tamper-proof evidence
  • πŸ“Š Regulatory Framework Mappings: Gap analysis and requirement tracking
  • πŸ“ˆ Advanced Analytics: Anomaly detection and compliance risk scoring

MCP (Model Context Protocol) Monitoring

  • πŸ” MCP Protocol Monitoring: Monitor all MCP communications between AI agents
  • πŸ›‘οΈ Tool Call Validation: Validate and block unauthorized tool calls
  • πŸ” Resource Access Control: Control access to resources (files, APIs, etc.)
  • πŸ“ MCP Audit Logging: Complete audit trail of all MCP interactions
  • βš–οΈ Policy Enforcement: Apply governance policies to MCP traffic

πŸš€ Quick Start

Prerequisites

Installation

# Clone the repository
git clone https://github.com/srex-dev/Guardian-Agent.git
cd Guardian-Agent

# Build (takes ~1 minute first time)
cargo build --release --features server

# Binary is ready: target/release/guardian-server (or guardian-server.exe on Windows)

Run

# Run the server
./target/release/guardian-server

# Or with configuration
GUARDIAN_CONFIG=guardian.yaml PORT=8080 ./target/release/guardian-server

Test

# Health check
curl http://localhost:8080/health

# Validate an action
curl -X POST http://localhost:8080/validate \
  -H "Content-Type: application/json" \
  -d '{
    "action": {
      "type": "file_write",
      "resource": "/tmp/test.txt"
    },
    "context": {
      "user_id": "test_user"
    }
  }'

πŸ“– Configuration

Create a guardian.yaml file:

# Policy rules (Rego format or plain text descriptions)
policies:
  - "no external http post except approved domains"
  - "mask pii fields before log write"
  - "require human review for model retrain"

# Paths to Rego policy files
policy_paths:
  - "./policies/base.rego"
  - "./policies/security.rego"

# OPA server URL (optional - for OPA server mode)
# opa_url: "http://localhost:8181"

# LLM Reasoner configuration (optional)
reasoner:
  model: "local:mistral-7b"  # Ollama model name
  temperature: 0.0
  max_tokens: 512
  base_url: "http://localhost:11434"  # Ollama default

# Capability/token gate configuration
capabilities:
  ttl_seconds: 300  # 5 minutes
  algorithm: "HS256"

# Immutable logging configuration
logging:
  log_path: "/var/lib/.log.jsonl"
  rotate_size_mb: 100

# Performance optimizations
cache:
  enable: true
  ttl_seconds: 300
  max_size: 1000

# Hot reload configuration
enable_hot_reload: true

# Rate limiting configuration (optional)
enable_rate_limiting: false
rate_limits:
  "action:file_write":
    capacity: 100
    refill_rate: 10  # requests per second

πŸ—οΈ Architecture

Core Components

  1. Policy Validator (src/policy_validator.rs)

    • Integrates with OPA for policy evaluation
    • Supports OPA server mode (HTTP) or CLI mode
    • Fallback validation when OPA unavailable
    • Fast: 1-5ms per validation
  2. Immutable Logger (src/logger.rs)

    • Zero-copy logging with HMAC-SHA256 signatures
    • Append-only JSONL format
    • Automatic log rotation
    • Device key management
  3. Capability Gate (src/capability_gate.rs)

    • JWT token issuance and validation
    • Short-lived tokens (configurable TTL)
    • Fast: 0.1-0.5ms per operation
  4. Guardian Agent (src/agent.rs)

    • Main orchestrator
    • Coordinates validation, reasoning, logging
    • Manages policy reloading
  5. HTTP Server (src/server.rs)

    • Axum-based async HTTP server
    • High throughput: 10000+ req/s
    • RESTful API endpoints
  6. Metrics Collector (src/metrics.rs)

    • Thread-safe atomic counters
    • Performance tracking
    • Prometheus-compatible

Workflow

1. Action Request β†’ Guardian Agent
2. Policy Validation (OPA) β†’ Allow/Deny/Ambiguous
3. If Ambiguous β†’ LLM Reasoning (Ollama)
4. Generate Verdict β†’ Allow/Deny + Reason
5. Issue Capability Token (if needed)
6. Log Event (signed, immutable)
7. Return Response

πŸ“‘ API Endpoints

POST /validate

Validate an action.

Request:

{
  "action": {
    "type": "file_write",
    "resource": "/tmp/test.txt",
    "method": "write"
  },
  "input_data": {},
  "context": {
    "user_id": "user123",
    "environment": "production"
  }
}

Response:

{
  "allowed": true,
  "reason": "Policy evaluation completed",
  "verdict_id": "abc123",
  "device_id": "def456",
  "confidence": 1.0,
  "latency_ms": 2.5
}

POST /validate/batch

Validate multiple actions in batch (parallel processing).

Request:

{
  "actions": [
    {
      "action": {"type": "file_write", "resource": "/tmp/test1.txt"}
    },
    {
      "action": {"type": "file_write", "resource": "/tmp/test2.txt"}
    }
  ],
  "parallel": true
}

Response:

{
  "results": [...],
  "total_latency_ms": 25.5,
  "success_count": 2,
  "denied_count": 0
}

POST /capability

Validate a capability token.

Request:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "action": "file_write",
  "resource": "/tmp/test.txt"
}

Response:

{
  "valid": true,
  "reason": "Token is valid",
  "payload": {
    "action": "file_write",
    "resource": "/tmp/test.txt",
    "exp": 1234567890
  }
}

GET /health

Health check with metrics.

Response:

{
  "status": "healthy",
  "device_id": "abc123",
  "uptime_seconds": 3600.0,
  "metrics": {
    "validations_total": 1000,
    "validations_allowed": 950,
    "validations_denied": 50,
    "cache_hits": 800,
    "cache_misses": 200
  }
}

GET /metrics

Prometheus metrics endpoint.

POST /policies/reload

Reload policies without restart (hot reload).

Phase 1: Compliance Endpoints

GET /retention/policies

Get current retention policies.

POST /retention/policies

Update retention policies.

POST /retention/process

Manually trigger retention processing.

GET /legal-hold/holds

List all legal holds.

POST /legal-hold/holds

Add a legal hold to preserve logs.

POST /pii/test

Test PII detection on sample data.

GET /encryption/keys

Get encryption key information.

POST /encryption/rotate

Rotate encryption keys.

GET /rbac/users

List all RBAC users.

POST /rbac/users

Create a new RBAC user.

GET /rbac/access-log

Get RBAC access audit log.

Phase 2: Compliance Endpoints

GET /compliance/frameworks

List available compliance frameworks.

POST /compliance/reports

Generate compliance report for a framework.

GET /compliance/requirements/:framework

Get requirements for a compliance framework.

POST /forensics/query

Query logs with filters and date ranges.

POST /forensics/timeline

Generate timeline of events.

GET /tenants

List all tenants (multi-tenancy).

POST /tenants

Create a new tenant.

Phase 3: Advanced Endpoints

GET /chain-of-custody/:id

Get chain of custody for a log entry.

GET /regulatory/mappings/:framework

Get regulatory framework mappings.

POST /regulatory/gap-analysis/:framework

Perform gap analysis for a framework.

GET /analytics/anomalies

Detect anomalies in logs.

GET /analytics/risk-score/:framework

Calculate compliance risk score.

🌍 Cross-Platform Deployment

Build for Different Platforms

Linux (x86_64)

cargo build --release --target x86_64-unknown-linux-gnu --features server

Linux (ARM64 - Raspberry Pi, AWS Graviton)

cargo build --release --target aarch64-unknown-linux-gnu --features server

macOS (Intel)

cargo build --release --target x86_64-apple-darwin --features server

macOS (Apple Silicon)

cargo build --release --target aarch64-apple-darwin --features server

Windows

cargo build --release --features server

Static Binary (Most Portable)

Build a static binary with no dependencies:

# Install musl target
rustup target add x86_64-unknown-linux-musl

# Build static binary
cargo build --release --target x86_64-unknown-linux-musl --features server

# Result: Single binary, works on any Linux!

Cross-Compilation

Use the cross tool for easy cross-compilation:

# Install cross
cargo install cross

# Build for Linux from Windows/macOS
cross build --release --target x86_64-unknown-linux-gnu --features server

🐳 Docker Deployment

Single Architecture

# Build
docker build -t guardian:latest .

# Run
docker run -p 8080:8080 \
  -v $(pwd)/guardian.yaml:/app/guardian.yaml:ro \
  -v $(pwd)/policies:/app/policies:ro \
  -v guardian-logs:/var/lib/guardian \
  guardian:latest

Multi-Architecture

# Build for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64 \
  -t guardian:latest \
  --push \
  .

# Docker automatically selects correct architecture
docker run -p 8080:8080 guardian:latest

Docker Compose

version: '3.8'

services:
  guardian:
    build: .
    ports:
      - "8080:8080"
    volumes:
      - ./guardian.yaml:/app/guardian.yaml:ro
      - ./policies:/app/policies:ro
      - guardian-logs:/var/lib/guardian
    environment:
      - GUARDIAN_CONFIG=/app/guardian.yaml
      - PORT=8080

πŸ“Š Performance

Benchmarks

Metric Value
Throughput 10000+ req/s
Latency (cached) 0.1-1ms
Latency (uncached) 1-5ms
Memory Usage 5-10MB
Startup Time 50ms
Binary Size 4MB

Comparison with Python

Metric Python Rust Improvement
Policy Validation 10-50ms 1-5ms 10x
JWT Operations 1-5ms 0.1-0.5ms 10x
Log Writing 2-10ms 0.2-1ms 10x
HTTP Throughput 1000 req/s 10000+ req/s 10x+
Memory Usage 50-100MB 5-10MB 10x
Startup Time 500ms 50ms 10x
Binary Size 200MB 4MB 50x

πŸ”§ Development

Build

# Debug build
cargo build

# Release build
cargo build --release --features server

# With optimizations
RUSTFLAGS="-C target-cpu=native" cargo build --release --features server

Test

# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Run specific test
cargo test test_policy_validator

Run

# Run directly
cargo run --release --features server

# Run with config
GUARDIAN_CONFIG=guardian.yaml cargo run --release --features server

Format & Lint

# Format code
cargo fmt

# Lint
cargo clippy

# Lint with fixes
cargo clippy --fix

πŸ“ Policy Examples

Basic Policy (Rego)

Create policies/example.rego:

package guardian

default allow = false

# Allow file writes to /tmp
allow {
    input.action.type == "file_write"
    input.action.resource = startswith("/tmp/")
}

# Allow file writes to home directories
allow {
    input.action.type == "file_write"
    input.action.resource = startswith("/home/")
}

# Deny writes to system directories
deny {
    input.action.type == "file_write"
    input.action.resource = startswith("/etc/")
}

# Final decision
allow {
    not deny
}

Policy Configuration

In guardian.yaml:

policy_paths:
  - "./policies/example.rego"

# Or use OPA server
opa_url: "http://localhost:8181"

πŸ” Security

Features

  • βœ… Memory safety - Rust's compile-time guarantees
  • βœ… Cryptographic signatures - HMAC-SHA256 for log integrity
  • βœ… Capability tokens - Short-lived JWTs for privileged actions
  • βœ… Immutable logs - Append-only, tamper-evident
  • βœ… Input validation - Type-safe API
  • βœ… Rate limiting - Prevent abuse

Best Practices

  1. Secure key storage - Store signing keys securely
  2. Policy review - Review policies before deployment
  3. Log monitoring - Monitor audit logs regularly
  4. Rate limiting - Enable rate limiting in production
  5. HTTPS - Use HTTPS in production (reverse proxy)

πŸš€ Deployment Examples

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: guardian-agent
spec:
  replicas: 1
  selector:
    matchLabels:
      app: guardian
  template:
    metadata:
      labels:
        app: guardian
    spec:
      containers:
      - name: guardian
        image: guardian:latest
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: config
          mountPath: /app/guardian.yaml
          subPath: guardian.yaml
        - name: policies
          mountPath: /app/policies
        - name: logs
          mountPath: /var/lib/guardian
      volumes:
      - name: config
        configMap:
          name: guardian-config
      - name: policies
        configMap:
          name: guardian-policies
      - name: logs
        emptyDir: {}

Systemd Service

Create /etc/systemd/system/guardian.service:

[Unit]
Description=Guardian Agent
After=network.target

[Service]
Type=simple
User=guardian
WorkingDirectory=/opt/guardian
ExecStart=/opt/.guardian
Environment="GUARDIAN_CONFIG=/etc/.guardian.yaml"
Environment="PORT=8080"
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Docker Compose (Production)

version: '3.8'

services:
  guardian:
    image: guardian:latest
    ports:
      - "8080:8080"
    volumes:
      - ./guardian.yaml:/app/guardian.yaml:ro
      - ./policies:/app/policies:ro
      - guardian-logs:/var/lib/guardian
    environment:
      - GUARDIAN_CONFIG=/app/guardian.yaml
      - PORT=8080
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  guardian-logs:

πŸ“Š Monitoring

Metrics

Access Prometheus metrics at /metrics:

curl http://localhost:8080/metrics

Key Metrics

  • guardian_validations_total - Total validations
  • guardian_validation_latency_seconds - Validation latency
  • guardian_cache_size - Cache size
  • guardian_errors_total - Error count

Health Check

curl http://localhost:8080/health

Returns:

  • Status
  • Device ID
  • Uptime
  • Metrics snapshot

πŸ§ͺ Testing

Unit Tests

cargo test

Integration Tests

# Start server
./target/release/guardian-server &

# Test endpoints
curl http://localhost:8080/health
curl -X POST http://localhost:8080/validate ...

Load Testing

# Using Apache Bench
ab -n 10000 -c 100 http://localhost:8080/health

# Using wrk
wrk -t12 -c400 -d30s http://localhost:8080/health

πŸ› Troubleshooting

Server Won't Start

# Check if port is in use
netstat -an | grep 8080

# Check logs
RUST_LOG=debug ./target/release/guardian-server

OPA Not Found

# Install OPA
# See: https://www.openpolicyagent.org/docs/latest/#running-opa

# Or use OPA server mode
opa_url: "http://localhost:8181"

Ollama Connection Failed

# Start Ollama
ollama serve

# Check connection
curl http://localhost:11434/api/tags

Policy Not Loading

# Check policy file paths
ls -la policies/

# Check configuration
cat guardian.yaml

# Enable debug logging
RUST_LOG=debug ./target/release/guardian-server

πŸ“š Advanced Usage

Hot Reload Policies

# Reload policies without restart
curl -X POST http://localhost:8080/policies/reload

Batch Validation

curl -X POST http://localhost:8080/validate/batch \
  -H "Content-Type: application/json" \
  -d '{
    "actions": [
      {"action": {"type": "file_write", "resource": "/tmp/test1.txt"}},
      {"action": {"type": "file_write", "resource": "/tmp/test2.txt"}}
    ],
    "parallel": true
  }'

Capability Tokens

# Validate capability token
curl -X POST http://localhost:8080/capability \
  -H "Content-Type: application/json" \
  -d '{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "action": "file_write",
    "resource": "/tmp/test.txt"
  }'

πŸ“š Documentation

πŸ”— Integration Examples

AI Inference Wrapper

use guardian_rs::{GuardianAgent, GuardianConfig};

// Initialize agent
let config = GuardianConfig::from_file("guardian.yaml").await?;
let agent = GuardianAgent::new(config).await?;

// Validate LLM prompt
let action = serde_json::json!({
    "type": "llm_inference",
    "prompt": user_prompt,
    "model": "gpt-4"
});

let result = agent.validate_action(&action, None, None).await?;
if result.allowed {
    // Make LLM API call
} else {
    // Deny request
}

CI/CD Hook

#!/bin/bash
# Pre-deploy validation

RESULT=$(curl -s -X POST http://localhost:8080/validate \
  -H "Content-Type: application/json" \
  -d "{
    \"action\": {
      \"type\": \"infrastructure_change\",
      \"resource\": \"$TERRAFORM_PLAN\"
    }
  }")

if echo "$RESULT" | jq -e '.allowed == true' > /dev/null; then
    echo "Deployment approved"
    exit 0
else
    echo "Deployment denied: $(echo $RESULT | jq -r '.reason')"
    exit 1
fi

API Gateway Plugin

// Middleware example
async fn guardian_middleware(request: Request, next: Next) -> Response {
    let action = extract_action(&request);
    let result = agent.validate_action(&action, None, None).await?;
    
    if !result.allowed {
        return Response::new(StatusCode::FORBIDDEN);
    }
    
    next.run(request).await
}

πŸ“– Project Structure

.
β”œβ”€β”€ Cargo.toml          # Rust project configuration
β”œβ”€β”€ Dockerfile          # Docker build
β”œβ”€β”€ Makefile           # Build automation
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ lib.rs         # Library entry point
β”‚   β”œβ”€β”€ main.rs        # Binary entry point
β”‚   β”œβ”€β”€ agent.rs       # Main orchestrator
β”‚   β”œβ”€β”€ policy_validator.rs  # OPA integration
β”‚   β”œβ”€β”€ logger.rs      # Immutable logging
β”‚   β”œβ”€β”€ capability_gate.rs   # JWT operations
β”‚   β”œβ”€β”€ server.rs      # HTTP server
β”‚   β”œβ”€β”€ metrics.rs     # Metrics collection
β”‚   β”œβ”€β”€ config.rs      # Configuration
β”‚   └── error.rs       # Error handling
β”œβ”€β”€ policies/          # Policy files (Rego)
β”‚   └── example.rego
└── guardian.yaml      # Configuration file

🎯 Use Cases

AI Workflows

  • βœ… Validate LLM prompts before execution
  • βœ… Block harmful completions
  • βœ… Enforce content policies
  • βœ… Log all AI interactions

Infrastructure

  • βœ… Validate infrastructure changes
  • βœ… Enforce compliance policies
  • βœ… Audit infrastructure actions
  • βœ… Prevent unauthorized changes

APIs

  • βœ… Validate API requests
  • βœ… Enforce rate limits
  • βœ… Audit API usage
  • βœ… Block malicious requests

CI/CD

  • βœ… Pre-deploy validation
  • βœ… Policy compliance checks
  • βœ… Security scanning
  • βœ… Audit deployment actions

πŸ”§ Configuration Reference

Full Configuration

# Policy configuration
policies:
  - "policy rule 1"
  - "policy rule 2"

policy_paths:
  - "./policies/base.rego"

opa_url: "http://localhost:8181"  # Optional

# LLM reasoner
reasoner:
  model: "local:mistral-7b"
  temperature: 0.0
  max_tokens: 512
  base_url: "http://localhost:11434"

# Capabilities
capabilities:
  ttl_seconds: 300
  algorithm: "HS256"

# Logging
logging:
  log_path: "/var/lib/.log.jsonl"
  rotate_size_mb: 100

# Cache
cache:
  enable: true
  ttl_seconds: 300
  max_size: 1000

# Hot reload
enable_hot_reload: true

# Rate limiting
enable_rate_limiting: false
rate_limits:
  "action:file_write":
    capacity: 100
    refill_rate: 10

πŸ“Š Performance Tuning

Optimize for Size

cargo build --release --features server \
  -- -C opt-level=z -C lto=thin

Optimize for Speed

RUSTFLAGS="-C target-cpu=native" \
  cargo build --release --features server

Static Binary

cargo build --release \
  --target x86_64-unknown-linux-musl \
  --features server

🐳 Docker Build

Standard Build

docker build -t guardian:latest .

Multi-Architecture Build

docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t guardian:latest \
  --push \
  .

πŸš€ Production Deployment

Recommended Setup

  1. Use static binary - No dependencies
  2. Enable rate limiting - Prevent abuse
  3. Configure hot reload - Zero downtime updates
  4. Set up monitoring - Track metrics
  5. Use HTTPS - Reverse proxy (nginx, Traefik)
  6. Secure keys - Store signing keys securely
  7. Rotate logs - Configure log rotation
  8. Backup logs - Regular backups

System Requirements

  • CPU: 1 core (2+ recommended)
  • Memory: 10MB minimum (50MB recommended)
  • Disk: 100MB for binary + logs
  • Network: Any (HTTP/HTTPS)

πŸ“ Log Format

Logs are written in JSONL format with cryptographic signatures:

{
  "timestamp": "2024-01-01T12:00:00Z",
  "event_type": "action_validated",
  "action": {
    "type": "file_write",
    "resource": "/tmp/test.txt"
  },
  "verdict": {
    "allowed": true,
    "reason": "Policy evaluation completed",
    "device_id": "abc123"
  },
  "metadata": {},
  "signature": "hmac-sha256-signature"
}

πŸ” Troubleshooting

Common Issues

  1. Port already in use

    # Use different port
    PORT=8081 ./target/release/guardian-server
  2. Policy not found

    # Check policy paths
    ls -la policies/
  3. OPA connection failed

    # Check OPA server
    curl http://localhost:8181/health
  4. Permission denied

    # Check file permissions
    chmod +x target/release/guardian-server

🀝 Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines. To report a security vulnerability, see SECURITY.md.

πŸ“„ License

MIT License - see LICENSE for details.

πŸ™ Acknowledgments

πŸ“ž Support


Guardian Agent - Safety coprocessor for AI workflows and infrastructure.

Built with Rust - Fast, safe, reliable.

About

A lightweight, high-performance safety coprocessor for AI workflows and infrastructure. Guardian Agent is a drop-in sidecar that validates, reasons, and logs actions in real-time, enforcing the principle

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages