Skip to content

Architecture

AegisAI is a multi-tenant AI agent security platform built on a FastAPI backend, Vite frontend, PostgreSQL persistence, Redis pub/sub, and an OPA policy engine. This document describes the major components, data flows, and security layers.

System Components

flowchart LR
    subgraph Presentation
        FE[Vite SPA<br/>:5173]
        LEG[Legacy Dashboard<br/>/dashboard]
    end

    subgraph API["FastAPI Application :8000"]
        GW[API Gateway<br/>/api/v1]
        WH[Webhooks<br/>/webhooks]
        WSS[WebSocket<br/>/api/v1/ws]
    end

    subgraph Services
        AR[Agent Registry]
        PS[Policy Service]
        SS[Security Service]
        AS[Audit Service]
        ADS[Anomaly Detector]
        GUARD[Prompt Guard]
        HITL[HITL Service]
        US[User Service]
        EP[Event Publisher]
        SIEM[SIEM Exporter]
    end

    subgraph External
        OPA[OPA :8181]
        PG[(PostgreSQL)]
        RD[(Redis)]
    end

    FE --> GW
    FE <--> WSS
    LEG --> GW
    WH --> SS

    GW --> AR & PS & SS & AS & ADS & GUARD & HITL & US
    US --> SIEM
    SS --> OPA
    PS --> OPA
    GUARD --> OPA
    GUARD --> RD
    GUARD --> AS
    EP --> RD
    WSS --> RD

    AR & PS & AS & ADS & HITL & US --> PG

Component Reference

Component Location Responsibility
API Gateway app/main.py, app/api/v1/ REST API, routing, CORS, exception handling
Agent Registry app/services/agent_registry.py Agent registration, heartbeat, lifecycle
Policy Service app/services/policy_service.py CRUD for tenant policies, template seeding
Policy Engine policies/engine.py OPA evaluation, Rego template loading, fallback engine
Security Service app/services/security_service.py Enhanced policy checks, risk scoring, anomaly reporting
Audit Service app/services/audit_service.py Tamper-evident logging, export jobs
Anomaly Detector security/anomaly_detector.py Supervised ML + Isolation Forest / ONNX hybrid + rules
Anomaly Hybrid security/anomaly_hybrid.py Backend selection, global fallback, external escalate
Agent Embeddings app/services/agent_embedding_service.py Semantic search, predicted type / risk
Shadow AI app/services/shadow_ai_service.py Unknown-agent fingerprinting → HITL register
Prompt Guard app/guard/ Prompt injection / jailbreak / leakage (rules + ML + OPA)
HITL Service app/services/security_service.py Approval request lifecycle
Event Publisher app/services/event_publisher.py Redis pub/sub for real-time events
WebSocket Manager app/services/websocket_manager.py Connection management, tenant-scoped broadcasts
User Service app/services/user_service.py Authentication, user CRUD, session management
SSO Service app/services/sso_service.py, app/auth/sso/ OIDC login, JIT provisioning, role mapping
SIEM Exporter app/services/siem/exporter.py Batched export to Syslog, Splunk, ELK
Frontend SPA frontend/ Dashboard UI, routing, real-time updates

Data Flow

Agent Action with Policy Check

sequenceDiagram
    participant Agent
    participant API as FastAPI
    participant SS as Security Service
    participant OPA
    participant AD as Anomaly Detector
    participant AUD as Audit Service
    participant HITL
    participant WS as WebSocket

    Agent->>API: POST /api/v1/policies/check
    API->>SS: check_policy_enhanced()
    SS->>OPA: Evaluate Rego policies
    OPA-->>SS: allow/deny + reason
    SS->>AD: Score behavioral anomaly
    AD-->>SS: risk_score, is_anomaly

    alt Policy denied
        SS->>WS: policy.violated event
    end

    alt Anomaly detected
        SS->>AUD: report_anomaly()
    end

    alt Requires approval
        SS->>HITL: create approval request
    end

    SS-->>API: PolicyCheckResponse
    API-->>Agent: allowed, risk_score, required_approval

Agent Prompt with Guard Check

sequenceDiagram
    participant Client
    participant MW as Guard Middleware
    participant GS as Guard Service
    participant RD as Redis
    participant OPA
    participant AUD as Audit Service

    Client->>MW: POST /agents/{id}/chat
    MW->>GS: validate(prompt)
    GS->>RD: cache lookup
    alt Cache miss
        GS->>GS: rules + ML (parallel)
        GS->>OPA: guard.main
        GS->>RD: cache result
    end
    alt Blocked
        GS->>AUD: log anomaly
        MW-->>Client: 403 + Guard details
    else Allowed
        MW->>MW: forward to route
    end

See Prompt Guard.

Real-time Event Flow

  1. An API action triggers an event (e.g., policy.violated, anomaly.detected)
  2. event_publisher publishes to a Redis channel scoped by tenant_id
  3. The WebSocket manager's Redis listener receives the event
  4. Connected dashboard clients for that tenant receive the message via /api/v1/ws

Authentication Flow

Password login:

sequenceDiagram
    participant User
    participant FE as Frontend
    participant API as FastAPI
    participant DB as PostgreSQL

    User->>FE: email + password
    FE->>API: POST /api/v1/auth/login
    API->>DB: authenticate user
    DB-->>API: user record
    API->>DB: issue session API key
    API-->>FE: JWT + api_key + user
    FE->>FE: Store session

    Note over FE,API: Subsequent API calls
    FE->>API: Authorization: Bearer <jwt>
    FE->>API: X-API-Key: <api_key>

SSO (OIDC): User clicks IdP button → redirect to Keycloak/Okta/etc. → callback → one-time exchange code → JWT. See SSO Configuration.

Security Layers

AegisAI applies defense in depth across five layers:

1. Transport & Network

  • HTTPS termination at reverse proxy (production)
  • CORS middleware on the API
  • Docker network isolation between services

2. Authentication

Two complementary mechanisms:

Mechanism Header Use Case
JWT Authorization: Bearer <token> User sessions, WebSocket (?token=)
API Key X-API-Key: <key> Tenant-scoped agent/SDK operations
Admin Key X-Admin-Key: <key> Tenant provisioning, SIEM admin
SSO (OIDC) External IdP Enterprise login via Keycloak, Okta, Google, Entra ID

User API keys are hashed at rest. Session API keys are issued on login (password or SSO) for dashboard convenience. SSO users have no local password (password_hash is NULL).

3. Authorization (RBAC)

Role-based access control with five roles:

Role Rank Scope
super_admin 5 Full platform access, cross-tenant
admin 4 Full tenant management
security_analyst 3 Audit, anomalies, read policies
developer 2 Agent management, read audit
viewer 1 Dashboard and audit read-only

Permissions are enforced per-resource (users, policies, agents, audit, anomalies, hitl, dashboard) via require_permission dependencies.

4. Policy Engine (OPA)

  • Rego templates loaded at startup into OPA (:8181)
  • Templates: gdpr, hipaa, fz152, hitl, guard, custom, main
  • Fallback in-process engine when OPA is unavailable
  • Enhanced checks combine OPA decisions with risk scoring and anomaly detection

5. Prompt Guard

  • Middleware inspects prompts on agent chat/action paths when ENABLE_GUARD=true
  • Detectors: regex/banlist, TF-IDF + Isolation Forest, OPA package guard.main
  • Redis cache (TTL configurable); audit log on blocked/suspicious results
  • Fail-open on detector errors for availability; strong rule/OPA hits hard-block
  • Details: Prompt Guard

6. Audit & Integrity

  • All agent actions logged with structured metadata
  • Optional HMAC signing (AUDIT_SIGNING_ENABLED=true)
  • Export to CSV, JSON, or async jobs for compliance archives
  • Anomaly reports linked to audit events for forensic correlation
  • Guard blocks recorded in the same audit trail

Multi-Tenancy

Every resource (agents, policies, audit logs, anomalies, HITL requests) is scoped to a tenant_id:

  • API keys resolve to a tenant context via get_current_tenant
  • RBAC enforces same-tenant access (except super_admin)
  • WebSocket events are broadcast only to connections in the same tenant
  • Default policies are seeded when a tenant is created

Database Schema (Key Tables)

Table Purpose
tenants Organization boundaries, API keys
users Authentication, roles, tenant membership, SSO identity
api_keys Per-user API keys (hashed)
agents Registered AI agents
policies Tenant policy definitions (JSON rules)
audit_logs Tamper-evident action records
anomaly_reports Detected behavioral anomalies
anomaly_training_samples Labeled features for supervised retrain
anomaly_model_versions Per-tenant anomaly model version metadata
agent_embeddings Semantic search vectors + predicted type / risk
discovery_candidates Shadow AI unknown-agent candidates
hitl_requests Pending and resolved approvals

Migrations are managed with Alembic (migrations/).

Deployment Topology

flowchart TB
    subgraph Docker Compose
        PG[(postgres:15)]
        RD[(redis:7)]
        OPA[opa:latest]
        APP[app<br/>FastAPI + Uvicorn]
        FE[frontend<br/>Vite dev server]
    end

    APP --> PG & RD & OPA
    FE -->|VITE_PROXY_TARGET| APP

In production, the frontend is built to static assets and served behind a reverse proxy alongside the API. See Deployment.