Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🛡️ AegisGate

CI Build Python 3.10+ License: Apache 2.0 Tests: 30/30 Green Anti-Corruption

Local-first, zero-leak AST and Shannon entropy security proxy & Git pre-commit firewall.
Intercepts source code, Git commits, and outgoing LLM completion payloads (/v1/chat/completions) to detect, mask, or block hardcoded API keys, bearer tokens, and credentials before they hit public model providers or remote Git repositories.


⚠️ The Problem

Modern AI coding agents (such as Cursor, Claude Code, Copilot, and custom LangChain/LangGraph autonomous loops) routinely index your entire workspace, frequently serializing active .env files, database connection strings, and production API tokens directly into outbound LLM completion prompts. Once leaked into remote inference logs or training corpuses, credentials are permanently compromised, resulting in silent data exposure and catastrophic security breaches.


🏛️ System Architecture

[ Developer / Cursor / Claude Code ]
                 │
                 │  HTTP POST /v1/chat/completions (OpenAI SDK / LangChain / IDE)
                 ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                         AEGISGATE SECURITY FIREWALL                         │
│                                                                             │
│  1. Ingress Payload Inspection                                              │
│     ├── OpenAI-Compatible Reverse Proxy & Git Pre-Commit Hook               │
│     └── JSON Parser & AST Source Code Boundary Isolator                     │
│                                                                             │
│  2. Multi-Stage Detection Pipeline                                          │
│     ├── Known Regex Signatures (AWS, GitHub PAT, OpenAI, Google, JWT, SSH) │
│     ├── Compiler-Level AST Scanner (Python assignments, dicts, kwargs)     │
│     └── Shannon Entropy Windowing (H(X) >= 4.2 bits/char, sliding spans)    │
│                                                                             │
│  3. Autonomous Healing & Policy Engine                                      │
│     ├── Self-Healing Agent: Extract to .env, update .gitignore, AST rewrite │
│     ├── Policy Verdict: [ MASK ] vs [ BLOCK ]                               │
│     └── Structural Integrity Re-validation (JSON syntax & Python AST parse) │
│         ├── If Syntax Corrupted  ──► HTTP 400 Hard Block (Zero Malformed)   │
│         └── If Syntax Preserved  ──► Stream Redacted Body to Upstream       │
└──────────────────────────────────────┬──────────────────────────────────────┘
                                       │
                                       │  Sanitized Payload (Zero Leaks)
                                       ▼
                     [ Upstream LLM (OpenAI / Anthropic) ]

⚡ 60-Second Quickstart

# Install AegisGate
pip install aegisgate

# Run an instant credential audit on a file or directory
aegisgate scan demo/sample_payload.py

# Autonomously heal your code: extract credentials to .env and rewrite AST
aegisgate heal demo/sample_payload.py --dry-run

AegisGate Autonomous Self-Healing Demo


💻 CLI Reference

1. Static Directory & File Scanner (aegisgate scan)

# Scan a single file with interactive diagnostic output
aegisgate scan demo/sample_payload.py

# Machine-readable JSON output for automated CI pipelines
aegisgate scan demo/sample_payload.py --format json

# Strict blocking mode (exits with code 1 upon secret detection)
aegisgate scan src/ --mode block

# Scan standard input pipe (e.g. inspecting shell environment dumps)
cat .env | aegisgate scan -

2. Autonomous Self-Healing Agent (aegisgate heal)

Automatically migrate hardcoded credentials out of your codebase into secure .env variables without breaking syntax:

# Preview proposed AST code changes and unified diffs without modifying files
aegisgate heal src/ --dry-run

# Apply self-healing: extracts secrets to .env, adds .env to .gitignore, and rewrites AST
aegisgate heal src/

# Specify custom environment file
aegisgate heal src/ --env-file .env.local

What the Autonomous Healing Agent does:

  1. Extracts hardcoded credentials into .env with canonical variable naming (e.g. OPENAI_API_KEY="sk-...", AWS_ACCESS_KEY_ID="AKIA...").
  2. Updates .gitignore to ensure .env files are never tracked or pushed to Git remotes.
  3. Rewrites Python source code using compiler-grade AST replacement, swapping literal strings with os.getenv("VAR_NAME", "").
  4. Ensures import os is injected cleanly at the top of the file without disturbing module docstrings or shebangs.
  5. Verifies syntax integrity using ast.parse prior to writing changes to disk.

3. Zero-Latency Local AI Security Proxy (aegisgate serve)

Launch the local reverse proxy to intercept and sanitize outgoing prompts in real time:

# Start proxy on localhost:8080 forwarding to OpenAI with deterministic masking
aegisgate serve --host 127.0.0.1 --port 8080 --upstream https://api.openai.com --mode mask

Audit Headers Injected into Every Response:

  • X-AegisGate-Action: MASKED (or PASSED / BLOCKED)
  • X-AegisGate-Secrets-Count: 2

4. Git Pre-Commit Gatekeeper (aegisgate init-hook & check-diff)

Prevent accidental commits of hardcoded keys to Git repositories:

# Install automated Git pre-commit hook into .git/hooks/pre-commit
aegisgate init-hook

# Manually verify currently staged git diff
aegisgate check-diff

🔌 Connecting to Cursor & Claude Code

Route your AI coding assistant through AegisGate to scrub credentials on the fly without changing your workflow:

In Cursor / VSCode AI Settings:

  1. Open Cursor Settings -> Models -> OpenAI API Key / Base URL.
  2. Set OpenAI Base URL to:
    http://localhost:8080/v1
    
  3. Set your API Key as usual (AegisGate preserves your credentials for upstream forwarding while stripping secrets embedded in code snippets and prompt bodies).

In Python / OpenAI SDK Applications:

from openai import OpenAI

# Drop-in replacement pointing to AegisGate local firewall
client = OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="your-api-key"
)

# If this code snippet contains leaked credentials, AegisGate masks them before transit!
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Help me debug this AWS client: AWS_ACCESS_KEY_ID = 'AKIAIOSFODNN7EXAMPLE'"}
    ]
)

🛡️ Anti-Corruption Structural Integrity Guarantee

A common flaw in naive regex scrubbing tools is that replacing text breaks string literals or creates malformed JSON, crashing downstream LLMs.

AegisGate enforces a strict Structural Integrity Invariant:

  • After redaction, JSON payloads are verified with json.loads, and Python code snippets are verified with ast.parse.
  • If a redaction operation would corrupt payload syntax or create invalid code, AegisGate triggers an IntegrityCorruptionError and returns a hard BLOCK verdict (HTTP 400 or Exit Code 1) rather than forwarding damaged data.

⚙️ Configuration Reference (.aegisgate.yml)

# Minimum Shannon entropy (bits per character) to flag candidate secrets
entropy_threshold: 4.2

# Minimum token length to trigger Shannon entropy scanning
min_token_length: 16

# Security action mode: 'mask' (deterministic redaction) or 'block' (reject request/commit)
mode: "mask"

# Invariant: Strictly verify structural integrity (JSON/Python AST) post-redaction
enforce_integrity: true

# Regex patterns that should never trigger alerts
allowlist_patterns:
  - "^AIzaSy_MOCK_.*$"
  - "^sk-mock-.*$"
  - "^placeholder.*$"
  - "^example.*$"
  - "^localhost.*$"
  - "^0\\.0\\.0\\.0$"
  - "^127\\.0\\.0\\.1$"
  - "^\\[REDACTED_.*\\]$"
  - "^MOCK_TEST_KEY.*$"
  - "^FAKE_API_KEY.*$"

# Path globs exempt from pre-commit blocking
allowlist_paths:
  - "tests/*"
  - "test_*"
  - "*.lock"
  - "package-lock.json"
  - "*.md"

# OpenAI-compatible Proxy Server Configuration
proxy_upstream_url: "https://api.openai.com"
proxy_host: "127.0.0.1"
proxy_port: 8080

🧪 Automated Test Suite (30 / 30 Passing)

PYTHONPATH=. pytest tests/ -v
============================= test session starts ==============================
platform darwin -- Python 3.13.13, pytest-9.1.1, pluggy-1.6.0
rootdir: /Users/chundurisushen/.gemini/antigravity/scratch/aegisgate
configfile: pyproject.toml
plugins: asyncio-1.4.0, anyio-4.14.2
collected 30 items

tests/test_agent.py::test_plan_code_extracts_secrets_and_injects_import_os PASSED [  3%]
tests/test_agent.py::test_ensure_import_os_preserves_module_docstring PASSED [  6%]
tests/test_agent.py::test_planner_derives_unique_environment_names PASSED [ 10%]
tests/test_agent.py::test_autonomous_remediation_e2e_on_disk PASSED      [ 13%]
tests/test_agent.py::test_ensure_import_os_preserves_future_imports_order PASSED [ 16%]
tests/test_ast.py::test_ast_scans_variable_assignments PASSED            [ 20%]
tests/test_ast.py::test_ast_scans_dict_literals PASSED                   [ 23%]
tests/test_ast.py::test_ast_scans_function_kwargs_and_env_defaults PASSED [ 26%]
tests/test_ast.py::test_ast_scanner_gracefully_handles_invalid_python PASSED [ 30%]
tests/test_classifier.py::test_classify_known_api_keys PASSED            [ 33%]
tests/test_classifier.py::test_classify_jwt_and_bearer_auth PASSED       [ 36%]
tests/test_classifier.py::test_classify_private_key PASSED               [ 40%]
tests/test_classifier.py::test_allowlist_ignores_mock_and_uuid PASSED    [ 43%]
tests/test_classifier.py::test_classify_high_entropy_standalone_token PASSED [ 46%]
tests/test_entropy.py::test_shannon_entropy_mathematical_baselines PASSED [ 50%]
tests/test_entropy.py::test_is_high_entropy_cryptographic_vs_natural PASSED [ 53%]
tests/test_entropy.py::test_hex_hash_allowlist_heuristics PASSED         [ 56%]
tests/test_entropy.py::test_sliding_window_detects_embedded_secret PASSED [ 60%]
tests/test_precommit.py::test_inspect_clean_diff PASSED                  [ 63%]
tests/test_precommit.py::test_inspect_diff_with_hardcoded_secrets PASSED [ 66%]
tests/test_precommit.py::test_allowlist_path_exemption PASSED            [ 70%]
tests/test_precommit.py::test_hook_installation_in_temp_repo PASSED      [ 73%]
tests/test_proxy.py::test_proxy_health_endpoint PASSED                   [ 76%]
tests/test_proxy.py::test_proxy_mask_mode_redacts_outgoing_payload PASSED [ 80%]
tests/test_proxy.py::test_proxy_block_mode_rejects_leakage PASSED        [ 83%]
tests/test_proxy.py::test_proxy_clean_payload_passes_unmodified PASSED   [ 86%]
tests/test_redaction.py::test_deterministic_text_redaction PASSED        [ 90%]
tests/test_redaction.py::test_json_payload_redaction_preserves_syntax PASSED [ 93%]
tests/test_python_code_redaction_preserves_ast_integrity PASSED          [ 96%]
tests/test_redaction.py::test_anti_corruption_invariant_raises_error_on_syntax_break PASSED [100%]

============================== 30 passed in 0.10s ==============================

📄 License

Licensed under the Apache License 2.0.

About

Local-first Zero-Trust security firewall and autonomous self-healing agent for AI coding workflows.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages