""" AegisVault Cloud Portal — Self-Defending Enterprise Web Application Uses all 8 local ONNX MiniLM security specialist models in real time to protect authentication, the AI operations assistant, and log ingestion. """ from __future__ import annotations import json import secrets import sqlite3 from datetime import datetime, timezone from pathlib import Path from typing import Any from flask import Flask, jsonify, request, send_from_directory from security_engine import SecurityEngine BASE_DIR = Path(__file__).resolve().parent MODELS_ROOT = BASE_DIR.parent STATIC_DIR = BASE_DIR / "static" DB_PATH = BASE_DIR / "aegisvault.db" app = Flask(__name__, static_folder=str(STATIC_DIR), static_url_path="/static") engine: SecurityEngine | None = None def utc_now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") def get_db() -> sqlite3.Connection: conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row return conn def init_db() -> None: conn = get_db() cur = conn.cursor() cur.executescript( """ CREATE TABLE IF NOT EXISTS incidents ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL, source TEXT NOT NULL, title TEXT NOT NULL, summary TEXT NOT NULL, domain TEXT NOT NULL, severity INTEGER NOT NULL, action TEXT NOT NULL, indicators_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'OPEN', latency_ms REAL NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS audit_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL, source TEXT NOT NULL, redacted_text TEXT NOT NULL, secrets_redacted INTEGER NOT NULL DEFAULT 0, domain TEXT NOT NULL, severity INTEGER NOT NULL, action TEXT NOT NULL, indicators_json TEXT NOT NULL, iocs_json TEXT NOT NULL, latency_ms REAL NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS iocs ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL, ioc_type TEXT NOT NULL, value TEXT NOT NULL, source TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'WATCH', UNIQUE(ioc_type, value) ); CREATE TABLE IF NOT EXISTS sessions ( token TEXT PRIMARY KEY, username TEXT NOT NULL, created_at TEXT NOT NULL, telemetry TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS metrics ( key TEXT PRIMARY KEY, value INTEGER NOT NULL DEFAULT 0 ); """ ) for k in ( "total_requests_inspected", "auth_allowed", "auth_blocked", "prompts_allowed", "prompts_blocked", "secrets_redacted", "logs_ingested", ): cur.execute("INSERT OR IGNORE INTO metrics (key, value) VALUES (?, 0)", (k,)) conn.commit() conn.close() def inc_metric(conn: sqlite3.Connection, key: str, delta: int = 1) -> None: conn.execute("UPDATE metrics SET value = value + ? WHERE key = ?", (delta, key)) def save_iocs(conn: sqlite3.Connection, entities: list[dict[str, Any]], source: str, auto_block: bool = False) -> None: status = "BLOCKED" if auto_block else "WATCH" now = utc_now() for ent in entities: val = ent["text"].strip() if not val: continue conn.execute( """ INSERT INTO iocs (created_at, ioc_type, value, source, status) VALUES (?, ?, ?, ?, ?) ON CONFLICT(ioc_type, value) DO UPDATE SET status = CASE WHEN excluded.status = 'BLOCKED' THEN 'BLOCKED' ELSE iocs.status END """, (now, ent["type"], val, source, status), ) def seed_initial_events(sec: SecurityEngine) -> None: conn = get_db() count = conn.execute("SELECT COUNT(*) AS c FROM audit_logs").fetchone()["c"] if count > 0: conn.close() return samples = [ ( "gateway-log", "Approved nightly backup completed normally with verified checksums for cluster prod-eu-01.", ), ( "ci-worker", "Deployment error with OPENAI_API_KEY=sk-proj-99aabbccddeeff112233 while syncing service prod_worker.", ), ( "siem-feed", "Account svc_backup connected from 203.0.113.45 to suspicious host updates-check.example.net and dumped lsass memory.", ), ] for src, text in samples: res = sec.evaluate_log(text) now = utc_now() conn.execute( """ INSERT INTO audit_logs (created_at, source, redacted_text, secrets_redacted, domain, severity, action, indicators_json, iocs_json, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, src, res["redacted_text"], res["secrets_found"], res["domain"]["label"], res["risk_severity"]["severity_level"], res["incident_action"]["label"], json.dumps(res["alert_indicators"]["active_tags"]), json.dumps(res["iocs"]["entities"]), res["total_latency_ms"], ), ) inc_metric(conn, "total_requests_inspected", 1) inc_metric(conn, "logs_ingested", 1) if res["secrets_found"] > 0: inc_metric(conn, "secrets_redacted", res["secrets_found"]) auto_block = res["risk_severity"]["severity_level"] >= 4 save_iocs(conn, res["iocs"]["entities"], src, auto_block=auto_block) if res["risk_severity"]["severity_level"] >= 3 or res["secrets_found"] > 0: title = ( f"Leaked Secret Redacted ({src})" if res["secrets_found"] > 0 and res["risk_severity"]["severity_level"] < 4 else f"{res['domain']['label']} Threat Detected ({src})" ) conn.execute( """ INSERT INTO incidents (created_at, source, title, summary, domain, severity, action, indicators_json, status, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, src, title, res["redacted_text"], res["domain"]["label"], res["risk_severity"]["severity_level"], res["incident_action"]["label"], json.dumps(res["alert_indicators"]["active_tags"]), "CONTAINED" if res["incident_action"]["label"] in ("ISOLATE_CONTAIN", "REVOKE_CREDENTIALS") else "OPEN", res["total_latency_ms"], ), ) conn.commit() conn.close() def get_engine() -> SecurityEngine: global engine if engine is None: init_db() engine = SecurityEngine(MODELS_ROOT) seed_initial_events(engine) return engine # --- Knowledge Base for the Real Cloud Ops AI Assistant --- OPS_KB = [ ( ["backup", "snapshot", "restore", "archive"], "Nightly encrypted backups run at 02:00 UTC across prod-us-east and prod-eu-west with SHA-256 checksum verification. Use `aegis backup verify --latest` to inspect the latest snapshot integrity.", ), ( ["status", "health", "uptime", "cluster", "server", "node"], "All 4 production clusters (us-east-1, eu-west-1, ap-sg-1, edge-waf) are healthy at 99.98% 30-day uptime. Zero unpatched critical CVEs detected on managed hosts.", ), ( ["mfa", "sso", "login", "auth", "access", "password", "key", "rotate"], "Zero-Trust policy requires FIDO2/WebAuthn hardware keys or corporate SSO for all privileged accounts. Automated service key rotation runs every 30 days via Vault IAM.", ), ( ["firewall", "waf", "ioc", "block", "ip", "quarantine", "incident"], "Active SOC enforcement is enabled: high-severity IOCs (IPs, domains, compromised accounts) are automatically quarantined and routed to the Security Operations dashboard.", ), ( ["deploy", "ci", "cd", "pipeline", "release", "staging"], "Production deployments require signed commits, passing security gates, and zero secret-leak detections from `sec_log_redact_secrets`.", ), ] def generate_ops_reply(sanitized_prompt: str, secrets_redacted: int) -> str: lower = sanitized_prompt.lower() reply = None for keywords, answer in OPS_KB: if any(kw in lower for kw in keywords): reply = answer break if reply is None: reply = ( "AegisVault Ops Assistant received your verified query. All system telemetry, " "cluster health checks, IAM policies, and deployment pipelines are operating under " "Zero-Trust protection. Ask about cluster status, backups, MFA policies, deployments, or firewall rules." ) if secrets_redacted > 0: reply += f"\n\n[DLP Notice]: {secrets_redacted} sensitive credential(s) were automatically redacted from your message before logging." return reply # --- Routes --- @app.route("/") def serve_index(): return send_from_directory(str(STATIC_DIR), "index.html") @app.route("/api/status", methods=["GET"]) def api_status(): sec = get_engine() conn = get_db() metrics = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM metrics").fetchall()} open_incidents = conn.execute("SELECT COUNT(*) AS c FROM incidents WHERE status != 'RESOLVED'").fetchone()["c"] blocked_iocs = conn.execute("SELECT COUNT(*) AS c FROM iocs WHERE status = 'BLOCKED'").fetchone()["c"] total_iocs = conn.execute("SELECT COUNT(*) AS c FROM iocs").fetchone()["c"] conn.close() return jsonify( { "status": "PROTECTED", "models_loaded": len(sec.models), "load_time_ms": sec.load_time_ms, "models": sec.list_models(), "metrics": { **metrics, "open_incidents": open_incidents, "blocked_iocs": blocked_iocs, "total_iocs": total_iocs, }, } ) @app.route("/api/auth/login", methods=["POST"]) def api_auth_login(): data = request.get_json(force=True) or {} username = str(data.get("username", "")).strip() telemetry = str(data.get("telemetry", "")).strip() if not username or not telemetry: return jsonify({"error": "username and telemetry are required"}), 400 sec = get_engine() evaluation = sec.evaluate_auth(telemetry) now = utc_now() conn = get_db() inc_metric(conn, "total_requests_inspected", 1) if evaluation["blocked"]: inc_metric(conn, "auth_blocked", 1) save_iocs(conn, evaluation["iocs"]["entities"], f"auth:{username}", auto_block=True) conn.execute( """ INSERT INTO incidents (created_at, source, title, summary, domain, severity, action, indicators_json, status, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, "auth-gate", f"Blocked Anomalous Sign-In for '{username}'", telemetry, "APP_IDENTITY", evaluation["risk_severity"]["severity_level"], evaluation["incident_action"]["label"], json.dumps(evaluation["alert_indicators"]["active_tags"]), "CONTAINED", evaluation["total_latency_ms"], ), ) conn.commit() conn.close() return jsonify( { "authenticated": False, "username": username, "session_token": None, "message": f"Access denied by Zero-Trust Auth Gate. Action enforced: {evaluation['incident_action']['label']}.", "security": evaluation, } ) token = "agv_" + secrets.token_hex(16) inc_metric(conn, "auth_allowed", 1) conn.execute( "INSERT INTO sessions (token, username, created_at, telemetry) VALUES (?, ?, ?, ?)", (token, username, now, telemetry), ) conn.commit() conn.close() return jsonify( { "authenticated": True, "username": username, "session_token": token, "message": f"Welcome back, {username}. Session verified by AegisVault Zero-Trust Gate.", "security": evaluation, } ) @app.route("/api/assistant/chat", methods=["POST"]) def api_assistant_chat(): data = request.get_json(force=True) or {} prompt = str(data.get("prompt", "")).strip() username = str(data.get("username", "ops-analyst")).strip() or "ops-analyst" if not prompt: return jsonify({"error": "prompt is required"}), 400 sec = get_engine() evaluation = sec.evaluate_prompt(prompt) now = utc_now() conn = get_db() inc_metric(conn, "total_requests_inspected", 1) secrets_count = evaluation["secret_redaction"]["count"] if secrets_count > 0: inc_metric(conn, "secrets_redacted", secrets_count) if evaluation["blocked"]: inc_metric(conn, "prompts_blocked", 1) sev = evaluation["risk_severity"]["severity_level"] if evaluation["risk_severity"] else 4 conn.execute( """ INSERT INTO incidents (created_at, source, title, summary, domain, severity, action, indicators_json, status, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, "ai-firewall", f"Prompt Injection Blocked ({username})", evaluation["sanitized_prompt"], "APP_IDENTITY", max(sev, 4), "ISOLATE_CONTAIN", json.dumps(["defense_evasion"]), "CONTAINED", evaluation["total_latency_ms"], ), ) conn.commit() conn.close() return jsonify( { "allowed": False, "reply": "Request blocked by AegisVault Prompt Injection Firewall (`sec_prompt_injection_gate`). This attempt has been logged to the Security Operations Center.", "sanitized_prompt": evaluation["sanitized_prompt"], "security": evaluation, } ) inc_metric(conn, "prompts_allowed", 1) conn.commit() conn.close() reply = generate_ops_reply(evaluation["sanitized_prompt"], secrets_count) return jsonify( { "allowed": True, "reply": reply, "sanitized_prompt": evaluation["sanitized_prompt"], "security": evaluation, } ) @app.route("/api/logs/ingest", methods=["POST"]) def api_logs_ingest(): data = request.get_json(force=True) or {} source = str(data.get("source", "app-gateway")).strip() or "app-gateway" log_text = str(data.get("log_text", "")).strip() if not log_text: return jsonify({"error": "log_text is required"}), 400 sec = get_engine() res = sec.evaluate_log(log_text) now = utc_now() conn = get_db() inc_metric(conn, "total_requests_inspected", 1) inc_metric(conn, "logs_ingested", 1) if res["secrets_found"] > 0: inc_metric(conn, "secrets_redacted", res["secrets_found"]) cur = conn.execute( """ INSERT INTO audit_logs (created_at, source, redacted_text, secrets_redacted, domain, severity, action, indicators_json, iocs_json, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, source, res["redacted_text"], res["secrets_found"], res["domain"]["label"], res["risk_severity"]["severity_level"], res["incident_action"]["label"], json.dumps(res["alert_indicators"]["active_tags"]), json.dumps(res["iocs"]["entities"]), res["total_latency_ms"], ), ) log_id = cur.lastrowid auto_block = res["risk_severity"]["severity_level"] >= 4 or res["incident_action"]["label"] in ( "ISOLATE_CONTAIN", "REVOKE_CREDENTIALS", ) save_iocs(conn, res["iocs"]["entities"], source, auto_block=auto_block) incident_created = False if ( res["risk_severity"]["severity_level"] >= 3 or res["secrets_found"] > 0 or res["incident_action"]["label"] != "ALLOW_LOG" ): incident_created = True title = f"{res['domain']['label']} Alert — {res['incident_action']['label']} ({source})" if res["secrets_found"] > 0 and res["domain"]["label"] == "BENIGN": title = f"Secret Leak Redacted in {source}" conn.execute( """ INSERT INTO incidents (created_at, source, title, summary, domain, severity, action, indicators_json, status, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( now, source, title, res["redacted_text"], res["domain"]["label"], res["risk_severity"]["severity_level"], res["incident_action"]["label"], json.dumps(res["alert_indicators"]["active_tags"]), "CONTAINED" if auto_block else "OPEN", res["total_latency_ms"], ), ) conn.commit() conn.close() return jsonify( { "log_id": log_id, "incident_created": incident_created, "security": res, } ) @app.route("/api/inspect", methods=["POST"]) def api_inspect(): data = request.get_json(force=True) or {} text = str(data.get("text", "")).strip() if not text: return jsonify({"error": "text is required"}), 400 sec = get_engine() res = sec.evaluate_all(text) conn = get_db() inc_metric(conn, "total_requests_inspected", 1) conn.commit() conn.close() return jsonify(res) @app.route("/api/incidents", methods=["GET"]) def api_incidents(): conn = get_db() rows = conn.execute("SELECT * FROM incidents ORDER BY id DESC LIMIT 50").fetchall() conn.close() return jsonify( [ { "id": r["id"], "created_at": r["created_at"], "source": r["source"], "title": r["title"], "summary": r["summary"], "domain": r["domain"], "severity": r["severity"], "action": r["action"], "indicators": json.loads(r["indicators_json"]), "status": r["status"], "latency_ms": r["latency_ms"], } for r in rows ] ) @app.route("/api/incidents//status", methods=["POST"]) def api_update_incident(incident_id: int): data = request.get_json(force=True) or {} status = str(data.get("status", "")).upper() if status not in ("OPEN", "CONTAINED", "RESOLVED"): return jsonify({"error": "Invalid status"}), 400 conn = get_db() cur = conn.execute("UPDATE incidents SET status = ? WHERE id = ?", (status, incident_id)) conn.commit() conn.close() if cur.rowcount == 0: return jsonify({"error": "Incident not found"}), 404 return jsonify({"id": incident_id, "status": status}) @app.route("/api/logs", methods=["GET"]) def api_logs(): conn = get_db() rows = conn.execute("SELECT * FROM audit_logs ORDER BY id DESC LIMIT 40").fetchall() conn.close() return jsonify( [ { "id": r["id"], "created_at": r["created_at"], "source": r["source"], "redacted_text": r["redacted_text"], "secrets_redacted": r["secrets_redacted"], "domain": r["domain"], "severity": r["severity"], "action": r["action"], "indicators": json.loads(r["indicators_json"]), "iocs": json.loads(r["iocs_json"]), "latency_ms": r["latency_ms"], } for r in rows ] ) @app.route("/api/iocs", methods=["GET"]) def api_iocs(): conn = get_db() rows = conn.execute("SELECT * FROM iocs ORDER BY id DESC LIMIT 50").fetchall() conn.close() return jsonify([dict(r) for r in rows]) @app.route("/api/iocs//toggle", methods=["POST"]) def api_toggle_ioc(ioc_id: int): conn = get_db() row = conn.execute("SELECT status FROM iocs WHERE id = ?", (ioc_id,)).fetchone() if not row: conn.close() return jsonify({"error": "IOC not found"}), 404 new_status = "WATCH" if row["status"] == "BLOCKED" else "BLOCKED" conn.execute("UPDATE iocs SET status = ? WHERE id = ?", (new_status, ioc_id)) conn.commit() conn.close() return jsonify({"id": ioc_id, "status": new_status}) if __name__ == "__main__": print("Initializing AegisVault Security Engine (loading 8 ONNX models)...", flush=True) eng = get_engine() print(f"Loaded {len(eng.models)} security models in {eng.load_time_ms} ms.", flush=True) app.run(host="127.0.0.1", port=8000, debug=False, threaded=True)