Retrieved article excerpt
Open article Β· Retrieved 2026-11-15T19:21:29.789202+00:00
# π‘οΈ Aegis Security Proxy
[PyPI version](https://pypi.org/project/aegis-proxy-sdk/)
[Docker Pulls](https://hub.docker.com/r/raymondartin2/aegis-proxy)
[License](https://github.com/raymondhani/aegis-proxy/blob/main/LICENSE)
---
Aegis sits between your application and your Postgres database and blocks destructive queries before they run, without you changing a line of your database code.
---
> **π Note:** If you are cloning this to test the Wasm AST parser locally, please drop a β on the repo! It helps me know people are actually using the open-source tier.
---
## How it fits together
```
sequenceDiagram
participant App as Your Application<br/>(psycopg2, or any client)
participant Proxy as Aegis Proxy<br/>:5433 TCP intercept / :5434 admin+metrics
participant DB as Your Database<br/>(e.g. Neon Postgres)
App->>Proxy: SELECT ... (benign query)
Proxy->>DB: forwarded over TLS
DB-->>Proxy: rows
Proxy-->>App: rows
App->>Proxy: DROP TABLE ... (destructive query)
Note over Proxy: parsed, blocked, connection terminated<br/>(the "Guillotine")
Proxy-->>App: fatal error
Note over DB: never reached
```
Loading
Your application never talks to the database directly β every query passes through the proxy first. A benign query is forwarded and the rows come straight back. A destructive one (`DROP TABLE`, an unfiltered `DELETE`, etc.) is intercepted and the connection is terminated before it reaches your database.
Plain-text diagram (terminal-friendly)
```
Your Application Aegis Proxy Your Database
(psycopg2, or any client) (e.g. Neon Postgres)
+--------------------+ Postgres wire +-----------------------------+ TLS +--------------------+
| | ------------------> | :5433 TCP intercept | -------> | |
| SELECT ... | | - parses every query | | real database |
| DROP TABLE ... | <------------------ | - enforces rate limits | <------- | |
| | rows, or a | - blocks destructive | | |
+--------------------+ fatal error | statements (the | +--------------------+
if blocked | "Guillotine") |
| :5434 admin + metrics API |
+-----------------------------+
```
## Quickstart
Three steps, one command to start the stack, and a running proxy.
### Step 1 β Get Aegis and your credentials
The primary way to install Aegis is to pull the published image straight from Docker Hub:
```
docker pull raymondartin2/aegis-proxy
```
**Expected output** (tag/digest will vary by release):
```
latest: Pulling from raymondartin2/aegis-proxy
Digest: sha256:...
Status: Downloaded newer image for raymondartin2/aegis-proxy:latest
docker.io/raymondartin2/aegis-proxy:latest
```
You still need this repo's `docker-compose.yml` and `.env.sample` to run the stack, so grab those too:
```
git clone https://github.com/raymondhani/aegis-proxy.git
cd aegis-proxy
cp .env.sample .env
```
Building the image yourself instead of pulling it is also supported β see `Dockerfile` in this repo β but pulling the published image is the recommended, primary path.
Now open `.env` and replace the four placeholders with your own values:
| Placeholder in `.env.sample` | What to put there |
| --- | --- |
| `NEON_API_KEY=your_api_key_here` | An API key from your [Neon](https://neon.tech) account |
| `NEON_PROJECT_ID=your_project_id_here` | The Neon project Aegis should provision ephemeral branches in |
| `AEGIS_ADMIN_TOKEN=your_custom_admin_token_12345` | Any string you choose β Aegis's own admin credential, not from Neon |
| `AEGIS_JWT_SECRET=your_super_secret_jwt_key_that_is_at_least_32_bytes_long` | Any string **at least 32 characters long** β used to sign session tokens |
None of these are optional: the proxy exits immediately at startup if `AEGIS_JWT_SECRET` is missing, and every step below assumes all four are set.
### Step 2 β Start the stack
```
docker compose up -d
```
**Expected output** (container name may vary slightly depending on your folder name):
```
Container aegis-proxy Started
```
This single command starts the container Aegis needs: the proxy itself, listening on `5433` (the database connection) and `5434` (an admin/metrics API). The OSS proxy runs on in-memory state and has no hard dependency on Redis β Redis is used only by the Enterprise tier for distributed/HA state.
### Step 3 β Confirm it's running
```
curl -s http://localhost:5434/metrics
```
**Expected output:**
```
{"queries_processed":0,"queries_blocked":0,"active_connections":0,"sessions_jailed":0,"anomalies_detected":0}
```
If you see that, the proxy is up and ready to accept connections.
## Try it: block a destructive query
Install the SDK and the Postgres driver, then run this against the stack you just started β nothing here needs modification beyond the credentials you already set in `.env`.
```
pip install aegis-proxy-sdk psycopg2-binary
```
```
import psycopg2
from aegis_sdk import safe_db_run
@safe_db_run()
def run_demo(db_url: str):
conn = psycopg2.connect(db_url)
conn.autocommit = True
cursor = conn.cursor()
print("Running an ordinary query...")
cursor.execute("SELECT 1;")
print(f"Result: {cursor.fetchone()}")
print("Running a destructive query: DROP TABLE users;")
cursor.execute("DROP TABLE users;")
if __name__ == "__main__":
try:
run_demo()
except psycopg2.OperationalError as e:
print(f"\n[Aegis] Connection severed by the proxy: {e}")
```
The `@safe_db_run()` decorator does the setup for you: it provisions a throwaway Neon database branch, mints a session token, and points `db_url` at the local proxy instead of the real database β then deletes the branch again when the function returns. Your function just receives a working `db_url` and uses it like any other Postgres connection string.
**Expected output:**
```
Running an ordinary query...
Result: (1,)
Running a destructive query: DROP TABLE users;
[Aegis] Connection severed by the proxy: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
The `SELECT 1` succeeds normally. The `DROP TABLE` never reaches the database β the proxy detects it, terminates the connection, and `psycopg2` surfaces that as `OperationalError`. Catching that exception around the specific call you expect to be blocked is the intended pattern, not a workaround.
`@safe_db_run` also accepts a few optional keyword arguments for less common setups:
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `agent_id` | `str` | `None` | A label for this run, included in telemetry β useful when multiple agents share one proxy. |
| `proxy_port` | `int` | `5433` | The TCP port the proxy is listening on, if you changed it from the default. |
| `validation_rules` | `list` | built-in schema checks | Custom functions to run against the database schema before/after execution, replacing the defaults (no dropped tables, no dropped columns, every table keeps a primary key). |
## Drop-in Guardrails for LangChain & AI Agents
Because Aegis operates completely transparently at Layer-4 (the network layer), developers do not need to write custom application code, install framework-specific plugins, or change their AI logic. To secure an AI agent against hallucinations, simply spin up Aegis and change your standard database connection port from 5432 to 5433.
```
# The Old, Dangerous Way (Direct to DB):
db = SQLDatabase.from_uri("postgresql://user:pass@localhost:5432/my_db")
# The Secure, Aegis Way (Routed through the Layer-4 Proxy):
db = SQLDatabase.from_uri("postgresql://user:pass@localhost:5433/my_db")
```
## What each tier gives you
Aegis ships as three products built on the same core. Every capability below is enforced by the proxy itself, not just documented β the automated benchmark suite in this workspace asserts each one directly against a running instance of every tier.
| Capability | OSS Proxy (self-hosted) | Hosted SaaS (managed) | Enterprise Guardrail (self-hosted) |
| --- | --- | --- | --- |
| **Static rate limiting** β stops a single client from firing more queries per minute than the account allows | β
| β
| β
|
| **Wire transparency** β works with your existing Postgres client, unmodified, by speaking the same wire protocol | β
| β
| β
|
| **The Guillotine** β instantly kills any connection that tries to run a destructive statement, before it reaches your database | β
| β
| β
|
| **ML adaptive throttling** β learns each agent's normal query pattern and slows down abnormal spikes automatically, instead of one fixed limit for everyone | β | β
*(paid plans)* | β
|
| **Central fleet telemetry** β live query activity across your whole fleet of proxies in one feed, not one proxy at a time | β | β
*(paid plans)* | β
|
| **eBPF kernel-bypass** β drops malicious traffic inside the Linux kernel itself, before user-space code ever sees it, for the lowest possible latency | β | β | β
|
| **Custom AST policies** β write your own rules for which query patterns are allowed, beyond the built-in defaults | β | β | β
|
## Troubleshooting
| Symptom | Cause | Fix |
| --- | --- | --- |
| **Wrong port** β your app hangs or times out connecting on `5432` | Aegis is not a Postgres server on the standard port. It listens on `5433` specifically, so it can run alongside a real Postgres instance on the same host without colliding. | Point your connection string at `5433` β the `docker-compose.yml` in this repo already maps it. |
| **Missing credentials** β the container exits right after starting (`docker compose ps` shows `Exited`), or your script raises `ValueError: AEGIS_JWT_SECRET environment variable is missing.` | `.env` was never created, or one of the four values is still the placeholder from `.env.sample`. | `cp .env.sample .env`, fill in real values (`AEGIS_JWT_SECRET` needs to be 32+ characters), then `docker compose up -d` again. |
| **Container not started** β `docker ps` shows nothing for `aegis-proxy` | `docker compose up -d` was never run in this directory, or it failed earlier without you noticing. | Run `docker compose up -d` from the repo root and read its output β each container should say `Started`. |
| **Connection refused** β `docker compose ps` shows `aegis-proxy` as `Up`, but your client still can't connect | Almost always a host mismatch. A client running inside its own Docker container can't reach the proxy via `localhost` β it needs the Docker-internal address. | From another container, connect to `host.docker.internal:5433` (Mac/Windows) or join the `aegis-net` network and use the service name `aegis-proxy`. Running your script directly on the host, as in the quickstart above, needs no special host. |
| **Unexpectedly severed query** β `psycopg2.OperationalError: server closed the connection unexpectedly` right after running a query | This is almost always the Guillotine working as intended β the proxy detected a destructive statement and terminated the connection to block it. It is not a network problem. | Catch `psycopg2.OperationalError` around the specific call, exactly as the example above does. If a query you didn't expect to be destructive gets blocked, that's a policy question, not a connectivity bug. |
---
## ποΈ Multi-Agent Architecture
Aegis is designed to support a **Multi-Agent Workflow** where several autonomous AI agents can operate simultaneously without cross-contamination.
- **Sandboxed Execution:** Every agent interaction is securely sandboxed in a dedicated C