AISOCin‑a‑box

Architecture Deep Dive for Developers

This is §1–§4 of the consolidated spec (docs/spec/LWL-32-architecture-spec.md) distilled to what you need to write code against. The spec is normative; this page is a map. When they disagree, the spec wins and this page has a bug.

The shape of the system

customer network                         vendor cloud
┌─────────────────────────┐   tunnel    ┌──────────────────────────────┐
│ Vector → redact → ES    │  outbound   │ Tunnel Gateway (Go/gRPC)     │
│ Edge Agent (Go)         │ ═══════════▶│  → alert ingest → cases      │
│ OPA sidecar (edge veto) │  WireGuard  │  → LangGraph orchestrator    │
│ enforcement APIs        │◀═══════════ │     + LLM router + RAG       │
│                         │  + mTLS     │  → FastAPI control-plane     │
│                         │             │  → PostgreSQL (RLS)          │
│                         │             │  → audit-chain writer        │
│                         │             │  → Next.js portal            │
└─────────────────────────┘             └──────────────────────────────┘

Import graph rule (CI-enforced): cloud apps/* never import edge/*; edge/* imports only packages/shared-schemas and itself. The Box builds with zero cloud credentials present.

The wire: TunnelFrame (§1.2.4)

One protobuf envelope on one bidirectional gRPC method (soc.tunnel.v1.TunnelStream.Session). If you add a payload, you add a oneof member — never a new service, never a new stream.

Direction Payloads
edge → cloud AlertMetadataPush, QueryResult, ContainmentReceipt, FleetHeartbeat
cloud → edge EsqlDispatch, ContainmentDirective, ConfigSync, UpdateManifest
protocol FrameAck, ErrorEnvelope

Delivery semantics you must code to:

  • At-least-once. frame_id (UUIDv7) is the dedupe key on both sides — 24 h LRU plus a persistent ledger for containment.
  • seq is per-session monotonic; a gap after a WireGuard flap means reconnect + FrameAck.last_seq resync. Undeliverable cloud dispatches sit in a per-tenant replay queue (10 k frames / 24 h max). Directives carry expires_at — the queue never resurrects an expired action.
  • Identity is the certificate, not the payload. The gateway derives tenant_id from the SPIFFE SAN (spiffe://soc.vendor/tenants/<t>/edges/<e>). The tenant_id field in the frame is informational.

Edge-side validation of cloud requests (§1.2.3, §1.2.4.b)

An edge agent must refuse, with a machine-readable QUERY_DENIED / directive rejection, unless all hold:

  1. JWS signature verifies against the pinned control-plane JWKS AND the canonical-bytes request_hash matches (no post-approval mutation).
  2. Nonce unseen (edge SQLite replay ledger, 90 d).
  3. expires_at in the future.
  4. Indices ⊆ allowed_indices ⊆ tenant allow-list expanded against the real local index catalog, not just string patterns.
  5. Query shape passes: read-only verbs, LIMIT ≤ max_rows, span ≤ 7 days, no write verbs / CHANGE POINT. (Real ES|QL grammar, vendored — regex checks are explicitly banned.)
  6. OPA edge bundle allows it. Two gates, one policy repo, different bundles: the cloud bundle permits dispatch, the edge bundle can veto it. A compromised cloud cannot make the edge do anything its own policy forbids.

Tenancy (§1.3, §4.4)

Three layers, each independently load-bearing:

  • PostgreSQL: shared schema, RLS everywhere. Every request transaction does SET LOCAL app.tenant_id = '<tnt>' before touching data; the connection role is not the table owner. The test suite asserts cross-tenant reads return ∅ — write that test before the query.
  • Elasticsearch: per-tenant index naming (logs-<namespace>.<source>-<tenant>-<date> family), tenant-scoped query users; DLS is defense-in-depth where licensed, the AST/allow-list check is the baseline fence (Basic tier).
  • Application: RBAC via OPA + view-scoped DTOs. CaseSafe vs CaseInternal are separate serializers, not one model with hidden fields. If you find yourself deleting keys from a dict before returning it, you are building the leak.

Error convention that follows from this: out-of-scope resource ⇒ 404 identical to nonexistent. Never 403 on existence probes.

Triage graph (§3)

LangGraph StateGraph over TriageState (TypedDict, total=False):

ingest_alert → hypothesis → esql_context_hunter → vector_rag_enrichment
            → verdict_attack_mapping ──(insufficient & replans<2)──▶ hypothesis
                    │ (insufficient & exhausted) ─▶ escalate_to_analyst ▶ finalize
                    ▼
              autonomy_gate ──(human needed, none on file)──▶ approval_wait
                    │                                          │ resume(approval)
                    ▼                                          ▼
              gate_finalize ──▶ auto_remediate | escalate_to_analyst ──▶ finalize_case

Invariants your node code must preserve:

  • Bounded loops: MAX_REPLANS = 2, MAX_ESQL_PER_RUN = 5, LIMIT cap 200, span ≤ 7 d. Hitting a bound forces insufficient_context; escalation, never a silent no-action close.
  • Deterministic routing: routers are pure functions of state. LLM output never picks an edge.
  • Write-before-execute: every fact (prompt, query, verdict, decision, approval, execution, receipt) lands in the hash-chained audit chain before the step that depends on it proceeds. The chain is (tenant, seq)-keyed, prev_hash-linked; the seq counter and the write share one BEGIN IMMEDIATE transaction.
  • OPA contract: a malformed decision (mode not in autonomous|human_approval|forbidden, empty/missing reasons) is an OpaError and fails closed — do not act on a decision you cannot parse. Approval validity is re-checked at resume: approving role, unexpired portal window measured on the gate clock, bound to the OPEN request_id, inside the request's policy ttl, and mfa_verified a hard boolean (D-V1).
  • All-or-nothing remediation: any forbidden action in a multi-action set escalates the whole set.

The executable reference artifacts (Rego policy, triage logic, ES|QL validator, audit chain, unit tests) live in apps/agent-orchestrator/ (Phase A moved them from spec/section-3-agentic-triage/, which is now a compat shim):

python3 apps/agent-orchestrator/src/orchestrator/tests/test_triage_logic.py -v
opa test apps/agent-orchestrator/policies/*.rego        # 18 cases

Portal & API (§4)

  • One app, one URL space, six personas, middleware gating + per-server-component re-check (defense in depth). /api/proxy/* is the BFF: it mints 60-second service JWTs (act=user) to FastAPI — the browser never holds an API token.
  • Pagination is cursor-only (?cursor=&limit≤200); long operations are 202 + JobRef with poll or SSE; nothing holds a connection across the tunnel.
  • Every mutating endpoint requires Idempotency-Key and emits an audit event atomically with its DB write (outbox pattern). trace_id propagates browser → BFF → FastAPI → gateway → box.
  • Rate-limit classes: reads 100/min, writes 20/min, assistant 10 msg/min, ES|QL 6/min, plus per-tenant ceilings.
  • Tunnel-down on a tunnel-dependent op ⇒ 502 GW_TUNNEL_DOWN, retryable, Retry-After reflects the heartbeat budget.

Monorepo orientation (§5)

Path Plane Notes
proto/soc/tunnel/v1/ contract the wire; buf breaking-change CI gate
packages/shared-schemas/ contract pydantic v2 + zod from one JSON-Schema source
apps/portal/ cloud Next.js 15 App Router
apps/control-plane-api/ cloud FastAPI, deps/rls.py sets tenant scope
apps/agent-orchestrator/ cloud LangGraph; nodes named in §3.2.1
apps/tunnel-gateway/ cloud Go; session registry, replay, SAN→tenant
edge/edge-agent/ box Go; tunnel supervisor, containment adapters
edge/policies/ box OPA bundles (second-line veto)
apps/agent-orchestrator/ verified artifacts §3 executable spec (canonical home since Phase A)
spec/section-3-agentic-triage/ compat shim historic paths re-export the artifacts above
deploy/compose/ reference stack Phase-0; loopback-only + tailscale serve

Where things are enforced (cheat sheet)

Claim in the marketing site The code that makes it true
"raw logs never leave the box" §2.1 Vector sinks: only agent_alerts (metadata) crosses; port-scan/egress gate is G1
"zero inbound ports" WireGuard is edge-dial-out (§1.2.1); nothing listens on the box's customer-facing NIC
"AI cannot act alone" hitl_guardrails.rego + autonomy_gate/approval_wait/gate_finalize trio
"approvals are provable" audit_chain.py hash chain + hitl_approvals RLS rows + mfa_verified (D-V1)
"one tenant can't see another" PG RLS + ES per-tenant indices + separate Safe/Internal serializers