Skip to content

Architecture and Tarpit Mechanics

Evan Newman edited this page Nov 30, 2026 · 1 revision

Architecture and tarpit mechanics

MirageGate sits as an inbound Layer 7 HTTP reverse proxy (server.proxy_listen, default :8080) in front of your real application API (server.upstream), isolating legitimate traffic while routing provably adversarial probes into a zero-LLM procedural labyrinth.


Five-stage request pipeline (internal/proxy/proxy.go)

  1. Stage 0 — Hard Bypass Path Guard:
    • Evaluates gate.IsBypassPath(r) before any watermark inspection or session lookup.
    • Paths matching gate.bypass_paths (default /healthz, /readyz, /metrics, /static/) go directly to upstream—strictly rejecting traversal sequences (.., \, %2f, %5c, %2e in Path/RawPath) so attackers cannot smuggle canary routes past bypass prefixes.
  2. Stage 1 — Pre-Gate Breadcrumb Inspector (~2 µs):
    • Resolves clientIP := gate.ClientIP(r) (ignoring X-Forwarded-For / X-Real-IP unless r.RemoteAddr is inside server.trusted_proxies, walking XFF right-to-left).
    • Scans Authorization, X-API-Key, X-Tenant-Scope, r.URL.Path, and query parameters cursor, page_token, api_key, token, scope.
    • Groups valid breadcrumbs by SessionID (KindHoneyJWT > KindAPIKey > KindShadowRoute > KindTenantScope > KindCursor), triggers CheckAndRecordHandoff per distinct session, and routes into serveMirage under the primary session with FlagBreadcrumbReuse.
  3. Stage 2 — Safe Activation Gate (internal/gate/gate.go):
    • Enforces full bypasses (bypass_paths, bypass_cidrs, constant-time bypass_header / bypass_header_value scoped to trusted_proxies) before any adversarial trigger.
    • Peeks up to 16 KiB of non-GET/HEAD request bodies only when detect_graphql_introspection is enabled and gate.IsGraphQLPath(r) matches, restoring r.Body transparently via io.MultiReader.
    • Evaluates 5 deterministic triggers plus active-session continuation (details below).
  4. Stage 3 — Upstream Passthrough vs. Procedural Labyrinth:
    • Clean (ActionPass / ActionBypass): Proxied via httputil.ReverseProxy (ResponseHeaderTimeout: 30s). Strips bypass_header and waf_shunt_header before forwarding upstream, preserves X-Forwarded-For only for trusted_proxies, and returns 502 Bad Gateway JSON on upstream errors. For ActionPass, statusCaptureWriter (implementing Unwrap() for Flusher/Hijacker) feeds 401/403/404 responses to gate.ObserveUpstreamStatus.
    • Adversarial (ActionMirage): Reserves a monotonic turn number (store.ReserveTurn), synthesizes the deterministic JSON response (labyrinth.Synthesize), measures defender CPU nanoseconds (min 1000ns), updates session economics, waits res.SimulatedDelay (cancellable on r.Context().Done()), and writes the response.
  5. Stage 4 — Economics, Attribution & Reporting:
    • Updates bounded in-memory session.Store, emits ECS v8.11.0 JSONL handoff alerts + structured slog warnings via OnHandoffAlert hooks, and exposes live state over the loopback Admin Web Console.

Safe Activation Gate triggers (internal/gate/gate.go)

Evaluated in strict priority order after Tier 0 hard bypasses:

Priority Trigger (TriggerFlags) Exact matching criteria
1 waf_shunt (1<<3) Opt-in when both waf_shunt_header and waf_shunt_value are non-empty; enforces trusted_proxies when configured; constant-time comparison (subtle.ConstantTimeCompare).
2 canary_route (1<<0) Case-insensitive match on cleaned path (backslashes normalized to /, semicolon matrix params stripped) against canary_routes (exact, /subpath, or .ext suffix such as /.env.local).
3 tampered_jwt (1<<1) Inspects all Authorization: Bearer headers. Flags missing signature segments (2-part JWT header), malformed Base64URL/JSON on JWT-like tokens, missing/empty/alg: "none", invalid/empty signature, or unexpected 4-part JWTs. Well-formed signed JWTs (even expired) and opaque non-JWT bearer tokens pass cleanly.
4 graphql_introspection (1<<2) Strictly scoped to graphql_paths (/graphql, /gql, /api/graphql). Inspects query string, JSON-decoded {"query": ...} (catching unicode escapes like \u005f\u005fschema), and raw body preview for exact identifier-bounded __schema or __type (__typename never false-positives).
5 active_session Continuation of an unexpired active mirage session (session_ttl_minutes, default 120m).
6 idor_velocity (1<<4) Sliding-window counter keyed by (clientIP, clamped UA <= 256B) firing after idor_velocity_threshold (default 6) distinct ID-like paths return upstream 401/403/404 within idor_window_seconds (default 30s).

ID-like path detection (isIDLikePath) ignores version segments (v1/V2) and matches numeric IDs, 36-char UUIDs, >=16-char hex strings, prefix_id/prefix-id tokens containing digits, and >=8-char mixed alphanumerics with >=2 digits. Buckets are capped at 4096 (maxIDORBuckets) with oldest-10% eviction.


Deterministic OpenAPI-shaped near-miss labyrinth (internal/labyrinth/labyrinth.go)

Every mirage response is seeded via HMAC-SHA256(K_labyrinth, sessionID || method || cleanedPath || rawQuery || canonicalHeaderShape) into math/rand/v2 ChaCha8 using a fixed synthetic epoch (2026-06-15T12:00:00Z), guaranteeing byte-for-byte determinism for repeated requests without storing generated payloads.

Every response emits realistic JSON with X-Request-Id: req_<24-hex>, Cache-Control: no-store, zero MirageGate banners, and zero prompt injections:

Depth Entry condition Status & behavior Minted breadcrumbs
0 Initial non-shadow adversarial probe 401 (legacy_token_unsupported), 422 (introspection_relocated), or 410 (endpoint_migrated) with realistic migration hints referencing OpenAPI resources shadow_route (/v2-internal/ops-<tok>)
1 Hits /v2-internal/... without X-Tenant-Scope or ?cursor= 422 Unprocessable Entity (validation_failed) showing expected X-Tenant-Scope format and OpenAPI ?resource=<res>&limit=<N> tenant_scope (org_<tok>)
2 Hits shadow route with X-Tenant-Scope or ?cursor= 200 OK paginated catalog with RecordsPerPage OpenAPI-schema-shaped records (typed realistic values for IDs, regions, tiers, amounts, digests, 10.x IPs) + has_more: true cursor (cur_<tok>) + shadow_route (/v2-internal/auth/exchange-<tok>)
3 Hits /v2-internal/auth/exchange... 200 OK OAuth-style credential exchange payload (expires_in: 14400, staging readonly exporter scope) honey_jwt (HS256), api_key (mg_live_<tok>), and shadow_route (/v2-internal/vault/export-<tok>)
4+ Hits /v2-internal/vault/export... or presents honey_jwt / api_key 200 OK staging vault export with 8..10 OpenAPI-shaped shards + checksum_manifest (chunk_sha256, merkle_root) + has_more: true; every 7th turn after turn 6 (turn > 6 && turn % 7 == 0) returns 429 Too Many Requests (Retry-After: 1) cursor (cur_<tok> / resume_cursor), depth increments up to max_depth

Simulated latency is drawn deterministically from [min_latency_ms, max_latency_ms] (default 8–35 ms) and slept in the proxy handler with request-context cancellation.


Cost-asymmetry economics & memory bounds (internal/session/store.go)

MirageGate directly measures defender CPU nanoseconds per synthesized turn (DefenderComputeUSD priced at $0.05/vCPU-hr; DefenderLLMUSD = $0.00) and models quadratic attacker context-window burn:

  • Per-turn input tokens: min(attacker_context_cap_tokens, context_tokens + 80 + len(path)/4) (initial 1800, cap 128000).
  • Per-turn output tokens: attacker_reasoning_tokens_per_turn (default 420).
  • Context growth after each response: context_tokens = min(cap, context_tokens + 80 + turnOut + ceil(responseBytes / 4)).
  • Attacker USD estimate: (CumulativeInputTokens / 1e6) * $3.00 + (CumulativeOutputTokens / 1e6) * $15.00 (configurable for any model tier).
  • CostAsymmetryMultiplier = EstimatedAttackerUSD / DefenderComputeUSD.

Memory caps: maxActiveSessions = 4096 (expired pruned first, then oldest 10% by LastSeen), maxAlertsInMemory = 1000, Transcript capped at 250 turns/session (omitted from /api/snapshot), recentEvents capped at telemetry.max_events_in_memory (50..20000, default 2000).