Repository navigation
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.
-
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,%2einPath/RawPath) so attackers cannot smuggle canary routes past bypass prefixes.
- Evaluates
-
Stage 1 — Pre-Gate Breadcrumb Inspector (
~2 µs):- Resolves
clientIP := gate.ClientIP(r)(ignoringX-Forwarded-For/X-Real-IPunlessr.RemoteAddris insideserver.trusted_proxies, walking XFF right-to-left). - Scans
Authorization,X-API-Key,X-Tenant-Scope,r.URL.Path, and query parameterscursor,page_token,api_key,token,scope. - Groups valid breadcrumbs by
SessionID(KindHoneyJWT > KindAPIKey > KindShadowRoute > KindTenantScope > KindCursor), triggersCheckAndRecordHandoffper distinct session, and routes intoserveMirageunder the primary session withFlagBreadcrumbReuse.
- Resolves
-
Stage 2 — Safe Activation Gate (
internal/gate/gate.go):- Enforces full bypasses (
bypass_paths,bypass_cidrs, constant-timebypass_header/bypass_header_valuescoped totrusted_proxies) before any adversarial trigger. - Peeks up to
16 KiBof non-GET/HEAD request bodies only whendetect_graphql_introspectionis enabled andgate.IsGraphQLPath(r)matches, restoringr.Bodytransparently viaio.MultiReader. - Evaluates 5 deterministic triggers plus active-session continuation (details below).
- Enforces full bypasses (
-
Stage 3 — Upstream Passthrough vs. Procedural Labyrinth:
-
Clean (
ActionPass/ActionBypass): Proxied viahttputil.ReverseProxy(ResponseHeaderTimeout: 30s). Stripsbypass_headerandwaf_shunt_headerbefore forwarding upstream, preservesX-Forwarded-Foronly fortrusted_proxies, and returns502 Bad GatewayJSON on upstream errors. ForActionPass,statusCaptureWriter(implementingUnwrap()forFlusher/Hijacker) feeds401/403/404responses togate.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, waitsres.SimulatedDelay(cancellable onr.Context().Done()), and writes the response.
-
Clean (
-
Stage 4 — Economics, Attribution & Reporting:
- Updates bounded in-memory
session.Store, emitsECS v8.11.0JSONL handoff alerts + structuredslogwarnings viaOnHandoffAlerthooks, and exposes live state over the loopback Admin Web Console.
- Updates bounded in-memory
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.
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.
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)(initial1800, cap128000). - Per-turn output tokens:
attacker_reasoning_tokens_per_turn(default420). - 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).