diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index ab7176616e..11abfd19c6 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -1548,9 +1548,14 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { input != nil && len(messages) == 0, policy, allowedProviderSerials) { return } - // Reject remote/non-data: media URLs pre-dispatch (the provider VLM path is - // data:-only): one clean 400 instead of dispatching and 400ing across the fleet. - if s.rejectRemoteMediaURLs(w, r, parsed, model, publicModel, requiresVision, hasTools) { + // Remote media URL gate (phase 1, pre-billing). With the media resolver + // enabled (default), remote http(s) image_url/video_url links are fetched + // and inlined as data: URIs AFTER the balance reservation (resolveRemoteMedia + // below); here we fail fast only the cases that must never fetch: sealed + // requests, remote refs in shapes the resolver doesn't handle, and the + // resolver-disabled fallback (the legacy one-clean-400, the provider VLM + // path being data:-only). + if s.gateRemoteMediaPreDispatch(w, r, parsed, model, publicModel, requiresVision, hasTools) { return } @@ -1724,17 +1729,49 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { return } - // Shared routing/capacity admission preflight (self-route / prefer / public - // capacity+TTFT gate — see runInferenceAdmission). On the chat path an alias - // fallback must refresh the threaded rawBody: re-lowering Responses input→chat - // when applicable, which can itself fail with a 400. Thread that as the - // onModelFallback callback; resolvedModel uses the new build to match the - // pre-extraction behavior. - onModelFallback := func(newModel string) bool { - rawBody, _ = marshalForwardBody(parsed) + // Resolve remote http(s) image_url/video_url links into inline base64 data: + // URIs (phase 2 — see media_resolve.go) — AFTER token admission, the balance + // reservation, and the catalog check, so network I/O is gated behind the + // cost gates: an authenticated but unfunded/over-quota request (or one for a + // nonexistent model) can never drive coordinator-side fetches. The token & + // routing estimates above count media parts flatly (300/1500 per part), so + // they don't need the inlined bytes. The billing reservation is refunded on + // any failure, and topped up below on success — it was taken while the media + // was still a ~100-byte URL. parsed is mutated in place, so every view + // derived from the pre-inline body is refreshed via refreshForwardBody. + var mediaInlined bool + rawBody, mediaInlined, ok = s.resolveRemoteMedia(w, r, rawBody, parsed, timing, mediaResolveMeta{ + model: model, + publicModel: publicModel, + stream: stream, + estimatedPromptTokens: estimatedPromptTokens, + requestedMaxTokens: requestedMaxTokens, + hasTools: hasTools, + requiresVision: requiresVision, + selfRoute: policy.enabled, + ownerAccountID: policy.ownerAccountID, + traits: routingTraits, + }) + if !ok { + refundReservation() + // Token-rate admission is intentionally NOT refunded: this matches every + // other post-admission validation failure and makes blocked/invalid URL + // probes consume the caller's input/output token quota. + return + } + + // refreshForwardBody re-derives every view of the provider-bound request from + // a freshly marshaled `parsed`: the threaded rawBody, the body actually + // forwarded to the provider (re-lowered input→chat on the Responses surface, + // which can itself fail with a 400), and the routing traits computed from it. + // Any in-place mutation of `parsed` MUST go through it — an alias fallback + // rewriting the model, or remote media being inlined as data: URIs. Returns + // false after writing a terminal response. + refreshForwardBody := func(body []byte, forModel string) bool { + rawBody = body if !isResponsesAPI { providerBody = rawBody - routingTraits = routingTraitsForModel(newModel) + routingTraits = routingTraitsForModel(forModel) return true } var err error @@ -1749,7 +1786,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { keyID: keyIDFromContext(r.Context()), consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), requestedModel: publicModel, - resolvedModel: newModel, + resolvedModel: forModel, stream: stream, estimatedPromptTokens: estimatedPromptTokens, requestedMaxTokens: requestedMaxTokens, @@ -1760,9 +1797,52 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error())) return false } - routingTraits = routingTraitsForModel(newModel) + routingTraits = routingTraitsForModel(forModel) return true } + + // Remote media was fetched and inlined into `parsed` above, so `providerBody` + // (captured before the resolve) and the routing traits derived from it now + // describe a body that no longer exists. Without this refresh the coordinator + // pays for the fetch and then seals and dispatches the ORIGINAL body still + // carrying the http(s) URL, which the provider's data:-only guard rejects. + if mediaInlined { + if !refreshForwardBody(rawBody, model) { + return + } + // The reservation was taken against a body where the image was a short + // URL, so estimateBillingPromptTokens — the guaranteed len(bytes) >= tokens + // upper bound the settlement path relies on — was computed over ~100 bytes + // of URL instead of the inlined media. Re-reserve against the real body + // before dispatch; otherwise settlement's 2x-reservation overage clamp + // silently absorbs the difference and underpays the provider. + var topUpHandled bool + reservedMicroUSD, topUpHandled = s.topUpReservationForInlinedMedia(w, r, parsed, balanceReservationParams{ + model: model, + publicModel: publicModel, + billingPromptTokens: estimateBillingPromptTokens(parsed), + estimatedPromptTokens: estimatedPromptTokens, + requestedMaxTokens: requestedMaxTokens, + stream: stream, + requiresVision: requiresVision, + hasTools: hasTools, + policy: policy, + }, reservedMicroUSD) + if topUpHandled { + refundReservation() + return + } + } + + // Shared routing/capacity admission preflight (self-route / prefer / public + // capacity+TTFT gate — see runInferenceAdmission). On the chat path an alias + // fallback must refresh the threaded rawBody; thread that as the + // onModelFallback callback. resolvedModel uses the new build to match the + // pre-extraction behavior. + onModelFallback := func(newModel string) bool { + body, _ := marshalForwardBody(parsed) + return refreshForwardBody(body, newModel) + } var preflightHandled bool model, preflightHandled = s.runInferenceAdmission(w, r, parsed, inferenceAdmissionParams{ model: model, diff --git a/coordinator/api/consumer_media_url_test.go b/coordinator/api/consumer_media_url_test.go index e2c7e3f4fe..a9a9c88a23 100644 --- a/coordinator/api/consumer_media_url_test.go +++ b/coordinator/api/consumer_media_url_test.go @@ -1,6 +1,12 @@ package api -import "testing" +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "unicode/utf8" +) // C4: media parts carrying a remote/non-data: URL must be detected so the // coordinator can reject them pre-dispatch (the provider VLM path is data:-only). @@ -64,20 +70,61 @@ func TestValidateMediaParts_RejectsRemote(t *testing.T) { } } -func TestVisionRejectRemoteEnabled_KillSwitch(t *testing.T) { - if !visionRejectRemoteEnabled() { - t.Error("default (unset) must be ON") +// TestRejectRemoteMediaURLsIsUnconditional pins the gate as unconditional on +// every surface. The generic (completions + Anthropic) surface never fetches, +// so forwarding a remote URL there can only end in a provider-side 400 — the +// retired DARKBLOOM_VISION_REJECT_REMOTE_URLS switch must never re-enable it. +func TestRejectRemoteMediaURLsIsUnconditional(t *testing.T) { + s := &Server{logger: quietLogger()} + remotePart := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/x.png"}} + remote := map[string]any{"messages": []any{msg([]any{remotePart})}} + + // The retired flag is read nowhere: no value of it may disable the gate. + for _, flag := range []string{"", "false", "0", "true"} { + t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", flag) + w := httptest.NewRecorder() + if !s.rejectRemoteMediaURLs(w, plainReq(), remote, "test", "test", true, false) { + t.Fatalf("flag=%q: a remote media URL must always be rejected pre-dispatch", flag) + } + if w.Code != http.StatusBadRequest { + t.Errorf("flag=%q: status = %d, want 400", flag, w.Code) + } } - t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "false") - if visionRejectRemoteEnabled() { - t.Error("=false must disable") + + // Unconditional on the flag, still conditional on the request: non-vision + // bodies and inline data: URIs pass untouched. + if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), remote, "test", "test", false, false) { + t.Error("non-vision requests must never be gated") } - t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "0") - if visionRejectRemoteEnabled() { - t.Error("=0 must disable") + inline := map[string]any{"messages": []any{msg([]any{ + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}}, + })}} + if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), inline, "test", "test", true, false) { + t.Error("inline data: URI must pass") } - t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "true") - if !visionRejectRemoteEnabled() { - t.Error("=true must enable") +} + +func TestTruncateMediaRef(t *testing.T) { + // "é" is 2 bytes; placed at offset 199 it straddles the 200-byte cut, so a + // naive ref[:200] ends on a partial rune that encoding/json renders U+FFFD. + straddling := strings.Repeat("a", 199) + "é" + strings.Repeat("b", 50) + cases := []struct { + name string + ref string + want string + }{ + {"short ref verbatim", "https://example.com/a.png", "https://example.com/a.png"}, + {"exactly at the cap verbatim", strings.Repeat("a", 200), strings.Repeat("a", 200)}, + {"ascii over the cap", strings.Repeat("a", 201), strings.Repeat("a", 200) + "…"}, + {"multibyte rune straddling the cut is dropped", straddling, strings.Repeat("a", 199) + "…"}, + } + for _, c := range cases { + got := truncateMediaRef(c.ref) + if got != c.want { + t.Errorf("%s: truncateMediaRef() = %q, want %q", c.name, got, c.want) + } + if !utf8.ValidString(got) { + t.Errorf("%s: truncateMediaRef() emitted invalid UTF-8: %q", c.name, got) + } } } diff --git a/coordinator/api/dispatch.go b/coordinator/api/dispatch.go index 4374b65136..25082a4e55 100644 --- a/coordinator/api/dispatch.go +++ b/coordinator/api/dispatch.go @@ -468,7 +468,15 @@ func applyTimingDecomposition(out *store.InferenceRouteOutcome, t *registry.Requ } out.ParseMs = timingMsBetween(t.ReceivedAt, t.ParsedAt) out.ReserveMs = timingMsBetween(t.ParsedAt, t.ReservedAt) - out.RouteMs = timingMsBetween(t.ReservedAt, t.RoutedAt) + // Remote-media fetch (when it happened) sits between ReservedAt and + // RoutedAt; anchor the route segment past it so a multi-second download + // doesn't masquerade as routing latency. The fetch duration itself is + // reported via the X-Timing header and DD histogram (no outcome column). + routeAnchor := t.ReservedAt + if !t.MediaFetchedAt.IsZero() { + routeAnchor = t.MediaFetchedAt + } + out.RouteMs = timingMsBetween(routeAnchor, t.RoutedAt) out.EncryptMs = timingMsBetween(t.RoutedAt, t.EncryptedAt) out.QueueWaitMs = timingMsBetween(t.QueuedAt, t.DispatchedAt) out.DispatchMs = timingMsBetween(t.DispatchedAt, firstChunk) @@ -2882,13 +2890,17 @@ func (d *dispatchState) writeCommittedResponse() { // Latency decomposition header for observability. if timing := pr.Timing; timing != nil { type timingJSON struct { - ParseUs int64 `json:"parse_us"` - ReserveUs int64 `json:"reserve_us"` - RouteUs int64 `json:"route_us"` - QueueUs int64 `json:"queue_us"` - EncryptUs int64 `json:"encrypt_us"` - DispatchUs int64 `json:"dispatch_us"` - ProviderUs int64 `json:"provider_us"` + ParseUs int64 `json:"parse_us"` + ReserveUs int64 `json:"reserve_us"` + // MediaFetchUs covers the post-reservation remote media download + + // inline step (media_resolve.go); omitted for the (typical) request + // that fetched nothing. + MediaFetchUs int64 `json:"media_fetch_us,omitempty"` + RouteUs int64 `json:"route_us"` + QueueUs int64 `json:"queue_us"` + EncryptUs int64 `json:"encrypt_us"` + DispatchUs int64 `json:"dispatch_us"` + ProviderUs int64 `json:"provider_us"` } tj := timingJSON{} if !timing.ParsedAt.IsZero() { @@ -2897,8 +2909,15 @@ func (d *dispatchState) writeCommittedResponse() { if !timing.ReservedAt.IsZero() && !timing.ParsedAt.IsZero() { tj.ReserveUs = timing.ReservedAt.Sub(timing.ParsedAt).Microseconds() } - if !timing.RoutedAt.IsZero() && !timing.ReservedAt.IsZero() { - tj.RouteUs = timing.RoutedAt.Sub(timing.ReservedAt).Microseconds() + // Media fetch (when present) sits between reserve and route; anchor the + // route segment past it so a download never inflates route_us. + routeAnchor := timing.ReservedAt + if !timing.MediaFetchedAt.IsZero() && !timing.ReservedAt.IsZero() { + tj.MediaFetchUs = timing.MediaFetchedAt.Sub(timing.ReservedAt).Microseconds() + routeAnchor = timing.MediaFetchedAt + } + if !timing.RoutedAt.IsZero() && !routeAnchor.IsZero() { + tj.RouteUs = timing.RoutedAt.Sub(routeAnchor).Microseconds() } if !timing.QueuedAt.IsZero() && !timing.DispatchedAt.IsZero() { tj.QueueUs = timing.DispatchedAt.Sub(timing.QueuedAt).Microseconds() diff --git a/coordinator/api/inference_admission.go b/coordinator/api/inference_admission.go index a648bf18d9..112d341ae2 100644 --- a/coordinator/api/inference_admission.go +++ b/coordinator/api/inference_admission.go @@ -58,7 +58,13 @@ func (s *Server) reserveInferenceBalance(w http.ResponseWriter, r *http.Request, return 0, false, false } consumerKey := consumerKeyFromContext(r.Context()) - reservedMicroUSD = s.reservationCost(p.model, p.billingPromptTokens, p.requestedMaxTokens) + // Normally the byte-count billing bound dominates the routing estimate. A + // remote media URL is the exception: its short URL is rewritten after this + // gate into hundreds/thousands of vision soft tokens. Reserve against the + // larger bound so a low-balance caller cannot trigger coordinator egress and + // only then fail the platform-price balance check. + reservationPromptTokens := max(p.billingPromptTokens, p.estimatedPromptTokens) + reservedMicroUSD = s.reservationCost(p.model, reservationPromptTokens, p.requestedMaxTokens) // Per-key spend cap (phase 1) — checked before the reservation so a capped // key never debits the account ledger. if msg, ok := s.checkKeySpendCap(r.Context(), reservedMicroUSD); !ok { @@ -112,6 +118,78 @@ func (s *Server) reserveInferenceBalance(w http.ResponseWriter, r *http.Request, return reservedMicroUSD, serviceReservation, false } +// topUpReservationForInlinedMedia re-reserves after remote media has been +// fetched and inlined into parsed. +// +// reserveInferenceBalance runs BEFORE the fetch (deliberately — network I/O must +// stay behind the cost gates), so for a remote media URL it reserves against a +// body where the image is ~100 bytes of URL text. That breaks the invariant the +// rest of the money path depends on: estimateBillingPromptTokens is documented +// as a guaranteed upper bound (len(bytes) >= tokens for any BPE tokenizer), and +// for an inline data: URI it is. The flat routing floor (300 image / 1500 video +// soft tokens) is NOT an upper bound — a provider samples up to 32 video frames +// at ~282 soft tokens each — and settlement clamps any overage at 2x the +// reservation as a fraud circuit-breaker, so the shortfall is silently written +// off AND the provider payout is recomputed from the clamped total. Recomputing +// the byte bound over the inlined body restores the guarantee. +// +// p.billingPromptTokens must already be recomputed from the mutated parsed. +// Returns the reservation now held (unchanged when no top-up was needed or when +// the top-up failed) and handled=true after writing a terminal response, in +// which case the caller must refund and return. +func (s *Server) topUpReservationForInlinedMedia(w http.ResponseWriter, r *http.Request, parsed map[string]any, p balanceReservationParams, currentMicroUSD int64) (reservedMicroUSD int64, handled bool) { + // Same skips as reserveInferenceBalance: self-route is free and a nil billing + // backend never reserved anything to top up. + if s.billing == nil || p.policy.enabled || currentMicroUSD <= 0 { + return currentMicroUSD, false + } + want := s.reservationCost(p.model, max(p.billingPromptTokens, p.estimatedPromptTokens), p.requestedMaxTokens) + if want <= currentMicroUSD { + return currentMicroUSD, false + } + reject := func(reasonCode, code, msg string) { + s.recordRejection(rejectionInfo{ + r: r, + stage: "balance", + reasonCode: reasonCode, + httpStatus: http.StatusPaymentRequired, + keyID: keyIDFromContext(r.Context()), + consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), + requestedModel: p.publicModel, + resolvedModel: p.model, + stream: p.stream, + estimatedPromptTokens: p.estimatedPromptTokens, + requestedMaxTokens: p.requestedMaxTokens, + requiresVision: p.requiresVision, + hasTools: p.hasTools, + params: rejectionSamplingParams(parsed), + }) + s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:rejected"}) + writeJSON(w, http.StatusPaymentRequired, errorResponse(code, msg, withCode("insufficient_quota"))) + } + // Cap check against the new TOTAL, matching reserveAdditionalForProvider. + if msg, ok := s.checkKeySpendCap(r.Context(), want); !ok { + reject("insufficient_quota", "insufficient_quota", msg) + return currentMicroUSD, true + } + consumerKey := consumerKeyFromContext(r.Context()) + // Charge only the delta; reserveInitialBalance re-derives the same + // service-vs-ledger mode for this account, so the hold stays consistent. + if _, err := s.reserveInitialBalance(consumerKey, p.model, want-currentMicroUSD); err != nil { + if errors.Is(err, store.ErrInsufficientBalance) { + reject("insufficient_funds", "insufficient_funds", + "your balance is too low for this request once the linked media is included — add funds at /billing, use smaller media, or lower max_tokens") + } else { + s.logger.Error("media reservation top-up failed (DB error)", "consumer_key", consumerKey, "error", err) + s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:error"}) + s.writeServiceUnavailable(w, p.model) + } + return currentMicroUSD, true + } + s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:reserved"}) + return want, false +} + // inferenceAdmissionParams bundles the per-request inputs the shared routing // preflight needs. model is the resolved build id; the preflight may swap it to // a Previous build via an alias fallback and returns the final value. diff --git a/coordinator/api/media_dispatch_body_test.go b/coordinator/api/media_dispatch_body_test.go new file mode 100644 index 0000000000..5e9e82d897 --- /dev/null +++ b/coordinator/api/media_dispatch_body_test.go @@ -0,0 +1,178 @@ +package api + +// Regression tests for the two contracts that bind remote-media inlining to the +// rest of the request lifecycle: the body actually handed to a provider, and the +// balance reservation held while that body is in flight. Both were previously +// unpinned — every media test asserted only that the origin was hit and that the +// response was not a media-gate 4xx, which a request that fetched the image and +// then dispatched the original URL passes. + +import ( + "bytes" + "context" + "encoding/json" + "image" + "image/color" + "image/png" + "math/rand/v2" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/mediafetch" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// noisyPNG returns an incompressible 256x256 PNG (~200 KB). Real bytes matter +// here: the billing bound is a byte count, so a 2x2 fixture cannot distinguish +// "reserved against the URL" from "reserved against the inlined media". +func noisyPNG(t *testing.T) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, 256, 256)) + rnd := rand.New(rand.NewPCG(1, 2)) + for y := range 256 { + for x := range 256 { + img.Set(x, y, color.RGBA{uint8(rnd.IntN(256)), uint8(rnd.IntN(256)), uint8(rnd.IntN(256)), 255}) + } + } + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatalf("encode png: %v", err) + } + return buf.Bytes() +} + +func loopbackMediaConfig() mediafetch.Config { + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true // httptest origins are loopback + cfg.AllowNonStandardPorts = true + return cfg +} + +// TestChatCompletionsDispatchesInlinedMediaBody is the end-to-end contract: what +// the PROVIDER receives must be the inlined data: URI, never the http(s) URL the +// consumer sent. The coordinator is the only component allowed to fetch, so a +// dispatched URL means the fetch was paid for and thrown away and the provider's +// data:-only guard will reject the request — the exact failure this feature +// exists to remove. +func TestChatCompletionsDispatchesInlinedMediaBody(t *testing.T) { + t.Setenv("EIGENINFERENCE_MEDIA_FETCH_ALLOW_PRIVATE_IPS", "true") + t.Setenv("EIGENINFERENCE_MEDIA_FETCH_ALLOW_NONSTANDARD_PORTS", "true") + + reg, _, ts := setupFailoverServer(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + const model = "media-inline-dispatch-model" + fp := startFailoverProvider(t, ctx, ts, reg, failoverProviderConfig{ + Name: "vision-inline", + Version: "0.7.6", + DecodeTPS: 200, + Models: []failoverModelSpec{{ID: model}}, + Script: func(ctx context.Context, fp *failoverProvider, req protocol.InferenceRequestMessage, body []byte) { + fp.serveFull(ctx, req, model, "ok") + }, + }) + p := reg.GetProvider(fp.registryID) + if p == nil { + t.Fatal("provider missing from registry after registration") + } + p.Mu().Lock() + for i := range p.Models { + if p.Models[i].ID == model { + p.Models[i].IsVision = true + } + } + p.Mu().Unlock() + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + imageURL := media.URL + "/cat.png" + + body := `{"model":"` + model + `","max_tokens":16,"messages":[{"role":"user","content":[` + + `{"type":"text","text":"describe"},` + + `{"type":"image_url","image_url":{"url":"` + imageURL + `"}}]}]}` + + status, respBody, err := postChat(ctx, ts.URL, "test-key", body) + if err != nil { + t.Fatalf("postChat: %v", err) + } + if n := atomic.LoadInt32(&hits); n != 1 { + t.Fatalf("origin hit %d time(s), want exactly 1; status=%d body=%.200s", n, status, respBody) + } + + select { + case got := <-fp.bodies: + if got == nil { + t.Fatal("provider could not decrypt the dispatched body") + } + if s := string(got); !strings.Contains(s, "data:image/png;base64,") { + t.Errorf("dispatched body carries no inlined data: URI:\n%.400s", s) + } else if strings.Contains(s, imageURL) { + t.Errorf("dispatched body still carries the remote URL %q:\n%.400s", imageURL, s) + } + case <-time.After(10 * time.Second): + t.Fatalf("provider never received an inference request (status=%d body=%.300s)", status, respBody) + } +} + +// TestChatCompletionsRemoteMediaTopsUpReservationAfterInlining pins the billing +// invariant across the fetch. estimateBillingPromptTokens is a guaranteed +// len(bytes) >= tokens upper bound, and settlement's 2x-reservation overage +// clamp relies on it — but the pre-fetch reservation sees a ~100-byte URL, not +// the media. Once inlined, the reservation must be re-taken against the real +// body; a caller funded only for the URL-shaped request must be rejected with +// its money returned, not served on a reservation that silently underpays the +// provider at settlement. +func TestChatCompletionsRemoteMediaTopsUpReservationAfterInlining(t *testing.T) { + srv, st := testBillingServer(t) + makeVisionRoutableProvider(t, srv.registry, "vision-topup", "test") + srv.mediaResolver = mediafetch.NewResolver(loopbackMediaConfig(), srv.logger) + // Non-zero input price so the prompt-token delta shows up in the reservation. + if err := st.SetModelPrice("platform", "test", 1_000_000, 0); err != nil { + t.Fatal(err) + } + + var hits int32 + img := noisyPNG(t) + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(img) + })) + defer media.Close() + + _, parsed := chatBodyBytes(t, media.URL+"/noise.png") + parsed["max_tokens"] = 1 + body, err := json.Marshal(parsed) + if err != nil { + t.Fatal(err) + } + + // Fund exactly the pre-fetch reservation: enough to clear the balance gate + // and drive the fetch, nowhere near the inlined body's byte bound. + preFetch := srv.reservationCost("test", max(estimateBillingPromptTokens(parsed), estimatePromptTokens(parsed)), 1) + if err := st.Credit(testConsumerID, preFetch, store.LedgerDeposit, "media-topup-floor"); err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402 (reservation must be re-taken against the inlined body); body=%s", + w.Code, w.Body.String()) + } + if n := atomic.LoadInt32(&hits); n != 1 { + t.Fatalf("origin hit %d time(s), want exactly 1 (the fetch is gated behind the pre-fetch reservation)", n) + } + if got := st.GetBalance(testConsumerID); got != preFetch { + t.Errorf("balance = %d, want %d — the reservation must be fully refunded when the top-up fails", got, preFetch) + } +} diff --git a/coordinator/api/media_resolve.go b/coordinator/api/media_resolve.go new file mode 100644 index 0000000000..21d5260856 --- /dev/null +++ b/coordinator/api/media_resolve.go @@ -0,0 +1,299 @@ +package api + +// media_resolve.go bridges the chat-completions handler to the mediafetch +// package: it turns remote http(s) image_url/video_url links into inline base64 +// data: URIs on the coordinator (the trusted SSRF chokepoint) before the body is +// E2E-encrypted to a provider, so consumers can pass links the way they do with +// OpenAI instead of pre-encoding media. The provider keeps seeing only data: +// URIs — its hardened non-data: guard is unchanged (defense in depth). +// +// Two-phase flow (both phases chat-completions-only; the generic completions + +// Anthropic surface keeps the unconditional pre-dispatch rejection): +// +// 1. gateRemoteMediaPreDispatch — BEFORE token admission/billing. Fails fast +// the cases that must never fetch: sender-sealed requests (fetching would +// generate origin-observable egress correlated with a payload the sender +// chose to seal), remote refs in shapes the resolver does not fetch +// (Anthropic source blocks, input_image — which would otherwise dispatch +// and be silently dropped by the provider, answering image-blind), and the +// resolver-disabled fallback (legacy one-clean-400). +// 2. resolveRemoteMedia — AFTER token admission and the balance reservation, +// so network I/O is gated behind the cost gates (an authenticated but +// unfunded/over-quota request can never drive coordinator-side fetches). +// The caller refunds the reservation on failure. + +import ( + "context" + "errors" + "net/http" + "time" + + "github.com/eigeninference/d-inference/coordinator/mediafetch" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// gateRemoteMediaPreDispatch is phase 1 (pre-billing) of remote media handling +// on the chat surface. handled=true => a terminal response was written and the +// caller must return. +func (s *Server) gateRemoteMediaPreDispatch(w http.ResponseWriter, r *http.Request, parsed map[string]any, model, publicModel string, requiresVision, hasTools bool) (handled bool) { + if !requiresVision { + return false + } + reject := func(msg string) bool { + s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, msg) + return true + } + scan := scanRemoteMediaRefs(parsed) + switch { + case scan.firstRemote == "": + // Inline data: URIs and text-only requests never reach the fetcher. + return false + case s.mediaResolver == nil || !s.mediaResolver.Enabled(): + // Resolver off means authoritative rollback to the data:-only contract: + // one clean pre-dispatch 400 instead of a provider-side one. Same message + // rejectRemoteMediaURLs writes on the generic surface, which never fetches. + return reject("image/video input must be an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\"); " + + "remote http(s):// and file:// media URLs are not supported on this endpoint. Got: " + truncateMediaRef(scan.firstRemote)) + case isSealedRequest(r): + // Sender-sealed requests are never fetched, whatever shape the reference + // takes: the sender opted into sealing the payload to the coordinator, and + // a fetch would leak request-correlated egress to the URL's origin. This + // keys off ANY remote reference, not just a fetchable one — telling a + // sealed caller to "send an OpenAI http(s) link instead" would be advice + // for something we will not do either. + return reject("sealed requests must send media as an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\"); " + + "remote image_url/video_url links are not fetched for sealed payloads — inline the media or disable request sealing") + case scan.firstUnfetchable != "": + // A remote reference in a shape the resolver does NOT fetch (Anthropic + // source blocks, Responses input_image parts, file:// and other schemes) + // keeps today's clean 400: dispatching it would either 400 across the + // fleet or be silently dropped by the provider (an image-blind answer). + return reject("this media reference is not fetchable on this endpoint; send it as an OpenAI-style image_url/video_url http(s) link " + + "or as an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\"). Got: " + truncateMediaRef(scan.firstUnfetchable)) + } + return false +} + +// remoteMediaScan answers, in one walk, the two different questions the gate +// asks about media references: is there ANY non-inline reference (sealed +// requests refuse them all), and is there one the resolver cannot fetch +// (everyone else refuses those). Deriving them from separate walks is how a +// sealed Anthropic source-URL request ended up being told to send an OpenAI +// link — advice for something a sealed request will never do either. +type remoteMediaScan struct { + // firstRemote is the first non-inline media reference of ANY shape. + firstRemote string + // firstUnfetchable is the first non-inline reference the resolver will not + // fetch, judged by the part's own shape and location rather than URL equality + // with another part. Only OpenAI image_url/video_url http(s) parts under + // messages[] are fetchable. + firstUnfetchable string +} + +// scanRemoteMediaRefs walks messages[] and input[] once. Like validateMediaParts +// it fails OPEN: a shape it cannot read is not treated as a remote reference. +func scanRemoteMediaRefs(parsed map[string]any) remoteMediaScan { + var scan remoteMediaScan + visit := func(content any, fetchableShapesAllowed bool) { + parts, isArr := content.([]any) + if !isArr { + return + } + for _, p := range parts { + pm, isMap := p.(map[string]any) + if !isMap { + continue + } + ref, isMedia := mediaPartURLString(pm) + if !isMedia || ref == "" || isInlineDataURI(ref) { + continue + } + if scan.firstRemote == "" { + scan.firstRemote = ref + } + if scan.firstUnfetchable == "" && + !(fetchableShapesAllowed && mediafetch.IsFetchableRemotePart(pm)) { + scan.firstUnfetchable = ref + } + } + } + if msgs, isArr := parsed["messages"].([]any); isArr { + for _, m := range msgs { + if mm, isMap := m.(map[string]any); isMap { + visit(mm["content"], true) + } + } + } + if input, isArr := parsed["input"].([]any); isArr { + for _, it := range input { + if im, isMap := it.(map[string]any); isMap { + visit(im["content"], false) + } + } + } + return scan +} + +// mediaResolveMeta carries the request descriptors resolveRemoteMedia needs to +// record rejection telemetry with the same fidelity as the surrounding gates, +// plus the self-route context used to gate egress on serve-ability. +type mediaResolveMeta struct { + model string + publicModel string + stream bool + estimatedPromptTokens int + requestedMaxTokens int + hasTools bool + requiresVision bool + // selfRoute (exclusive X-Darkbloom-Route: self) skips the balance + // reservation, so the monetary cost gate that otherwise precedes a fetch is + // absent. ownerAccountID is the caller's owned-provider set. resolveRemoteMedia + // confirms the owner can actually serve the request BEFORE any fetch, so a + // user with no linked/online/capable machine can't drive coordinator egress + // and only then receive the self-route-unavailable error. + // + // traits carries the FULL routing traits, not just HasTools: a constrained + // tool_choice raises RequiresToolConstraint, which providerEligibleForTraits + // enforces, so reconstructing a partial trait set here would call an owned + // provider serviceable and fetch before the real admission rejected it. The + // traits are derived from the pre-inline body; runInferenceAdmission re-checks + // with the post-inline set, which can only be stricter. + selfRoute bool + ownerAccountID string + traits registry.RequestTraits +} + +// resolveRemoteMedia is phase 2 (post-reservation): it fetches remote media +// URLs in the (already tool-schema normalized, JSON-parsed) request and inlines +// them. On success it returns the body to forward downstream — re-marshaled +// only when a URL was actually inlined — inlined=true when it was, and ok=true. +// On any failure it writes the terminal OpenAI-style error response and returns +// ok=false; the caller must refund the balance reservation and return +// immediately. +// +// parsed is mutated in place when media is inlined, so callers that also hold +// the parsed map (routing/alias fallback re-marshals) observe the inlined data: +// URIs consistently with the returned rawBody. inlined=true obliges the caller +// to refresh every view derived from the pre-inline body — the provider-bound +// body, the routing traits computed from it, and the balance reservation, which +// was taken while the media was still a ~100-byte URL. +func (s *Server) resolveRemoteMedia(w http.ResponseWriter, r *http.Request, rawBody []byte, parsed map[string]any, timing *registry.RequestTiming, meta mediaResolveMeta) (body []byte, inlined bool, ok bool) { + if s.mediaResolver == nil || !s.mediaResolver.Enabled() { + return rawBody, false, true + } + + // Self-route skips the balance reservation, so nothing has yet gated egress + // on serve-ability. Before fetching, confirm the owner has an online machine + // that can serve this request; otherwise a user with no linked/offline/ + // incapable machine could drive up to the media-fetch caps of coordinator + // egress and only then get the self-route error. Only runs when a fetch would + // actually happen (remote media present); selfRouteUnavailable writes its own + // terminal response. The later runInferenceAdmission re-checks (idempotent). + if meta.selfRoute && mediafetch.HasRemoteMedia(parsed) { + if s.selfRouteUnavailable(w, r, meta.ownerAccountID, meta.model, + meta.traits, meta.requiresVision) { + return nil, false, false + } + } + + start := time.Now() + res, err := s.mediaResolver.Resolve(r.Context(), parsed) + if err != nil { + if errors.Is(err, context.Canceled) { + // The client is gone. The caller still refunds the monetary reservation, + // but there is no response to write and no rejection/timeout telemetry to + // emit: this was not an origin failure. + return nil, false, false + } + var me *mediafetch.Error + if !errors.As(err, &me) { + me = &mediafetch.Error{Status: http.StatusBadGateway, Code: "media_fetch_failed", + Public: "failed to fetch remote media", Internal: "unexpected resolver error"} + } + // Never log Internal here: media URLs often contain presigned credentials, + // and wrapped network errors can reproduce the full URL. mediafetch.Error + // keeps Internal non-sensitive as defense in depth, but the API log needs + // only stable structured fields. + s.logger.Warn("remote media rejected", "code", me.Code, "status", me.Status) + s.mediaFetchRejected(w, r, parsed, meta, me.Status, me.Code, me.Public) + return nil, false, false + } + if !res.Changed { + return rawBody, false, true + } + + // A URL was inlined — re-marshal so the forwarded body reflects the data: + // URI. marshalForwardBody (HTML-escaping disabled) matches the body the + // handler actually seals, so the routing/size view is consistent with the + // encrypted payload rather than an HTML-escaped (inflated) variant. + newBody, mErr := marshalForwardBody(parsed) + if mErr != nil { + s.logger.Error("re-marshal after media inline failed", "error", mErr) + s.ddIncr("inference.media_fetch.rejected", []string{"code:remarshal_failed", "model:" + meta.model}) + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", + "failed to process request media")) + return nil, false, false + } + // The inlined body must still fit the sealed-frame budget. The dispatch-time + // re-check would catch this too, but failing here names the actual cause + // (media, not "your JSON") while the fetch is still the freshest context. + if len(newBody) > maxInferenceBodyBytes { + s.mediaFetchRejected(w, r, parsed, meta, http.StatusRequestEntityTooLarge, "media_too_large", + "the request exceeds the size limit once remote media is inlined; use smaller media or fewer attachments") + return nil, false, false + } + + timing.MediaFetchedAt = time.Now() + modelTag := []string{"model:" + meta.model} + s.ddIncr("inference.media_fetch.ok", modelTag) + s.ddCount("inference.media_fetch.items", int64(res.Count), modelTag) + s.ddCount("inference.media_fetch.bytes", res.Bytes, modelTag) + s.ddHistogram("inference.media_fetch.duration_ms", float64(time.Since(start).Milliseconds()), modelTag) + return newBody, true, true +} + +// mediaFetchRejected records + writes a terminal media-fetch failure with the +// standard rejection telemetry shape. +func (s *Server) mediaFetchRejected(w http.ResponseWriter, r *http.Request, parsed map[string]any, meta mediaResolveMeta, status int, code, message string) { + reason := mediaRejectionReason(status) + s.recordRejection(rejectionInfo{ + r: r, + stage: "validation", + reasonCode: reason, + httpStatus: status, + keyID: keyIDFromContext(r.Context()), + consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), + requestedModel: meta.publicModel, + resolvedModel: meta.model, + stream: meta.stream, + estimatedPromptTokens: meta.estimatedPromptTokens, + requestedMaxTokens: meta.requestedMaxTokens, + requiresVision: true, + hasTools: meta.hasTools, + params: rejectionSamplingParams(parsed), + }) + s.ddIncr("inference.media_fetch.rejected", []string{"code:" + code, "model:" + meta.model}) + writeJSON(w, status, errorResponse(code, message, withParam("messages"))) +} + +// mediaRejectionReason maps a media-fetch failure's HTTP status onto the +// rejection-ledger reason_code, so the dashboards can tell a malformed consumer +// request apart from a blocked host, a slow origin and a broken upstream. +// Filing all of them as "bad_param" made every upstream fault look like a +// client bug. reason_code is a free-form TEXT column (store/postgres.go), so +// these values need no schema change. +func mediaRejectionReason(status int) string { + switch status { + case http.StatusForbidden: + return "media_blocked" + case http.StatusRequestTimeout: + return "upstream_timeout" + case http.StatusBadGateway, http.StatusGatewayTimeout: + return "upstream_error" + case http.StatusRequestEntityTooLarge: + return "payload_too_large" + default: + return "bad_param" + } +} diff --git a/coordinator/api/media_resolve_test.go b/coordinator/api/media_resolve_test.go new file mode 100644 index 0000000000..d332909c51 --- /dev/null +++ b/coordinator/api/media_resolve_test.go @@ -0,0 +1,739 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "image" + "image/png" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/eigeninference/d-inference/coordinator/mediafetch" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// --- helpers ---------------------------------------------------------------- + +// testPNG returns a real, decodable 2x2 PNG (passes both the sniff allowlist +// and the header pixel gate). +func testPNG(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil { + t.Fatalf("encode png: %v", err) + } + return buf.Bytes() +} + +// pngHandler serves a valid PNG and counts hits (for fetched/not-fetched asserts). +func pngHandler(t *testing.T, hits *int32) http.HandlerFunc { + img := testPNG(t) + return func(w http.ResponseWriter, r *http.Request) { + if hits != nil { + atomic.AddInt32(hits, 1) + } + w.Write(img) + } +} + +// makeVisionRoutableProvider registers an online, routable, vision-capable +// provider for model so a media request clears visionToolsFailFast and reaches +// the remote-media gate/resolution steps the HTTP-path tests below exercise. +// Nil test catalog => IsModelInCatalog/HasVisionProviderForModel allow it. +func makeVisionRoutableProvider(t *testing.T, reg *registry.Registry, id, model string) { + t.Helper() + p := makeRoutableProvider(t, reg, id, model) + p.Mu().Lock() + for i := range p.Models { + if p.Models[i].ID == model { + p.Models[i].IsVision = true + } + } + p.Mu().Unlock() +} + +// minimalMediaServer builds a Server with only the fields the media gate / +// resolver bridge touch, using a resolver that permits loopback so httptest +// works. +func minimalMediaServer(cfg mediafetch.Config) *Server { + return &Server{ + logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + mediaResolver: mediafetch.NewResolver(cfg, nil), + } +} + +func chatBodyBytes(t *testing.T, imageURL string) ([]byte, map[string]any) { + t.Helper() + parsed := map[string]any{ + "model": "test", + "messages": []any{map[string]any{"role": "user", "content": []any{ + map[string]any{"type": "image_url", "image_url": map[string]any{"url": imageURL}}, + }}}, + } + raw, err := json.Marshal(parsed) + if err != nil { + t.Fatalf("marshal: %v", err) + } + // Re-parse so the returned map is independent of the bytes (mirrors prelude). + var fresh map[string]any + if err := json.Unmarshal(raw, &fresh); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return raw, fresh +} + +func sealedReq() *http.Request { + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + return req.WithContext(context.WithValue(req.Context(), sealedCtxKey, struct{}{})) +} + +func plainReq() *http.Request { + return httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) +} + +func testMeta() mediaResolveMeta { + return mediaResolveMeta{model: "test", publicModel: "test"} +} + +// --- resolveRemoteMedia (phase 2, post-reservation) -------------------------- + +func TestResolveRemoteMediaInlinesOnSuccess(t *testing.T) { + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + s := minimalMediaServer(cfg) + + media := httptest.NewServer(pngHandler(t, nil)) + defer media.Close() + + raw, parsed := chatBodyBytes(t, media.URL+"/cat.png") + w := httptest.NewRecorder() + timing := ®istry.RequestTiming{} + + out, inlined, ok := s.resolveRemoteMedia(w, plainReq(), raw, parsed, timing, testMeta()) + if !ok { + t.Fatalf("resolveRemoteMedia ok=false, body=%s", w.Body.String()) + } + if !inlined { + t.Error("a body whose remote URL was inlined must report inlined=true") + } + if !bytes.Contains(out, []byte("data:image/png;base64,")) { + t.Errorf("returned body not inlined: %.80s", out) + } + if bytes.Contains(out, []byte("http://")) { + t.Errorf("returned body still carries an http URL: %.120s", out) + } + if timing.MediaFetchedAt.IsZero() { + t.Error("MediaFetchedAt must be stamped when media was fetched (X-Timing media_fetch_us)") + } +} + +func TestResolveRemoteMediaNoRemoteNoOp(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + raw, parsed := chatBodyBytes(t, "data:image/png;base64,iVBORw0KGgo=") + w := httptest.NewRecorder() + timing := ®istry.RequestTiming{} + + out, inlined, ok := s.resolveRemoteMedia(w, plainReq(), raw, parsed, timing, testMeta()) + if !ok || inlined || !bytes.Equal(out, raw) { + t.Fatalf("inline-only body must pass through unchanged (ok=%v inlined=%v)", ok, inlined) + } + if !timing.MediaFetchedAt.IsZero() { + t.Error("MediaFetchedAt must stay zero when nothing was fetched") + } +} + +func TestResolveRemoteMediaNilResolverPassthrough(t *testing.T) { + s := &Server{logger: quietLogger()} // e.g. a bare test Server + raw, parsed := chatBodyBytes(t, "https://example.com/cat.png") + w := httptest.NewRecorder() + + out, inlined, ok := s.resolveRemoteMedia(w, plainReq(), raw, parsed, ®istry.RequestTiming{}, testMeta()) + if !ok || inlined || !bytes.Equal(out, raw) { + t.Fatal("nil resolver must behave as disabled passthrough") + } +} + +func TestResolveRemoteMediaClientCancellationWritesNoRejection(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + raw, parsed := chatBodyBytes(t, "https://example.com/cancelled.png") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + req := plainReq().WithContext(ctx) + w := httptest.NewRecorder() + + out, _, ok := s.resolveRemoteMedia(w, req, raw, parsed, ®istry.RequestTiming{}, testMeta()) + if ok || out != nil { + t.Fatal("client cancellation must stop resolution") + } + if w.Body.Len() != 0 { + t.Fatalf("client cancellation wrote a rejection body: %s", w.Body.String()) + } +} + +func TestResolveRemoteMediaFailureWrites400(t *testing.T) { + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + s := minimalMediaServer(cfg) + + // Origin serves HTML behind a lying image Content-Type header. + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/png") + w.Write([]byte("not an image")) + })) + defer media.Close() + + raw, parsed := chatBodyBytes(t, media.URL+"/fake.png") + w := httptest.NewRecorder() + + out, _, ok := s.resolveRemoteMedia(w, plainReq(), raw, parsed, ®istry.RequestTiming{}, testMeta()) + if ok || out != nil { + t.Fatal("invalid content must fail the request") + } + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } + if code := errType(t, w.Body.Bytes()); code != "media_invalid_type" { + t.Errorf("error code = %q, want media_invalid_type", code) + } + // The consumer-facing message must not echo the internal origin host. + if strings.Contains(w.Body.String(), "127.0.0.1") { + t.Errorf("error body leaks the origin host: %s", w.Body.String()) + } +} + +func TestResolveRemoteMediaNeverLogsPresignedURLSecrets(t *testing.T) { + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + var logs bytes.Buffer + logger := slog.New(slog.NewTextHandler(&logs, nil)) + s := &Server{logger: logger, mediaResolver: mediafetch.NewResolver(cfg, logger)} + + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "missing", http.StatusNotFound) + })) + defer media.Close() + const secret = "X-Amz-Signature=do-not-log-this-secret" + raw, parsed := chatBodyBytes(t, media.URL+"/private.png?"+secret) + w := httptest.NewRecorder() + + if out, _, ok := s.resolveRemoteMedia(w, plainReq(), raw, parsed, ®istry.RequestTiming{}, testMeta()); ok || out != nil { + t.Fatal("upstream 404 must fail media resolution") + } + if got := logs.String(); strings.Contains(got, secret) || strings.Contains(got, media.URL) || strings.Contains(got, "/private.png") { + t.Fatalf("logs contain request URL or secret: %s", got) + } +} + +// --- gateRemoteMediaPreDispatch (phase 1, pre-billing) ----------------------- + +func TestGateSealedRejectsRemoteWithoutFetching(t *testing.T) { + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + s := minimalMediaServer(cfg) + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + + _, parsed := chatBodyBytes(t, media.URL+"/cat.png") + w := httptest.NewRecorder() + + if !s.gateRemoteMediaPreDispatch(w, sealedReq(), parsed, "test", "test", true, false) { + t.Fatal("sealed request with a remote URL must be handled (rejected)") + } + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } + if !strings.Contains(w.Body.String(), "data:") { + t.Errorf("error should instruct the sender to use a data: URI: %s", w.Body.String()) + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Errorf("sealed request triggered %d fetch(es); must be 0", n) + } +} + +func TestGateSealedAllowsInlineData(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + _, parsed := chatBodyBytes(t, "data:image/png;base64,iVBORw0KGgo=") + w := httptest.NewRecorder() + if s.gateRemoteMediaPreDispatch(w, sealedReq(), parsed, "test", "test", true, false) { + t.Fatal("sealed request with inline data: must pass the gate") + } +} + +func TestGateRemoteFetchableDefersToResolver(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + _, parsed := chatBodyBytes(t, "https://example.com/cat.png") + w := httptest.NewRecorder() + if s.gateRemoteMediaPreDispatch(w, plainReq(), parsed, "test", "test", true, false) { + t.Fatalf("fetchable remote URL must defer to post-reservation resolution, body=%s", w.Body.String()) + } +} + +func TestGateUnfetchableShapeRejected(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + // Anthropic source block with a remote URL: the resolver does not fetch this + // shape and the provider silently drops it (image-blind) — must keep the + // clean pre-dispatch 400. + parsed := map[string]any{ + "model": "test", + "messages": []any{map[string]any{"role": "user", "content": []any{ + map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://example.com/a.png"}}, + }}}, + } + w := httptest.NewRecorder() + if !s.gateRemoteMediaPreDispatch(w, plainReq(), parsed, "test", "test", true, false) { + t.Fatal("unfetchable remote shape must be rejected pre-dispatch") + } + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } +} + +func TestGateDisabledFallsBackToLegacyReject(t *testing.T) { + cfg := mediafetch.DefaultConfig() + cfg.Enabled = false + s := minimalMediaServer(cfg) + _, parsed := chatBodyBytes(t, "https://example.com/cat.png") + + w := httptest.NewRecorder() + if !s.gateRemoteMediaPreDispatch(w, plainReq(), parsed, "test", "test", true, false) { + t.Fatal("resolver disabled: remote URL must hit the legacy rejection") + } + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } + + // The retired DARKBLOOM_VISION_REJECT_REMOTE_URLS switch is read nowhere + // anymore: setting it must not turn fetch-disabled rollback back into + // dispatch-then-provider-400. + t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "false") + w2 := httptest.NewRecorder() + if !s.gateRemoteMediaPreDispatch(w2, plainReq(), parsed, "test", "test", true, false) { + t.Fatal("fetch-disabled gate must reject regardless of the legacy flag") + } + if w2.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", w2.Code) + } +} + +func TestGateNonVisionNoOp(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + if s.gateRemoteMediaPreDispatch(httptest.NewRecorder(), plainReq(), map[string]any{}, "test", "test", false, false) { + t.Fatal("non-vision requests must never be gated") + } +} + +func TestScanRemoteMediaRefs(t *testing.T) { + openaiRemote := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://x/a.png"}} + anthropicRemote := map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://x/b.png"}} + inline := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}} + fileScheme := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "file:///etc/passwd"}} + + mk := func(parts ...map[string]any) map[string]any { + anyParts := make([]any, len(parts)) + for i, p := range parts { + anyParts[i] = p + } + return map[string]any{"messages": []any{map[string]any{"role": "user", "content": anyParts}}} + } + + for _, tc := range []struct { + name string + body map[string]any + wantRemote, wantUnfetch string + }{ + {"text only", map[string]any{"messages": []any{map[string]any{"role": "user", "content": "hi"}}}, "", ""}, + {"inline only", mk(inline), "", ""}, + // Fetchable: remote, but nothing for the unfetchable-shape gate. + {"fetchable openai part", mk(openaiRemote, inline), "https://x/a.png", ""}, + {"anthropic beside fetchable", mk(openaiRemote, anthropicRemote), "https://x/a.png", "https://x/b.png"}, + // URL equality must not make an unsupported shape fetchable: each part is + // judged by its own shape and location. + {"same url, both shapes", mk( + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://x/s.png"}}, + map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://x/s.png"}}, + ), "https://x/s.png", "https://x/s.png"}, + {"file scheme", mk(fileScheme), "file:///etc/passwd", "file:///etc/passwd"}, + {"responses input surface", map[string]any{"input": []any{ + map[string]any{"content": []any{anthropicRemote}}, + }}, "https://x/b.png", "https://x/b.png"}, + // Responses input[] never has a fetchable shape, even for an OpenAI part. + {"openai part under input", map[string]any{"input": []any{ + map[string]any{"content": []any{openaiRemote}}, + }}, "https://x/a.png", "https://x/a.png"}, + } { + t.Run(tc.name, func(t *testing.T) { + got := scanRemoteMediaRefs(tc.body) + if got.firstRemote != tc.wantRemote { + t.Errorf("firstRemote = %q, want %q", got.firstRemote, tc.wantRemote) + } + if got.firstUnfetchable != tc.wantUnfetch { + t.Errorf("firstUnfetchable = %q, want %q", got.firstUnfetchable, tc.wantUnfetch) + } + }) + } +} + +// TestGateSealedRejectsEveryRemoteShape pins that a sealed request is refused +// for ANY remote reference, not just the ones the resolver would fetch. Keying +// the sealed branch off the fetchable subset sent an Anthropic source-URL +// sender the unfetchable-shape message, which advises sending an OpenAI http(s) +// link — advice for something a sealed request will never do either. +func TestGateSealedRejectsEveryRemoteShape(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + for _, tc := range []struct { + name string + part map[string]any + }{ + {"openai image_url", map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://x/a.png"}}}, + {"anthropic source url", map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": "https://x/b.png"}}}, + {"responses input_image", map[string]any{"type": "input_image", "image_url": "https://x/c.png"}}, + } { + t.Run(tc.name, func(t *testing.T) { + body := map[string]any{"messages": []any{ + map[string]any{"role": "user", "content": []any{tc.part}}, + }} + w := httptest.NewRecorder() + if !s.gateRemoteMediaPreDispatch(w, sealedReq(), body, "test", "test", true, false) { + t.Fatal("a sealed request carrying a remote media reference must be rejected") + } + if got := w.Body.String(); !strings.Contains(got, "sealed requests must send media as an inline") { + t.Errorf("sealed request got the wrong guidance: %s", got) + } + }) + } +} + +func TestResolveRemoteMediaSelfRouteUnavailableSkipsFetch(t *testing.T) { + srv, _ := testServer(t) // real registry + store, no linked providers + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + + raw, parsed := chatBodyBytes(t, media.URL+"/cat.png") + w := httptest.NewRecorder() + meta := mediaResolveMeta{ + model: "test", publicModel: "test", requiresVision: true, + selfRoute: true, ownerAccountID: "owner-with-no-machine", + } + out, _, ok := srv.resolveRemoteMedia(w, plainReq(), raw, parsed, ®istry.RequestTiming{}, meta) + if ok || out != nil { + t.Fatal("self-route with no serving machine must not resolve media") + } + if w.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409 (no_linked_machine)", w.Code) + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("unserviceable self-route triggered %d origin fetch(es); want 0", n) + } +} + +// --- full HTTP path through srv.Handler() ------------------------------------ + +func errType(t *testing.T, body []byte) string { + t.Helper() + var resp struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal(body, &resp); err != nil { + t.Fatalf("unmarshal error body %q: %v", body, err) + } + if resp.Error.Code != "" { + return resp.Error.Code + } + return resp.Error.Type +} + +func TestChatCompletionsRemoteMediaRequiresMediaAwareBalanceBeforeFetch(t *testing.T) { + srv, st := testBillingServer(t) + makeVisionRoutableProvider(t, srv.registry, "vision-balance", "test") + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + // Make the prompt-token difference visible above the universal minimum fee. + if err := st.SetModelPrice("platform", "test", 1_000_000, 0); err != nil { + t.Fatal(err) + } + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + _, parsed := chatBodyBytes(t, media.URL+"/private.png") + parsed["max_tokens"] = 1 + body, err := json.Marshal(parsed) + if err != nil { + t.Fatal(err) + } + estimated := estimatePromptTokens(parsed) + billing := estimateBillingPromptTokens(parsed) + if estimated <= billing { + t.Fatalf("test setup requires media estimate > URL-byte bound; estimated=%d billing=%d", estimated, billing) + } + urlOnlyCost := srv.reservationCost("test", billing, 1) + mediaAwareCost := srv.reservationCost("test", estimated, 1) + if mediaAwareCost <= urlOnlyCost { + t.Fatalf("test setup requires distinct costs; URL=%d media=%d", urlOnlyCost, mediaAwareCost) + } + if err := st.Credit(testConsumerID, urlOnlyCost, store.LedgerDeposit, "media-prefetch-floor"); err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402; body=%s", w.Code, w.Body.String()) + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("insufficient media-aware balance triggered %d origin fetch(es); want 0", n) + } +} + +func TestChatCompletionsRemoteMediaSSRFBlocked(t *testing.T) { + srv, _ := testServer(t) + makeVisionRoutableProvider(t, srv.registry, "vision-ssrf", "test") + cfg := mediafetch.DefaultConfig() + cfg.AllowNonStandardPorts = true // isolate connect-time loopback blocking from the port gate + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + media := httptest.NewServer(pngHandler(t, nil)) + defer media.Close() + + body, _ := chatBodyBytes(t, media.URL+"/x.png") // loopback → must be blocked at dial time + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403; body=%s", w.Code, w.Body.String()) + } + if code := errType(t, w.Body.Bytes()); code != "media_blocked" { + t.Errorf("error code = %q, want media_blocked", code) + } +} + +func TestChatCompletionsRemoteMediaSuccessInlines(t *testing.T) { + srv, _ := testServer(t) + makeVisionRoutableProvider(t, srv.registry, "vision-ok", "test") + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true // loopback httptest origin + cfg.AllowNonStandardPorts = true + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + + body, _ := chatBodyBytes(t, media.URL+"/cat.png") + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + // The fetch+inline succeeded (origin was hit exactly once) and the request + // proceeded past validation into dispatch. No live provider WebSocket exists + // in this harness, so the terminal status is a downstream dispatch/queue + // outcome — anything but the media-gate 4xx family proves the media step. + if n := atomic.LoadInt32(&hits); n != 1 { + t.Fatalf("origin hit %d time(s), want exactly 1; status=%d body=%.200s", n, w.Code, w.Body.String()) + } + if w.Code == http.StatusBadRequest || w.Code == http.StatusForbidden { + t.Errorf("request died at the media gate: %d %s", w.Code, w.Body.String()) + } +} + +func TestChatCompletionsRemoteMediaDisabledLegacyReject(t *testing.T) { + srv, _ := testServer(t) + makeVisionRoutableProvider(t, srv.registry, "vision-disabled", "test") + cfg := mediafetch.DefaultConfig() + cfg.Enabled = false + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + // Fake public URL: never fetched because the disabled gate fires first + // (legacy pre-dispatch rejection, invalid_request_error). + body, _ := chatBodyBytes(t, "https://example.com/cat.png") + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body=%s", w.Code, w.Body.String()) + } + if code := errType(t, w.Body.Bytes()); code != "invalid_request_error" { + t.Errorf("error code = %q, want invalid_request_error (legacy reject)", code) + } + if !strings.Contains(w.Body.String(), "data:") { + t.Errorf("legacy rejection must point at the data: URI contract: %s", w.Body.String()) + } +} + +// TestPreludeDefersRemoteMediaResolution locks in the cost-gate ordering: the +// shared parseInferencePrelude must NOT fetch/inline remote media. Resolution is +// deferred to the chat handler AFTER token admission + the balance reservation, +// so an authenticated but unfunded/over-quota request can never drive +// coordinator-side fetches. A remote URL therefore survives the prelude +// unchanged and no fetch occurs. The resolver here permits loopback, so it +// WOULD inline successfully if the prelude (wrongly) invoked it — proving the +// deferral, not a fetch failure. +func TestPreludeDefersRemoteMediaResolution(t *testing.T) { + srv, _ := testServer(t) + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + + body, _ := chatBodyBytes(t, media.URL+"/x.png") + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + w := httptest.NewRecorder() + + prelude, ok := srv.parseInferencePrelude(w, req) + if !ok { + t.Fatalf("prelude unexpectedly failed: %s", w.Body.String()) + } + if !bytes.Contains(prelude.rawBody, []byte("http://")) { + t.Errorf("prelude inlined the remote URL; media resolution must be deferred to post-billing") + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Errorf("prelude fetched media %d time(s); must be 0 (resolution is deferred to post-billing)", n) + } +} + +// TestMediaRejectionReasonMapping pins the media-failure status → rejection-ledger +// reason_code mapping. Filing everything but 413 as "bad_param" made a blocked +// host, a slow origin and a broken upstream indistinguishable from a malformed +// consumer request on the rejection dashboards. +func TestMediaRejectionReasonMapping(t *testing.T) { + cases := []struct { + name string + status int + want string + }{ + {"blocked host or resolved address", http.StatusForbidden, "media_blocked"}, + {"origin took too long", http.StatusRequestTimeout, "upstream_timeout"}, + {"upstream failed", http.StatusBadGateway, "upstream_error"}, + {"upstream gateway timeout", http.StatusGatewayTimeout, "upstream_error"}, + {"media too large", http.StatusRequestEntityTooLarge, "payload_too_large"}, + {"malformed consumer request", http.StatusBadRequest, "bad_param"}, + {"unmapped status falls back", http.StatusInternalServerError, "bad_param"}, + } + for _, c := range cases { + if got := mediaRejectionReason(c.status); got != c.want { + t.Errorf("%s: mediaRejectionReason(%d) = %q, want %q", c.name, c.status, got, c.want) + } + } +} + +// TestMediaFetchRejectedPreservesAPIContract guards the other half of the remap: +// the consumer-visible status, error type and message are API contract and must +// not shift when the internal reason_code changes. +func TestMediaFetchRejectedPreservesAPIContract(t *testing.T) { + s := minimalMediaServer(mediafetch.DefaultConfig()) + w := httptest.NewRecorder() + s.mediaFetchRejected(w, plainReq(), map[string]any{}, + mediaResolveMeta{model: "test", publicModel: "test"}, + http.StatusForbidden, "media_blocked", "a media URL host is not allowed") + + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403", w.Code) + } + var body struct { + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode body: %v", err) + } + if body.Error.Type != "media_blocked" { + t.Errorf("error.type = %q, want media_blocked", body.Error.Type) + } + if body.Error.Message != "a media URL host is not allowed" { + t.Errorf("error.message = %q, want the unchanged public message", body.Error.Message) + } +} + +// TestResolveRemoteMediaSelfRouteUsesFullTraits pins that the pre-fetch +// self-route gate judges serve-ability with the SAME traits the real admission +// uses. Reconstructing a partial set (HasTools only) called an owned provider +// serviceable when the request needed a trait it does not advertise — here a +// constrained tool_choice (RequiresToolConstraint) — so the media was fetched +// and only then rejected by runInferenceAdmission. That is the exact +// egress-before-rejection hole the self-route gate exists to close. +func TestResolveRemoteMediaSelfRouteUsesFullTraits(t *testing.T) { + srv, _ := testServer(t) + cfg := mediafetch.DefaultConfig() + cfg.AllowPrivateIPs = true + cfg.AllowNonStandardPorts = true + srv.mediaResolver = mediafetch.NewResolver(cfg, srv.logger) + + // An owned, online, vision- and tool-capable machine that does NOT advertise + // the tool-constraint protocol: serviceable for HasTools alone, ineligible + // once RequiresToolConstraint is included. + const owner = "owner-acct" + makeVisionRoutableProvider(t, srv.registry, "self-route-traits", "test") + for _, id := range srv.registry.ProviderIDs() { + if p := srv.registry.GetProvider(id); p != nil { + p.Mu().Lock() + p.AccountID = owner + // Well above the tools version floor, so HasTools alone is satisfied + // and ToolConstraintProtocol (left unset, i.e. not v1) is the ONLY + // reason the request is ineligible. Without this the provider fails + // the floor either way and the test cannot see the trait delta. + p.Version = "0.7.6" + p.Mu().Unlock() + } + } + // Sanity: the partial trait set the gate used to reconstruct MUST consider + // this provider serviceable, or the assertion below proves nothing. + if !srv.registry.HasToolCapableProviderForModel("test") { + t.Fatal("setup: provider must satisfy the plain tools floor") + } + + var hits int32 + media := httptest.NewServer(pngHandler(t, &hits)) + defer media.Close() + + raw, parsed := chatBodyBytes(t, media.URL+"/cat.png") + w := httptest.NewRecorder() + out, _, ok := srv.resolveRemoteMedia(w, plainReq(), raw, parsed, ®istry.RequestTiming{}, mediaResolveMeta{ + model: "test", publicModel: "test", requiresVision: true, + selfRoute: true, ownerAccountID: owner, hasTools: true, + traits: registry.RequestTraits{HasTools: true, RequiresToolConstraint: true}, + }) + if ok || out != nil { + t.Fatal("a self-route request needing an unadvertised trait must not resolve media") + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("trait-ineligible self-route triggered %d origin fetch(es); want 0", n) + } +} diff --git a/coordinator/api/request_introspection.go b/coordinator/api/request_introspection.go index e7700263cb..04ed0104f2 100644 --- a/coordinator/api/request_introspection.go +++ b/coordinator/api/request_introspection.go @@ -8,13 +8,19 @@ package api // state; the pre-dispatch media-URL rejection (rejectRemoteMediaURLs) hangs // off *Server only to record rejection telemetry. Split out of consumer.go // to keep the request-handling orchestrator thin. +// +// Remote-media flow note: on the chat-completions surface the media resolver +// (media_resolve.go / coordinator/mediafetch) FETCHES remote image_url/video_url +// links and inlines them as data: URIs, so rejectRemoteMediaURLs only fires +// there when the resolver is disabled, the request is sender-sealed, or a +// remote reference sits in a shape the resolver does not fetch (see +// gateRemoteMediaPreDispatch). The generic (completions + Anthropic) surface +// keeps the unconditional rejection. import ( "encoding/json" "fmt" "net/http" - "os" - "strconv" "strings" "github.com/eigeninference/d-inference/coordinator/store" @@ -414,34 +420,47 @@ func validateMediaParts(parsed map[string]any) (badRef string, ok bool) { return "", true } -// visionRejectRemoteEnabled gates the C4 pre-dispatch remote-media-URL rejection. -// Default ON; DARKBLOOM_VISION_REJECT_REMOTE_URLS=false (or 0) restores the prior -// dispatch-then-provider-400 behavior (still bounded by C1). Read live so the -// kill switch toggles without a redeploy. -func visionRejectRemoteEnabled() bool { - v := strings.TrimSpace(os.Getenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS")) - if v == "" { - return true - } - on, err := strconv.ParseBool(v) - return err != nil || on -} - // rejectRemoteMediaURLs fails a vision request fast (one terminal 400) when any // media part carries a remote/non-inline URL, mirroring the provider's data:-only // contract. Pre-dispatch — no provider is contacted. handled=true => caller returns. +// +// Unconditional by design, on every surface. The generic (completions + +// Anthropic) surface never fetches, so forwarding a remote URL there can only +// end in a provider-side 400 — the dispatch-then-provider-400 behavior this +// gate exists to eliminate. On the chat surface it is the authoritative +// data:-only fallback used when EIGENINFERENCE_MEDIA_FETCH_ENABLED=false. +// The retired DARKBLOOM_VISION_REJECT_REMOTE_URLS kill switch no longer gates +// it: disabling fetch must never re-enable forwarding. func (s *Server) rejectRemoteMediaURLs(w http.ResponseWriter, r *http.Request, parsed map[string]any, model, publicModel string, requiresVision, hasTools bool) (handled bool) { - if !requiresVision || !visionRejectRemoteEnabled() { + if !requiresVision { return false } badRef, ok := validateMediaParts(parsed) if ok { return false } - shown := badRef - if len(shown) > 200 { - shown = shown[:200] + "…" - } + s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, + "image/video input must be an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\"); "+ + "remote http(s):// and file:// media URLs are not supported on this endpoint. Got: "+truncateMediaRef(badRef)) + return true +} + +// truncateMediaRef bounds a consumer-supplied media reference for inclusion in +// an error message (URLs can be data: URIs megabytes long). The cut is a byte +// slice, so it can split a multibyte rune; the trailing partial rune is dropped +// rather than left for encoding/json to turn into U+FFFD. +func truncateMediaRef(ref string) string { + if len(ref) > 200 { + return strings.ToValidUTF8(ref[:200], "") + "…" + } + return ref +} + +// writeRemoteMediaRejection records + writes the standard pre-dispatch remote +// media 400 (identical telemetry shape for every remote-media rejection path: +// legacy data:-only, sealed-request, and unfetchable-shape — see +// gateRemoteMediaPreDispatch in media_resolve.go). +func (s *Server) writeRemoteMediaRejection(w http.ResponseWriter, r *http.Request, parsed map[string]any, model, publicModel string, hasTools bool, message string) { stream, _ := parsed["stream"].(bool) s.recordRejection(rejectionInfo{ r: r, @@ -458,11 +477,7 @@ func (s *Server) rejectRemoteMediaURLs(w http.ResponseWriter, r *http.Request, p params: rejectionSamplingParams(parsed), }) s.ddIncr("inference.media_remote_url_rejected", []string{"model:" + model}) - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - "image/video input must be an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\"); "+ - "remote http(s):// and file:// media URLs are not supported on this end-to-end-encrypted endpoint. Got: "+shown, - withParam("messages"))) - return true + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", message, withParam("messages"))) } // requestHasTools reports whether the request carries a non-empty top-level diff --git a/coordinator/api/sender_encryption.go b/coordinator/api/sender_encryption.go index 6d9855af68..daac6d4f72 100644 --- a/coordinator/api/sender_encryption.go +++ b/coordinator/api/sender_encryption.go @@ -75,6 +75,17 @@ type sealedCtxKeyT struct{} var sealedCtxKey = sealedCtxKeyT{} +// isSealedRequest reports whether r was decrypted by sealedTransport (i.e. the +// sender NaCl-Box-sealed it to the coordinator). The marker is set on the +// request context at sealedTransport's r.Clone(...WithValue(sealedCtxKey,...)) +// site. Used to refuse remote-media URL fetching on sealed requests: fetching +// would generate origin-observable egress correlated with a payload the sender +// chose to seal, so sealed media must be an inline data: URI instead (see +// gateRemoteMediaPreDispatch). +func isSealedRequest(r *http.Request) bool { + return r.Context().Value(sealedCtxKey) != nil +} + // isSealedContentType returns true when ct is the sealed media type, ignoring // case (RFC 7231 §3.1.1.1) and any parameters like charset suffixes. func isSealedContentType(ct string) bool { diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 105b9d61c0..fa7057bcb4 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -40,6 +40,7 @@ import ( "github.com/eigeninference/d-inference/coordinator/datadog" "github.com/eigeninference/d-inference/coordinator/internal/e2e" "github.com/eigeninference/d-inference/coordinator/mdm" + "github.com/eigeninference/d-inference/coordinator/mediafetch" "github.com/eigeninference/d-inference/coordinator/payments" "github.com/eigeninference/d-inference/coordinator/payments/baserewards" "github.com/eigeninference/d-inference/coordinator/profilesign" @@ -423,6 +424,15 @@ type Server struct { // Server built directly (e.g. &Server{} in tests) leaves it nil, and // submitTelemetry falls back to a per-write saferun.Go in that case. routeTelemetry *telemetrySink + + // mediaResolver fetches remote http(s) image_url/video_url links into + // inline base64 data: URIs before the request body is E2E-encrypted to a + // provider, so consumers can pass links instead of pre-encoding media + // client-side (media_resolve.go). The coordinator is the single SSRF + // chokepoint; the provider still only ever sees data: URIs. Set by + // NewServer from env; nil (e.g. a &Server{} built directly in tests) + // behaves as disabled and falls back to the legacy pre-dispatch rejection. + mediaResolver *mediafetch.Resolver } // SetRateLimiter configures the per-account rate limiter applied to @@ -691,6 +701,13 @@ func NewServer(reg *registry.Registry, st store.Store, cfg ServerConfig, logger // Wire the store into the registry for provider fleet persistence. reg.SetStore(st) + // main.go supplies the AppConfig-validated media-fetch config; a nil field + // (bare ServerConfig{} literals, tests) falls back to the environment. + mediaFetchCfg := mediafetch.ConfigFromEnv() + if cfg.MediaFetch != nil { + mediaFetchCfg = *cfg.MediaFetch + } + s := &Server{ registry: reg, store: st, @@ -709,6 +726,7 @@ func NewServer(reg *registry.Registry, st store.Store, cfg ServerConfig, logger zombieCanceller: newZombieStreamCanceller(), serviceReservations: newServiceReservationManager(st, cfg.ServiceReservations), routeTelemetry: newTelemetrySink(logger, defaultTelemetrySinkCapacity, defaultTelemetrySinkWorkers), + mediaResolver: mediafetch.NewResolver(mediaFetchCfg, logger), } s.registerDefaultGauges() s.routes() diff --git a/coordinator/api/server_config.go b/coordinator/api/server_config.go index 51431837b5..820b00e23e 100644 --- a/coordinator/api/server_config.go +++ b/coordinator/api/server_config.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/eigeninference/d-inference/coordinator/env" + "github.com/eigeninference/d-inference/coordinator/mediafetch" ) // ServerConfig holds coordinator HTTP server and URL configuration. @@ -22,6 +23,11 @@ type ServerConfig struct { ReleaseKey string ServiceReservations bool BaseRewards BaseRewardsConfig + // MediaFetch is the remote media resolution config (mediafetch package). + // nil means "read it from the environment in NewServer", which keeps the + // bare ServerConfig{} literals used by tests working unchanged. main.go + // threads the AppConfig-validated value in. + MediaFetch *mediafetch.Config } // BaseRewardsConfig holds the deployment knobs for the provider base-rewards diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index 49436f611e..87ee057101 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -231,7 +231,12 @@ func main() { // Secret Manager, never commit). When set, geo lookups use the unmetered // https://pro.ip-api.com endpoint; unset falls back to the free, 45 req/min // http://ip-api.com endpoint (graceful, so dev without a key still works). - srv := api.NewServer(reg, st, cfg.ServerConfig, logger) + // Remote media resolution (mediafetch) is read and validated as part of + // AppConfig; hand the validated value to the server instead of letting + // NewServer re-read the environment. + serverCfg := cfg.ServerConfig + serverCfg.MediaFetch = &cfg.MediaFetchCfg + srv := api.NewServer(reg, st, serverCfg, logger) var promptProvisioner *promptcontract.Provisioner if cfg.PromptSidecar.Enabled { artifactBaseURL, err := url.Parse(cfg.PromptSidecar.ArtifactBaseURL) diff --git a/coordinator/config/app_config.go b/coordinator/config/app_config.go index b2b6921869..a08e494501 100644 --- a/coordinator/config/app_config.go +++ b/coordinator/config/app_config.go @@ -18,6 +18,7 @@ import ( "github.com/eigeninference/d-inference/coordinator/datadog" "github.com/eigeninference/d-inference/coordinator/env" "github.com/eigeninference/d-inference/coordinator/mdm" + "github.com/eigeninference/d-inference/coordinator/mediafetch" "github.com/eigeninference/d-inference/coordinator/promptcontract" "github.com/eigeninference/d-inference/coordinator/ratelimit" "github.com/eigeninference/d-inference/coordinator/registry" @@ -42,6 +43,7 @@ type AppConfig struct { RegistryCfg registry.Config MDMConfig mdm.Config DatadogConfig datadog.Config + MediaFetchCfg mediafetch.Config PromptSidecar promptcontract.SupervisorConfig AdminKey string AdminEmails []string @@ -74,6 +76,9 @@ func (c AppConfig) Check() error { if err := c.DatadogConfig.Check(); err != nil { return fmt.Errorf("datadog: %w", err) } + if err := c.MediaFetchCfg.Check(); err != nil { + return fmt.Errorf("media_fetch: %w", err) + } if err := c.PromptSidecar.Check(); err != nil { return fmt.Errorf("prompt_sidecar: %w", err) } @@ -97,6 +102,7 @@ func ReadAppConfig() AppConfig { RegistryCfg: registry.ReadConfig(), MDMConfig: mdm.ReadConfig(), DatadogConfig: datadog.ConfigFromEnv(), + MediaFetchCfg: mediafetch.ConfigFromEnv(), PromptSidecar: promptcontract.ReadSupervisorConfig(), AdminKey: env.EnvOr(EnvPrefix+"_ADMIN_KEY", ""), AdminEmails: api.ParseCommaList(env.EnvOr(EnvPrefix+"_ADMIN_EMAILS", "")), diff --git a/coordinator/mediafetch/budget.go b/coordinator/mediafetch/budget.go new file mode 100644 index 0000000000..39abe29f8d --- /dev/null +++ b/coordinator/mediafetch/budget.go @@ -0,0 +1,89 @@ +package mediafetch + +// budget.go enforces the raw per-request byte limit DURING concurrent reads. +// Checking only after each fetch returns allows Concurrency × MaxFileBytes to be +// retained transiently (32 MiB under defaults) before the 10 MiB aggregate cap +// trips. byteBudget coordinates all readers and permits at most limit+1 consumed +// bytes across them; the extra byte is solely the overflow sentinel that lets an +// exactly-at-limit response probe EOF successfully. + +import ( + "errors" + "io" + "math" + "sync" +) + +var errAggregateBudgetExceeded = errors.New("mediafetch: aggregate byte budget exceeded") + +type byteBudget struct { + mu sync.Mutex + cond *sync.Cond + limit int64 + capacity int64 // limit+1 overflow sentinel + used int64 // bytes returned to callers and retained in their result buffers + inFlight int64 // bytes reserved by reads currently inside the underlying Reader +} + +func newByteBudget(limit int64) *byteBudget { + capacity := limit + if limit < math.MaxInt64 { + capacity++ + } + b := &byteBudget{limit: limit, capacity: capacity} + b.cond = sync.NewCond(&b.mu) + return b +} + +func (b *byteBudget) reader(r io.Reader) io.Reader { + return &budgetReader{source: r, budget: b} +} + +// reserve waits only while another reader temporarily owns all available +// budget. Once those reads finish, unused reservation is returned; consumed +// bytes remain charged. If the sentinel capacity is fully consumed there is no +// future capacity to wait for and the aggregate-overflow error is terminal. +func (b *byteBudget) reserve(want int) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + for { + available := b.capacity - b.used - b.inFlight + if available > 0 { + if int64(want) > available { + want = int(available) + } + b.inFlight += int64(want) + return want, nil + } + if b.inFlight == 0 { + return 0, errAggregateBudgetExceeded + } + b.cond.Wait() + } +} + +func (b *byteBudget) finish(reserved, consumed int) { + b.mu.Lock() + b.inFlight -= int64(reserved) + b.used += int64(consumed) + b.cond.Broadcast() + b.mu.Unlock() +} + +type budgetReader struct { + source io.Reader + budget *byteBudget +} + +func (r *budgetReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + reserved, err := r.budget.reserve(len(p)) + if err != nil { + return 0, err + } + n, readErr := r.source.Read(p[:reserved]) + r.budget.finish(reserved, n) + return n, readErr +} diff --git a/coordinator/mediafetch/budget_test.go b/coordinator/mediafetch/budget_test.go new file mode 100644 index 0000000000..ce5e6a06e8 --- /dev/null +++ b/coordinator/mediafetch/budget_test.go @@ -0,0 +1,74 @@ +package mediafetch + +import ( + "bytes" + "errors" + "io" + "sync" + "testing" +) + +func TestByteBudgetExactLimitAcrossConcurrentReaders(t *testing.T) { + budget := newByteBudget(100) + inputs := [][]byte{bytes.Repeat([]byte{'a'}, 40), bytes.Repeat([]byte{'b'}, 60)} + + var wg sync.WaitGroup + errs := make(chan error, len(inputs)) + for _, input := range inputs { + wg.Add(1) + go func(data []byte) { + defer wg.Done() + got, err := io.ReadAll(budget.reader(bytes.NewReader(data))) + if err == nil && len(got) != len(data) { + err = errors.New("short exact-limit read") + } + errs <- err + }(input) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("exact aggregate limit must succeed: %v", err) + } + } + if budget.used != 100 { + t.Fatalf("used = %d, want 100", budget.used) + } +} + +func TestByteBudgetBoundsConcurrentOverflow(t *testing.T) { + budget := newByteBudget(100) + inputs := [][]byte{ + bytes.Repeat([]byte{'a'}, 80), + bytes.Repeat([]byte{'b'}, 80), + bytes.Repeat([]byte{'c'}, 80), + bytes.Repeat([]byte{'d'}, 80), + } + + var wg sync.WaitGroup + errCount := 0 + var errMu sync.Mutex + for _, input := range inputs { + wg.Add(1) + go func(data []byte) { + defer wg.Done() + _, err := io.ReadAll(budget.reader(bytes.NewReader(data))) + if errors.Is(err, errAggregateBudgetExceeded) { + errMu.Lock() + errCount++ + errMu.Unlock() + } + }(input) + } + wg.Wait() + if errCount == 0 { + t.Fatal("aggregate overflow must fail at least one reader") + } + if budget.used > 101 { + t.Fatalf("transient consumed bytes = %d, want <= limit+1 sentinel (101)", budget.used) + } + if budget.inFlight != 0 { + t.Fatalf("inFlight = %d after readers complete, want 0", budget.inFlight) + } +} diff --git a/coordinator/mediafetch/config.go b/coordinator/mediafetch/config.go new file mode 100644 index 0000000000..425d4cd18a --- /dev/null +++ b/coordinator/mediafetch/config.go @@ -0,0 +1,350 @@ +// Package mediafetch resolves remote http(s) media URLs (image_url / video_url) +// embedded in OpenAI-compatible inference request bodies into inline base64 +// `data:` URIs, on the coordinator, before the body is end-to-end-encrypted to a +// provider. +// +// Why coordinator-side: the Swift provider deliberately rejects any non-`data:` +// URI as an SSRF guard (providers run on consumer-owned Macs whose LANs must not +// be probed — see MediaIngest.swift). The coordinator is the more-trusted +// component (TEE/CVM) and a single chokepoint: it fetches each URL exactly once +// per request — not once per speculative/failover dispatch — applies strict SSRF +// defenses, re-encodes the bytes as a `data:` URI, and hands the provider the +// same inline shape it already accepts. The provider's guard is therefore +// unchanged (defense in depth). +// +// Safety posture ("is it malware?"): fetched bytes are never executed or parsed +// beyond header sniffing here. Defenses are structural and layered: +// +// - SSRF: scheme allowlist, no embedded credentials, optional domain +// blocklist, and a connect-time IP deny policy (loopback/private/link-local/ +// metadata/CGNAT/IPv6-transition/reserved) enforced in the dialer Control hook, +// runs on the post-DNS-resolution address of EVERY dial including each +// redirect hop — DNS-rebinding-proof (ssrf.go). +// - Content: the data: URI is built from the SNIFFED type (magic bytes), never +// the spoofable Content-Type header; only formats the provider's decoders +// (CoreImage / AVFoundation) actually support are inlined; an image_url part +// must sniff as an image and a video_url part as a video; HTML/SVG/scripts/ +// executables/polyglots fail the allowlist (sniff.go). +// - Bombs: per-file and shared per-request byte caps enforced while reading +// (Content-Length is only a pre-check), no transparent decompression, and a +// header-only megapixel cap for every accepted image format mirroring the +// provider's own pre-raster pixel gate (fetch.go, budget.go, sniff.go). The +// provider's decode-time caps (pixels, bytes, video duration/frames) remain +// the second, authoritative layer. +// - Resource use: per-request part count/concurrency caps, a process-wide +// fetch semaphore, and per-fetch + whole-step deadlines. +// +// Sender-sealed requests are never fetched: the sender opted into sealing the +// payload to the coordinator, and fetching would generate origin-observable +// egress correlated with that request. The API layer rejects sealed requests +// carrying remote URLs (see api.gateRemoteMediaPreDispatch) and tells the sender +// to inline a data: URI instead. +package mediafetch + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/env" +) + +// Environment variable names (EIGENINFERENCE_ prefix, per coordinator/env). +const ( + envEnabled = env.EnvPrefix + "_MEDIA_FETCH_ENABLED" + envMaxFileBytes = env.EnvPrefix + "_MEDIA_FETCH_MAX_FILE_BYTES" + envMaxTotalBytes = env.EnvPrefix + "_MEDIA_FETCH_MAX_TOTAL_BYTES" + envTimeoutMS = env.EnvPrefix + "_MEDIA_FETCH_TIMEOUT_MS" + envTotalDeadline = env.EnvPrefix + "_MEDIA_FETCH_TOTAL_DEADLINE_MS" + envGlobalConc = env.EnvPrefix + "_MEDIA_FETCH_GLOBAL_CONCURRENCY" + envMaxMegapixels = env.EnvPrefix + "_MEDIA_FETCH_MAX_IMAGE_MEGAPIXELS" + envBlocklist = env.EnvPrefix + "_MEDIA_FETCH_BLOCKLIST_DOMAINS" + envAllowPrivateIP = env.EnvPrefix + "_MEDIA_FETCH_ALLOW_PRIVATE_IPS" + envAllowOtherPorts = env.EnvPrefix + "_MEDIA_FETCH_ALLOW_NONSTANDARD_PORTS" +) + +// Defaults. The byte caps are reconciled against the coordinator's own 16 MiB +// forwarded-body cap (api.maxInferenceBodyBytes), which binds before the +// provider's 32 MiB frame. Raw media inflates ~1.37x as base64, so a 10 MiB +// aggregate raw cap inlines to ~13.3 MiB and leaves ~2.7 MiB for the rest of the +// request — a valid request is never fetched only to be rejected afterwards. +// +// MaxInlinedBytes bounds the same 16 MiB from the other side: duplicate parts +// sharing one URL are fetched once but written back to EVERY location, and the +// raw caps cannot see that multiplication. +// +// MaxImageMegapixels mirrors the provider's DARKBLOOM_MAX_IMAGE_MEGAPIXELS +// (100 MP, header-read) so pixel bombs die here, not across the fleet. +const ( + DefaultMaxFileBytes int64 = 8 << 20 // 8 MiB per fetched file + DefaultMaxTotalBytes int64 = 10 << 20 // 10 MiB aggregate raw media/request (~13.3 MiB inlined) + DefaultMaxInlinedBytes int64 = 16 << 20 // matches api.maxInferenceBodyBytes (post-inline projection cap) + DefaultMaxParts = 8 // max remote media parts per request (matches the provider's videos/request cap) + DefaultTimeout = 15 * time.Second + DefaultTotalDeadline = 25 * time.Second + DefaultConcurrency = 4 // per-request fetch workers + DefaultGlobalConcurrency = 32 // process-wide in-flight fetch cap + DefaultMaxImageMegapixels = 100 // header-decoded image pixel cap (all accepted image formats) +) + +// Config controls remote media resolution. The zero value is not usable; build +// one with ConfigFromEnv or DefaultConfig. +type Config struct { + // Enabled gates the whole feature. When false, any request carrying a + // remote http(s) media URL is rejected (inline data: URIs still work). + Enabled bool + // MaxFileBytes caps a single fetched media item (raw bytes, pre-base64). + MaxFileBytes int64 + // MaxTotalBytes caps the sum of all fetched media in one request. + MaxTotalBytes int64 + // MaxInlinedBytes caps the projected size of the inlined media once every + // data: URI has been written to every request location that references it + // (locations × data-URI size). Unlike MaxTotalBytes this counts duplicate + // targets, which multiply one fetch into many copies of the same base64 blob. + // + // Compile-time constant, deliberately not an env knob: it is protocol-derived, + // mirroring api.maxInferenceBodyBytes (the coordinator's own forwarded-body + // cap). Tuning it independently would only move where an oversized request + // fails, not whether it fails. + MaxInlinedBytes int64 + // MaxParts caps the number of remote media URLs fetched per request. + // + // Compile-time constant, deliberately not an env knob: 8 is matched to the + // provider's videos-per-request cap, so changing one side just desyncs the + // coordinator from the provider that has to accept the result. + MaxParts int + // FetchTimeout bounds a single fetch (connect + read), independent of the + // request's TTFT deadline so a slow origin fails at the coordinator rather + // than starving the provider. + FetchTimeout time.Duration + // TotalDeadline bounds the whole resolution step across all parts. + TotalDeadline time.Duration + // Concurrency is the per-request fetch worker-pool size. + // + // Compile-time constant, deliberately not an env knob: per-request fan-out is + // not a useful capacity lever (a request has at most MaxParts parts). The + // process-wide bound on outbound sockets is GlobalConcurrency, which is. + Concurrency int + // GlobalConcurrency caps in-flight fetches across ALL requests (one shared + // semaphore per Resolver) so a burst of media-heavy requests can't open an + // unbounded number of outbound sockets from the coordinator. + GlobalConcurrency int + // MaxImageMegapixels caps decoded image dimensions (width×height), checked + // from the image HEADER only (never a full decode) for every accepted format + // (JPEG/PNG/GIF/WebP/BMP). 0 disables the coordinator-side check; the + // provider's own pre-raster pixel cap still applies. + MaxImageMegapixels int + // BlocklistDomains is an optional set of lowercased hostnames to reject + // (applied to the initial host and every redirect host). Empty = no domain + // blocklist; IP-level SSRF defenses always apply regardless. + BlocklistDomains map[string]bool + // AllowPrivateIPs disables the private/loopback/link-local/metadata IP deny + // policy. Default false. Set true only in dev/tests (httptest binds 127.0.0.1). + AllowPrivateIPs bool + // AllowNonStandardPorts permits explicit ports other than 80 for HTTP and + // 443 for HTTPS. Default false: limiting public origins to standard web ports + // prevents the coordinator from becoming a public-network port scanner. Set + // true only for controlled dev/test origins. + AllowNonStandardPorts bool + // malformedEnv names every EIGENINFERENCE_MEDIA_FETCH_* variable that was SET + // but could not be parsed. The shared env helpers fall back silently on a + // parse error, which is the right call for a tuning knob and the wrong one + // for a kill switch: `ENABLED=flase` typed during an incident would fall back + // to the compiled default (true) and keep fetching. ConfigFromEnv records + // those keys here and Check reports them, so the boot fails instead. + malformedEnv []string +} + +// envBool reads a boolean env var, recording the key when it is set but +// unparseable instead of silently falling back to the compiled default. +func (c *Config) envBool(key string, fallback bool) bool { + v := strings.TrimSpace(os.Getenv(key)) + if v == "" { + return fallback + } + b, err := strconv.ParseBool(v) + if err != nil { + c.malformedEnv = append(c.malformedEnv, key) + return fallback + } + return b +} + +// envInt reads an integer env var, recording the key when it is set but +// unparseable instead of silently falling back to the compiled default. +func (c *Config) envInt(key string, fallback int) int { + v := strings.TrimSpace(os.Getenv(key)) + if v == "" { + return fallback + } + n, err := strconv.Atoi(v) + if err != nil { + c.malformedEnv = append(c.malformedEnv, key) + return fallback + } + return n +} + +// DefaultConfig returns the production defaults (feature enabled). +func DefaultConfig() Config { + return Config{ + Enabled: true, + MaxFileBytes: DefaultMaxFileBytes, + MaxTotalBytes: DefaultMaxTotalBytes, + MaxInlinedBytes: DefaultMaxInlinedBytes, + MaxParts: DefaultMaxParts, + FetchTimeout: DefaultTimeout, + TotalDeadline: DefaultTotalDeadline, + Concurrency: DefaultConcurrency, + GlobalConcurrency: DefaultGlobalConcurrency, + MaxImageMegapixels: DefaultMaxImageMegapixels, + BlocklistDomains: map[string]bool{}, + AllowPrivateIPs: false, + AllowNonStandardPorts: false, + } +} + +// ConfigFromEnv builds a Config from EIGENINFERENCE_MEDIA_FETCH_* env vars, +// falling back to DefaultConfig for anything unset. +// +// The result is deliberately NOT sanitized: it is the raw operator intent, so +// AppConfig.Check can fail the boot on a bad value instead of silently serving a +// default nobody asked for. Both failure shapes are covered — an out-of-range +// value (MAX_TOTAL_BYTES=0) trips Check's bounds, and a value that is set but +// unparseable (ENABLED=flase, TIMEOUT_MS=fast) is recorded in malformedEnv and +// trips Check too, because a silently-ignored kill switch is exactly the failure +// an operator cannot afford mid-incident. NewResolver clamps whatever reaches +// it, so a Resolver is safe either way. +func ConfigFromEnv() Config { + c := DefaultConfig() + c.Enabled = c.envBool(envEnabled, c.Enabled) + c.MaxFileBytes = int64(c.envInt(envMaxFileBytes, int(c.MaxFileBytes))) + c.MaxTotalBytes = int64(c.envInt(envMaxTotalBytes, int(c.MaxTotalBytes))) + c.FetchTimeout = time.Duration(c.envInt(envTimeoutMS, int(c.FetchTimeout/time.Millisecond))) * time.Millisecond + c.TotalDeadline = time.Duration(c.envInt(envTotalDeadline, int(c.TotalDeadline/time.Millisecond))) * time.Millisecond + c.GlobalConcurrency = c.envInt(envGlobalConc, c.GlobalConcurrency) + c.MaxImageMegapixels = c.envInt(envMaxMegapixels, c.MaxImageMegapixels) + c.BlocklistDomains = parseBlocklist(env.EnvOr(envBlocklist, "")) + c.AllowPrivateIPs = c.envBool(envAllowPrivateIP, c.AllowPrivateIPs) + c.AllowNonStandardPorts = c.envBool(envAllowOtherPorts, c.AllowNonStandardPorts) + return c +} + +// sanitized clamps nonsensical values to safe defaults so a misconfigured env +// can't disable a cap (e.g. MaxParts<=0 would otherwise admit unbounded fetches). +// MaxImageMegapixels is exempt: 0 is a meaningful "coordinator check off" value +// (the provider's own pixel cap still applies), so only negatives are clamped. +func (c Config) sanitized() Config { + if c.MaxFileBytes <= 0 { + c.MaxFileBytes = DefaultMaxFileBytes + } + if c.MaxTotalBytes <= 0 { + c.MaxTotalBytes = DefaultMaxTotalBytes + } + if c.MaxInlinedBytes <= 0 { + c.MaxInlinedBytes = DefaultMaxInlinedBytes + } + if c.MaxFileBytes > c.MaxTotalBytes { + // The aggregate per-request cap is authoritative: a larger per-file cap + // must never admit more than the operator's total budget. Clamp the file + // cap down to the total rather than weakening (raising) the total. + c.MaxFileBytes = c.MaxTotalBytes + } + if c.MaxParts <= 0 { + c.MaxParts = DefaultMaxParts + } + if c.FetchTimeout <= 0 { + c.FetchTimeout = DefaultTimeout + } + if c.TotalDeadline <= 0 { + c.TotalDeadline = DefaultTotalDeadline + } + if c.Concurrency <= 0 { + c.Concurrency = DefaultConcurrency + } + if c.GlobalConcurrency <= 0 { + c.GlobalConcurrency = DefaultGlobalConcurrency + } + if c.MaxImageMegapixels < 0 { + c.MaxImageMegapixels = DefaultMaxImageMegapixels + } + if c.BlocklistDomains == nil { + c.BlocklistDomains = map[string]bool{} + } + return c +} + +// parseBlocklist turns a comma-separated domain list into a canonicalized set. +// Entries go through the same canonicalHost normalization hostAllowed applies to +// request hosts (lowercase, UTS-46 IDNA, leading/trailing dots trimmed), so +// neither the FQDN spelling "evil.com." nor the conventional wildcard spelling +// ".evil.com" nor a Unicode homoglyph separator can store a key that never +// matches. +func parseBlocklist(csv string) map[string]bool { + out := map[string]bool{} + for _, raw := range strings.Split(csv, ",") { + if h := canonicalHost(strings.TrimSpace(raw)); h != "" { + out[h] = true + } + } + return out +} + +// Check validates the configuration, rejecting bounds that would disable a cap +// outright. sanitized() silently clamps the same fields so a running Resolver is +// always safe; Check is the loud, boot-time counterpart that makes an operator +// typo fail the process instead of quietly reverting to a default the operator +// did not ask for. +// +// AllowPrivateIPs / AllowNonStandardPorts are deliberately NOT errors: dev and +// single-host deployments legitimately set them. NewResolver logs a boot WARN +// for those instead. +func (c Config) Check() error { + // Reported first: a key that was set but unparseable means the operator asked + // for something the process did not do, which matters most for the ENABLED + // kill switch — a silent fallback there keeps fetching during an incident. + if len(c.malformedEnv) > 0 { + return fmt.Errorf("mediafetch: unparseable value(s) for %s", strings.Join(c.malformedEnv, ", ")) + } + // One row per numeric bound, so a new field is a new line rather than a new + // branch. env is empty for the fields that are compile-time constants with no + // operator-facing variable; those print without a dangling parenthetical. + for _, rule := range []struct { + field string + env string + bound string + ok bool + got any + }{ + {"MaxFileBytes", envMaxFileBytes, "> 0", c.MaxFileBytes > 0, c.MaxFileBytes}, + {"MaxTotalBytes", envMaxTotalBytes, "> 0", c.MaxTotalBytes > 0, c.MaxTotalBytes}, + {"MaxInlinedBytes", "", "> 0", c.MaxInlinedBytes > 0, c.MaxInlinedBytes}, + {"MaxParts", "", "> 0", c.MaxParts > 0, c.MaxParts}, + {"FetchTimeout", envTimeoutMS, "> 0", c.FetchTimeout > 0, c.FetchTimeout}, + {"TotalDeadline", envTotalDeadline, "> 0", c.TotalDeadline > 0, c.TotalDeadline}, + {"Concurrency", "", "> 0", c.Concurrency > 0, c.Concurrency}, + {"GlobalConcurrency", envGlobalConc, "> 0", c.GlobalConcurrency > 0, c.GlobalConcurrency}, + // >= 0, not > 0: 0 is the documented "coordinator-side pixel check off" + // value (the provider's own pre-raster cap still applies). A negative, + // though, parses fine and would be silently reverted to the default by + // sanitized() — exactly the quiet substitution Check exists to catch. + {"MaxImageMegapixels", envMaxMegapixels, ">= 0", c.MaxImageMegapixels >= 0, c.MaxImageMegapixels}, + } { + if rule.ok { + continue + } + if rule.env == "" { + return fmt.Errorf("mediafetch: %s must be %s, got %v", rule.field, rule.bound, rule.got) + } + return fmt.Errorf("mediafetch: %s must be %s (%s), got %v", rule.field, rule.bound, rule.env, rule.got) + } + // Not a per-field bound: the two caps are individually fine and only their + // ordering is wrong. + if c.MaxFileBytes > c.MaxTotalBytes { + return fmt.Errorf("mediafetch: MaxFileBytes (%d) must be <= MaxTotalBytes (%d); the aggregate per-request budget is authoritative", + c.MaxFileBytes, c.MaxTotalBytes) + } + return nil +} diff --git a/coordinator/mediafetch/config_test.go b/coordinator/mediafetch/config_test.go new file mode 100644 index 0000000000..5e7a1c1180 --- /dev/null +++ b/coordinator/mediafetch/config_test.go @@ -0,0 +1,147 @@ +package mediafetch + +import ( + "strings" + "testing" + "time" +) + +// TestConfigCheck pins the boot-time validation contract: every numeric bound +// must be positive — except MaxImageMegapixels, where 0 is the documented +// "coordinator-side check off" value and only negatives are rejected — and the +// per-file cap must fit inside the aggregate cap. sanitized() silently clamps +// the same fields, so Check is what turns an operator typo into a loud startup +// failure instead of a quiet revert to a default they did not ask for. +func TestConfigCheck(t *testing.T) { + // mutate returns the production defaults with one field broken. + mutate := func(f func(*Config)) Config { + c := DefaultConfig() + f(&c) + return c + } + // wantMsg is the precise diagnostic, not just the field name: the + // file-cap-vs-total-cap message mentions BOTH fields, so a loose field-name + // match would let a missing "MaxTotalBytes must be > 0" branch hide behind + // it. + cases := []struct { + name string + cfg Config + wantMsg string // substring the error must contain; "" = must pass + }{ + {"defaults are valid", DefaultConfig(), ""}, + {"disabled defaults are still valid", mutate(func(c *Config) { c.Enabled = false }), ""}, + {"private-IP override is a WARN, not an error", mutate(func(c *Config) { c.AllowPrivateIPs = true }), ""}, + {"nonstandard-port override is a WARN, not an error", mutate(func(c *Config) { c.AllowNonStandardPorts = true }), ""}, + {"zero MaxFileBytes", mutate(func(c *Config) { c.MaxFileBytes = 0 }), "MaxFileBytes must be > 0"}, + {"negative MaxFileBytes", mutate(func(c *Config) { c.MaxFileBytes = -1 }), "MaxFileBytes must be > 0"}, + {"zero MaxTotalBytes", mutate(func(c *Config) { c.MaxTotalBytes = 0 }), "MaxTotalBytes must be > 0"}, + {"file cap above total cap", mutate(func(c *Config) { c.MaxFileBytes = c.MaxTotalBytes + 1 }), "must be <= MaxTotalBytes"}, + {"zero MaxInlinedBytes", mutate(func(c *Config) { c.MaxInlinedBytes = 0 }), "MaxInlinedBytes must be > 0"}, + {"zero MaxParts", mutate(func(c *Config) { c.MaxParts = 0 }), "MaxParts must be > 0"}, + {"zero FetchTimeout", mutate(func(c *Config) { c.FetchTimeout = 0 }), "FetchTimeout must be > 0"}, + {"negative FetchTimeout", mutate(func(c *Config) { c.FetchTimeout = -time.Second }), "FetchTimeout must be > 0"}, + {"zero TotalDeadline", mutate(func(c *Config) { c.TotalDeadline = 0 }), "TotalDeadline must be > 0"}, + {"zero Concurrency", mutate(func(c *Config) { c.Concurrency = 0 }), "Concurrency must be > 0"}, + {"zero GlobalConcurrency", mutate(func(c *Config) { c.GlobalConcurrency = 0 }), "GlobalConcurrency must be > 0"}, + // A negative megapixel cap parses fine and sanitized() would silently + // restore the default, so Check must reject it — but 0 is the documented + // "coordinator-side pixel check off" value and must stay valid. + {"negative MaxImageMegapixels", mutate(func(c *Config) { c.MaxImageMegapixels = -1 }), "MaxImageMegapixels must be >= 0"}, + {"negative MaxImageMegapixels names its env var", mutate(func(c *Config) { c.MaxImageMegapixels = -1 }), envMaxMegapixels}, + {"zero MaxImageMegapixels is the off switch, not an error", mutate(func(c *Config) { c.MaxImageMegapixels = 0 }), ""}, + } + for _, c := range cases { + err := c.cfg.Check() + switch { + case c.wantMsg == "" && err != nil: + t.Errorf("%s: Check() = %v, want nil", c.name, err) + case c.wantMsg != "" && err == nil: + t.Errorf("%s: Check() = nil, want an error containing %q", c.name, c.wantMsg) + case c.wantMsg != "" && !strings.Contains(err.Error(), c.wantMsg): + t.Errorf("%s: Check() = %v, want the error to contain %q", c.name, err, c.wantMsg) + } + } +} + +// TestParseBlocklistCanonicalizesEntries covers the leading-dot wildcard +// spelling. ".evil.com" is the conventional way operators write "this domain +// and everything under it"; trimming only the trailing dot stored a key +// hostAllowed could never match (it would need a literal "..evil.com" suffix), +// silently disabling the entry. Reverting the leading-dot trim flips both +// dotted-entry rows below to allowed. +func TestParseBlocklistCanonicalizesEntries(t *testing.T) { + cases := []struct { + name string + entry string + }{ + {"bare domain", "evil.com"}, + {"leading-dot wildcard spelling", ".evil.com"}, + {"trailing FQDN dot", "evil.com."}, + {"both ends dotted", ".evil.com."}, + {"uppercase with surrounding space", " EVIL.COM "}, + {"unicode separator", "evil\u3002com"}, + } + for _, c := range cases { + bl := parseBlocklist(c.entry) + if !bl["evil.com"] { + t.Errorf("%s: parseBlocklist(%q) = %v, want the canonical key evil.com", c.name, c.entry, bl) + continue + } + for _, host := range []string{"evil.com", "img.evil.com"} { + if err := hostAllowed(host, bl); err == nil { + t.Errorf("%s: entry %q must block %q", c.name, c.entry, host) + } + } + if err := hostAllowed("notevil.com", bl); err != nil { + t.Errorf("%s: entry %q must not block notevil.com: %v", c.name, c.entry, err) + } + } + + // A list of only separators/whitespace must not store an empty key — an + // empty key would suffix-match every host and black-hole all media. + for _, csv := range []string{"", " , , ", ".", "..", " . "} { + if bl := parseBlocklist(csv); len(bl) != 0 { + t.Errorf("parseBlocklist(%q) = %v, want an empty set", csv, bl) + } + } +} + +// TestConfigFromEnvRejectsMalformedValues pins the incident-rollback contract: +// a variable that is SET but unparseable must fail Check, not silently fall back +// to the compiled default. `ENABLED=flase` typed during an incident previously +// left the feature ON with no error and no warning anywhere. +func TestConfigFromEnvRejectsMalformedValues(t *testing.T) { + for _, tc := range []struct { + name, key, value string + }{ + {"enabled typo", envEnabled, "flase"}, + {"allow private ips typo", envAllowPrivateIP, "yes-please"}, + {"nonstandard ports typo", envAllowOtherPorts, "1.0"}, + {"global concurrency not a number", envGlobalConc, "eight"}, + {"timeout not a number", envTimeoutMS, "fast"}, + {"max file bytes not a number", envMaxFileBytes, "8MiB"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv(tc.key, tc.value) + c := ConfigFromEnv() + err := c.Check() + if err == nil { + t.Fatalf("Check() = nil for %s=%q; a malformed value must fail boot", tc.key, tc.value) + } + if !strings.Contains(err.Error(), tc.key) { + t.Errorf("Check() = %v, want the error to name %s", err, tc.key) + } + }) + } + + // A well-formed value must still pass, and the recorded-key list must not + // leak across reads. + t.Setenv(envEnabled, "false") + c := ConfigFromEnv() + if err := c.Check(); err != nil { + t.Fatalf("Check() = %v for a well-formed config", err) + } + if c.Enabled { + t.Error("ENABLED=false must disable the feature") + } +} diff --git a/coordinator/mediafetch/fetch.go b/coordinator/mediafetch/fetch.go new file mode 100644 index 0000000000..fedac43fdb --- /dev/null +++ b/coordinator/mediafetch/fetch.go @@ -0,0 +1,259 @@ +package mediafetch + +// fetch.go owns the hardened outbound HTTP path: a dedicated one-shot client +// whose every dial runs the SSRF Control hook (ssrf.go), redirect re-validation, +// size-capped reads, and the typed error classification the API layer maps to +// consumer-facing responses. + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +// maxRedirects bounds redirect-chain depth. Every hop is re-validated (scheme, +// userinfo, blocklist) and every dial is IP-checked by the Control hook, so this +// only needs to stop loops / unbounded chains. +const maxRedirects = 3 + +// newHTTPClient builds the dedicated, hardened http.Client used for media +// fetches. It is isolated from the coordinator's other outbound clients (small +// connection pool) so a media-fetch storm can't starve provider/registry traffic. +func newHTTPClient(cfg Config) *http.Client { + dialer := &net.Dialer{ + Timeout: cfg.FetchTimeout, + KeepAlive: -1, // no keep-alive: each fetch is one-shot + Control: dialControl(cfg.AllowPrivateIPs), + } + transport := &http.Transport{ + DialContext: dialer.DialContext, + DisableKeepAlives: true, + DisableCompression: true, // never auto-inflate: defeats gzip/zip bombs + ForceAttemptHTTP2: false, + MaxIdleConns: cfg.GlobalConcurrency, + // PROCESS-WIDE, not per-request: this client is built once per Resolver, + // so MaxConnsPerHost bounds every concurrent fetch to a given origin + // across ALL requests. Concurrency is the per-REQUEST worker-pool size + // (4) — using it here would serialize a media-heavy fleet into waves of + // four sockets per CDN, and because DisableKeepAlives means no connection + // is ever reused, the queue wait is charged against FetchTimeout and + // healthy origins start returning spurious media_fetch_timeout. The + // process-wide socket bound belongs to GlobalConcurrency, which is + // exactly what globalSem already admits. + MaxConnsPerHost: cfg.GlobalConcurrency, + // Headers are read before any body budget applies, and Go's default cap is + // 10 MiB per connection — with GlobalConcurrency slots an attacker-owned + // origin could force GlobalConcurrency x 10 MiB of header buffering while + // every body stayed tightly capped. No legitimate media origin needs more + // than a few KiB of headers. + MaxResponseHeaderBytes: 64 << 10, + TLSHandshakeTimeout: cfg.FetchTimeout, + ResponseHeaderTimeout: cfg.FetchTimeout, + ExpectContinueTimeout: time.Second, + } + return &http.Client{ + Transport: transport, + Timeout: cfg.FetchTimeout, + CheckRedirect: redirectGuard(cfg), + } +} + +// redirectGuard validates each redirect hop: scheme allowlist, no transport +// downgrade, no embedded credentials, and the optional domain blocklist. The IP +// of every hop is still validated independently by the dialer Control hook. +// Depth is capped. +func redirectGuard(cfg Config) func(req *http.Request, via []*http.Request) error { + return func(req *http.Request, via []*http.Request) error { + // Strip the Referer Go's client auto-populates from the previous hop. + // The previous URL can be a presigned S3/R2/GCS link whose query string + // carries the signature; without this a cross-host redirect would leak + // that signed URL to the redirect target, defeating the URL-secrecy the + // rest of this package preserves. + req.Header.Del("Referer") + if len(via) >= maxRedirects { + return fmt.Errorf("%w: too many redirects (>%d)", errBlockedHost, maxRedirects) + } + // Refuse an https -> http downgrade. Validating each hop independently + // against the scheme allowlist would accept it: both schemes are allowed + // in isolation. But a caller who supplied an https URL is owed transport + // confidentiality and integrity for the whole chain — otherwise a + // redirect's signed query crosses the network in plaintext, and an + // on-path party can swap the image before it is inlined into the + // (encrypted) provider request. A plain http URL supplied deliberately + // still works; only the downgrade is refused. + if strings.EqualFold(req.URL.Scheme, "http") { + for _, prev := range via { + if strings.EqualFold(prev.URL.Scheme, "https") { + return fmt.Errorf("%w: https to http redirect downgrade", errBlockedScheme) + } + } + } + return validateURL(req.URL, cfg) + } +} + +// validateURL enforces the scheme + port allowlists, rejects embedded userinfo, +// and applies the domain blocklist. IP-level SSRF is enforced at dial time. +func validateURL(u *url.URL, cfg Config) error { + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return fmt.Errorf("%w: %q (only http/https)", errBlockedScheme, u.Scheme) + } + if u.User != nil { + return fmt.Errorf("%w: embedded credentials are not allowed", errBlockedHost) + } + if u.Host == "" { + return fmt.Errorf("%w: empty host", errBlockedHost) + } + if !cfg.AllowNonStandardPorts { + port := u.Port() + if (scheme == "http" && port != "" && port != "80") || + (scheme == "https" && port != "" && port != "443") { + return fmt.Errorf("%w: non-standard %s port %q is not allowed", errBlockedHost, scheme, port) + } + } + return hostAllowed(u.Host, cfg.BlocklistDomains) +} + +// isRemoteMediaURL reports whether s is an http(s) URL (as opposed to an inline +// data: URI, which is passed through untouched, or some other scheme). +func isRemoteMediaURL(s string) bool { + t := strings.TrimSpace(s) + if len(t) < 7 { + return false + } + lower := strings.ToLower(t) + return strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") +} + +// fetchOne downloads one media URL under the SSRF policy and size cap, validates +// the content structurally (allowlist, declared-kind match, pixel cap), and +// returns the bytes plus sniffed MIME type. The per-fetch timeout is applied via +// ctx so it is independent of the request TTFT deadline. +func (r *Resolver) fetchOne(ctx context.Context, ref mediaRef, maxBytes int64, totalBudget *byteBudget) (*fetchedMedia, error) { + u, err := url.Parse(strings.TrimSpace(ref.url)) + if err != nil { + return nil, &Error{Status: http.StatusBadRequest, Code: "invalid_media_url", + Public: "a media URL could not be parsed", Internal: "URL parse failed"} + } + if err := validateURL(u, r.cfg); err != nil { + return nil, classifyURLError(err) + } + + fetchCtx, cancel := context.WithTimeout(ctx, r.cfg.FetchTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(fetchCtx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, &Error{Status: http.StatusBadRequest, Code: "invalid_media_url", + Public: "a media URL could not be requested", Internal: "request construction failed"} + } + req.Header.Set("Accept", "image/*,video/*") + req.Header.Set("Accept-Encoding", "identity") // belt-and-suspenders with DisableCompression + req.Header.Set("User-Agent", "darkbloom-coordinator-mediafetch") + + resp, err := r.client.Do(req) + if err != nil { + return nil, classifyFetchError(err) + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, &Error{Status: http.StatusBadGateway, Code: "media_fetch_failed", + Public: "a media URL could not be retrieved", + Internal: fmt.Sprintf("upstream returned HTTP %d", resp.StatusCode)} + } + + // Pre-check the declared length to reject obvious oversize before reading. + if resp.ContentLength > maxBytes { + return nil, &Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: "a media file exceeds the maximum allowed size", + Internal: fmt.Sprintf("Content-Length %d > cap %d", resp.ContentLength, maxBytes)} + } + + // Read at most maxBytes+1 so we can detect overflow without buffering more — + // the LimitReader (not the header) is the enforced cap. + // Layer the per-file reader under the SHARED per-request budget. The shared + // budget allows only MaxTotalBytes+1 bytes across all concurrent fetches, so + // four 8 MiB responses can never transiently retain 32 MiB before the 10 MiB + // aggregate check notices. The +1 byte distinguishes exactly-at-cap EOF from + // overflow without buffering more than one byte past the aggregate limit. + data, err := io.ReadAll(totalBudget.reader(io.LimitReader(resp.Body, maxBytes+1))) + if err != nil { + if errors.Is(err, errAggregateBudgetExceeded) { + return nil, &Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: "combined media exceeds the maximum allowed size for one request", + Internal: fmt.Sprintf("aggregate body exceeded cap %d", totalBudget.limit)} + } + return nil, classifyFetchError(err) + } + if int64(len(data)) > maxBytes { + return nil, &Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: "a media file exceeds the maximum allowed size", + Internal: fmt.Sprintf("response body exceeded cap %d", maxBytes)} + } + if len(data) == 0 { + return nil, &Error{Status: http.StatusBadGateway, Code: "media_fetch_failed", + Public: "a media URL returned an empty body", Internal: "upstream returned an empty body"} + } + + mime, err := r.validateFetchedMedia(ref.kind, data) + if err != nil { + return nil, err + } + return &fetchedMedia{mime: mime, data: data}, nil +} + +// classifyURLError maps a pre-flight validateURL failure to a typed Error. +func classifyURLError(err error) *Error { + switch { + case errors.Is(err, errBlockedScheme): + return &Error{Status: http.StatusBadRequest, Code: "media_invalid_scheme", + Public: "media URLs must use http or https", Internal: "URL scheme blocked"} + case errors.Is(err, errBlockedHost): + return &Error{Status: http.StatusForbidden, Code: "media_blocked", + Public: "a media URL host is not allowed", Internal: "URL host or port blocked"} + default: + return &Error{Status: http.StatusBadRequest, Code: "invalid_media_url", + Public: "a media URL is invalid", Internal: "URL validation failed"} + } +} + +// classifyFetchError maps a client.Do / read failure to a typed Error: SSRF +// blocks → 403, timeouts → 408, everything else → 502. NEITHER the consumer +// message NOR Internal may echo the URL, host, query or the wrapped error: +// presigned media URLs carry secrets and callers log Error(). Internal is a +// fixed, non-sensitive cause string — keep it that way. +func classifyFetchError(err error) error { + switch { + case errors.Is(err, context.Canceled): + return context.Canceled + case errors.Is(err, errBlockedIP): + return &Error{Status: http.StatusForbidden, Code: "media_blocked", + Public: "a media URL resolves to a disallowed address", Internal: "resolved address blocked"} + case errors.Is(err, errBlockedScheme): + return &Error{Status: http.StatusBadRequest, Code: "media_invalid_scheme", + Public: "media URLs must use http or https", Internal: "redirect scheme blocked"} + case errors.Is(err, errBlockedHost): + return &Error{Status: http.StatusForbidden, Code: "media_blocked", + Public: "a media URL host is not allowed", Internal: "redirect host or port blocked"} + case errors.Is(err, context.DeadlineExceeded) || isTimeout(err): + return &Error{Status: http.StatusRequestTimeout, Code: "media_fetch_timeout", + Public: "a media URL took too long to fetch", Internal: "fetch deadline exceeded"} + default: + return &Error{Status: http.StatusBadGateway, Code: "media_fetch_failed", + Public: "a media URL could not be retrieved", Internal: "network request failed"} + } +} + +// isTimeout unwraps net.Error timeouts (e.g. *url.Error wrapping a dial timeout). +func isTimeout(err error) bool { + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} diff --git a/coordinator/mediafetch/resolver.go b/coordinator/mediafetch/resolver.go new file mode 100644 index 0000000000..243b00da91 --- /dev/null +++ b/coordinator/mediafetch/resolver.go @@ -0,0 +1,466 @@ +package mediafetch + +// resolver.go is the package entry point: Resolver walks a parsed OpenAI-style +// request for remote image_url/video_url references, fetches them under the +// SSRF/size/format policy (fetch.go, sniff.go, ssrf.go), and rewrites each URL +// in place as an inline base64 data: URI. All-or-nothing: on any failure nothing +// is mutated and a typed *Error is returned for the API layer to surface. + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math" + "net/http" + "net/url" + "strings" + "sync" + + "github.com/eigeninference/d-inference/coordinator/saferun" +) + +// Error is a typed resolution failure carrying the HTTP status + OpenAI-style +// error code to return to the consumer, a Public message, and a non-sensitive +// Internal diagnostic. Internal MUST NOT contain the request URL, host, query, +// fragment, credentials, or wrapped errors that may reproduce them: presigned +// media URLs commonly carry secrets and Error() may be logged by callers. +type Error struct { + Status int + Code string + Public string + Internal string +} + +func (e *Error) Error() string { + if e.Internal != "" { + return fmt.Sprintf("mediafetch: %s (%s): %s", e.Code, e.Public, e.Internal) + } + return fmt.Sprintf("mediafetch: %s (%s)", e.Code, e.Public) +} + +// Result reports what a Resolve call did, for metrics. +type Result struct { + Changed bool // at least one URL was inlined (rawBody must be re-marshaled) + Count int // number of media items fetched + Bytes int64 // total raw bytes fetched +} + +// Resolver fetches remote media URLs into inline data: URIs under the SSRF and +// size policy in cfg. It is safe for concurrent use; construct once and reuse — +// the process-wide fetch semaphore lives on the instance. +type Resolver struct { + cfg Config + client *http.Client + logger *slog.Logger + globalSem chan struct{} // caps in-flight fetches across ALL requests +} + +// NewResolver builds a Resolver with a dedicated hardened http.Client. logger +// may be nil (a no-op logger is used). cfg is clamped to safe bounds, so a +// programmatically supplied Config (api.ServerConfig.MediaFetch) can never +// disable a cap — the env path fails boot on the same values via Config.Check, +// but a direct embedder gets defense in depth plus a WARN naming the problem. +func NewResolver(cfg Config, logger *slog.Logger) *Resolver { + if logger == nil { + logger = slog.New(slog.DiscardHandler) + } + if err := cfg.Check(); err != nil { + logger.Warn("media fetch config clamped to defaults", "detail", err.Error()) + } + cfg = cfg.sanitized() + if cfg.AllowPrivateIPs || cfg.AllowNonStandardPorts { + // These are dev/test escape hatches: together they turn the coordinator + // into a LAN/port scanner reachable from any consumer prompt. Config.Check + // deliberately does not reject them (single-host deployments need them), + // so a boot WARN is the only signal an operator gets that a production + // process is running without the full SSRF policy. + logger.Warn("media fetch SSRF override enabled", + "allow_private_ips", cfg.AllowPrivateIPs, + "allow_nonstandard_ports", cfg.AllowNonStandardPorts, + ) + } + return &Resolver{ + cfg: cfg, + client: newHTTPClient(cfg), + logger: logger, + globalSem: make(chan struct{}, cfg.GlobalConcurrency), + } +} + +// Enabled reports whether remote-media fetching is turned on. +// +// This is the value read at construction, NOT a live re-read. An earlier +// revision called env.EnvBool here on every request and advertised the kill +// switch as redeploy-free, which was wrong: os.Getenv returns the process +// environment captured at exec, so editing /etc/d-inference/env or reloading +// the unit changes nothing for a running coordinator. Flipping the switch +// requires recreating the process — see the rollback section of +// docs/operations/coordinator-deploy.md. +func (r *Resolver) Enabled() bool { return r.cfg.Enabled } + +// mediaRef points at one resolvable URL inside the parsed request: the map that +// holds it, the key to overwrite with the data: URI, and the declared kind the +// fetched bytes must match (image_url → image, video_url → video). +type mediaRef struct { + set map[string]any + key string + url string + kind mediaKind +} + +// mediaFetch groups every mutable request location that references the same +// trimmed remote URL. The URL is downloaded once, then one data: URI is written +// to every target. A URL reused across image_url and video_url is rejected before +// network I/O because one byte stream cannot satisfy both declared media kinds. +type mediaFetch struct { + request mediaRef + targets []mediaRef +} + +// Resolve walks an OpenAI-compatible request body (parsed JSON) for image_url / +// video_url content parts whose value is an http(s) URL, fetches each one under +// the SSRF + size + format policy, and replaces it in place with an inline data: +// URI. parsed is mutated; the caller must re-marshal it into rawBody when +// Changed. +// +// Resolve never fetches for a disabled feature: it returns a 400 Error if a +// remote URL is present while disabled (defense in depth — the API layer gates +// this case pre-reservation). Inline data: URIs and text-only requests are +// no-ops. +func (r *Resolver) Resolve(ctx context.Context, parsed map[string]any) (Result, error) { + refs := collectMediaRefs(parsed) + if len(refs) == 0 { + return Result{}, nil + } + if !r.Enabled() { // live kill switch, same gate the API layer consults + return Result{}, &Error{Status: http.StatusBadRequest, Code: "remote_media_disabled", + Public: "remote media URLs are not enabled on this endpoint; send media as an inline base64 data: URI", + Internal: "feature disabled via config"} + } + // Cap request locations BEFORE URL deduplication. Each target is rewritten + // with the full base64 data URI, so allowing unbounded duplicate targets would + // turn one bounded fetch into an oversized allocation/marshal DoS. + if len(refs) > r.cfg.MaxParts { + return Result{}, &Error{Status: http.StatusBadRequest, Code: "too_many_media_parts", + Public: fmt.Sprintf("too many remote media parts (%d); the maximum is %d", len(refs), r.cfg.MaxParts), + Internal: fmt.Sprintf("%d remote targets > MaxParts %d", len(refs), r.cfg.MaxParts)} + } + fetches, err := groupMediaRefs(refs) + if err != nil { + return Result{}, err + } + + // Bound the whole resolution step (independent of the request TTFT deadline). + resolveCtx, cancel := context.WithTimeout(ctx, r.cfg.TotalDeadline) + defer cancel() + + fetched, totalBytes, err := r.fetchAll(resolveCtx, fetches) + if err != nil { + return Result{}, err + } + + // Duplicate targets multiply one fetch into many inlined copies: the byte + // caps bound what is FETCHED, not what is written back. Eight parts sharing + // one in-budget URL inline eight copies of the same base64 blob, so project + // the post-inline size BEFORE mutating anything — otherwise the coordinator + // builds (and the marshaler retains) a body the API layer can only discard + // afterwards. Each data: URI is built once here and reused for the writes. + dataURIs := make([]string, len(fetches)) + for i := range fetches { + dataURIs[i] = toDataURI(fetched[i]) + } + if projected := projectedInlinedBytes(fetches, dataURIs); projected > r.cfg.MaxInlinedBytes { + return Result{}, &Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: "the request exceeds the size limit once remote media is inlined; use smaller media or fewer attachments", + Internal: fmt.Sprintf("projected inlined %d > MaxInlinedBytes %d", projected, r.cfg.MaxInlinedBytes)} + } + + // All fetches succeeded and fit — apply mutations atomically. + for i, fetch := range fetches { + for _, target := range fetch.targets { + target.set[target.key] = dataURIs[i] + } + } + return Result{Changed: true, Count: len(fetches), Bytes: totalBytes}, nil +} + +// projectedInlinedBytes reports how many bytes the inlined data: URIs occupy in +// the rewritten body: each fetch's URI counts once per request location that +// references it. MaxTotalBytes cannot express this — it bounds the raw bytes +// FETCHED, and a duplicated URL is fetched once but written back N times. +// Accumulation saturates rather than wrapping: a wrapped negative total would +// silently disable the very cap this feeds. +func projectedInlinedBytes(fetches []mediaFetch, dataURIs []string) int64 { + var total int64 + for i, fetch := range fetches { + size := int64(len(dataURIs[i])) + for range fetch.targets { + if size > math.MaxInt64-total { + return math.MaxInt64 + } + total += size + } + } + return total +} + +func groupMediaRefs(refs []mediaRef) ([]mediaFetch, error) { + fetches := make([]mediaFetch, 0, len(refs)) + byKey := make(map[string]int, len(refs)) + for _, ref := range refs { + key, err := mediaFetchKey(ref.url) + if err != nil { + return nil, err + } + if i, exists := byKey[key]; exists { + if fetches[i].request.kind != ref.kind { + return nil, &Error{Status: http.StatusBadRequest, Code: "media_kind_mismatch", + Public: "the same remote media URL cannot be used as both image_url and video_url", + Internal: "one URL declared with conflicting media kinds"} + } + fetches[i].targets = append(fetches[i].targets, ref) + continue + } + byKey[key] = len(fetches) + fetches = append(fetches, mediaFetch{request: ref, targets: []mediaRef{ref}}) + } + return fetches, nil +} + +// mediaFetchKey returns the deduplication key for a media URL: two request +// locations share one fetch only when their keys match. It is ONLY a key — the +// URL requested is always the string the consumer sent, byte for byte. +// +// Normalized: the fragment (never put on the wire) and scheme/host case (both +// case-insensitive per RFC 3986, IPv6 hex included). Nothing else — in +// particular an explicit :80/:443 stays, because a presigned signature can cover +// the exact host:port and rewriting it turns a valid link into an upstream auth +// error. Cost: `https://h/a` and `https://h:443/a` are fetched twice; both still +// count against every byte cap, so nothing is bypassed. +func mediaFetchKey(raw string) (string, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return "", &Error{Status: http.StatusBadRequest, Code: "invalid_media_url", + Public: "a media URL could not be parsed", Internal: "URL parse failed"} + } + u.Scheme = strings.ToLower(u.Scheme) + u.Host = strings.ToLower(u.Host) // host, port digits and bracketed IPv6 hex + u.Fragment = "" + return u.String(), nil +} + +// fetchAll fetches every ref with bounded concurrency (per-request worker cap + +// the process-wide semaphore), enforcing the per-request aggregate byte cap. On +// the first error all remaining work is cancelled and the error is returned +// (atomic: the caller inlines nothing on failure). +func (r *Resolver) fetchAll(ctx context.Context, fetches []mediaFetch) ([]*fetchedMedia, int64, error) { + out := make([]*fetchedMedia, len(fetches)) + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + var ( + mu sync.Mutex + firstErr error + totalBytes int64 + ) + fail := func(e error) { + mu.Lock() + if firstErr == nil { + firstErr = e + cancel() // stop the other in-flight fetches + } + mu.Unlock() + } + // ctxCancelled records a slot/semaphore wait that ended by cancellation. If a + // sibling already set firstErr, fail() is a no-op and the real error is + // preserved; otherwise (parent deadline / client disconnect) the timeout error + // stands, and out[i] is never left nil for Resolve to dereference in toDataURI. + ctxCancelled := func() { + if errors.Is(ctx.Err(), context.Canceled) { + fail(context.Canceled) + return + } + fail(&Error{Status: http.StatusRequestTimeout, Code: "media_fetch_timeout", + Public: "media fetching did not complete in time", Internal: ctx.Err().Error()}) + } + + sem := make(chan struct{}, r.cfg.Concurrency) + totalBudget := newByteBudget(r.cfg.MaxTotalBytes) + var wg sync.WaitGroup + for i, fetch := range fetches { + wg.Add(1) + go func(i int, fetch mediaFetch) { + defer wg.Done() + // A panic on THIS goroutine kills the whole process: net/http only + // recovers panics raised on the handler goroutine, never on one + // spawned from it, and everything below runs the outbound HTTP/TLS + // client and the image-header parsers over attacker-chosen bytes. + // One malformed response must not take down every in-flight request + // from every consumer. + // + // Defers run LIFO: saferun.Recover (registered last, so it runs + // first) consumes the panic, logs it with a stack trace and fires + // the panic metric; the guard below then turns the aborted worker + // into a typed failure. The guard keys off "no result stored", which + // also backstops any future return path that forgets to fail(): a + // worker that leaves without storing a result MUST leave firstErr + // set, or Resolve would dereference a nil out[i]. fail() keeps the + // first error, so paths that already failed are unaffected. + defer func() { + if out[i] == nil { + fail(&Error{Status: http.StatusBadGateway, Code: "media_fetch_failed", + Public: "failed to fetch remote media", Internal: "panic during media fetch"}) + } + }() + defer saferun.Recover(r.logger, "mediafetch.fetchOne") + // Per-request worker slot. + select { + case sem <- struct{}{}: + defer func() { <-sem }() + case <-ctx.Done(): + ctxCancelled() + return + } + // Process-wide fetch slot: bounds coordinator-wide outbound sockets + // under a burst of media-heavy requests. + select { + case r.globalSem <- struct{}{}: + defer func() { <-r.globalSem }() + case <-ctx.Done(): + ctxCancelled() + return + } + + m, e := r.fetchOne(ctx, fetch.request, r.cfg.MaxFileBytes, totalBudget) + if e != nil { + var me *Error + if errors.As(e, &me) { + r.logger.Warn("media fetch rejected", "code", me.Code, "status", me.Status) + } else { + r.logger.Warn("media fetch rejected", "code", "unknown") + } + fail(e) + return + } + + mu.Lock() + totalBytes += int64(len(m.data)) + total := totalBytes // snapshot under lock; other goroutines keep writing totalBytes + mu.Unlock() + if total > r.cfg.MaxTotalBytes { // invariant backstop; budget.go enforces during reads + fail(&Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: "combined media exceeds the maximum allowed size for one request", + Internal: fmt.Sprintf("aggregate %d > MaxTotalBytes %d", total, r.cfg.MaxTotalBytes)}) + return + } + out[i] = m + }(i, fetch) + } + wg.Wait() + + if firstErr != nil { + return nil, 0, firstErr + } + return out, totalBytes, nil +} + +// HasRemoteMedia reports whether parsed carries any http(s) media URL this +// package would fetch. Used by the API layer's sealed-request gate, which must +// reject (never fetch) such a request without touching the network. +func HasRemoteMedia(parsed map[string]any) bool { + return len(collectMediaRefs(parsed)) > 0 +} + +// IsFetchableRemotePart reports whether pm is an OpenAI image_url/video_url part +// carrying an http(s) URL in a shape Resolve can mutate. It deliberately judges +// the part's shape/location, not just its URL string: an unsupported Anthropic +// source block remains unsupported even when another OpenAI part uses the same +// URL. +func IsFetchableRemotePart(pm map[string]any) bool { + typ, _ := pm["type"].(string) + key, kind, ok := mediaKeyForType(typ) + if !ok { + return false + } + _, ok = mediaRefFromPart(pm, key, kind) + return ok +} + +// collectMediaRefs walks messages[].content[] for OpenAI-shaped image_url / +// video_url parts whose URL is http(s), returning a mutable handle to each. Both +// the object form ({"image_url":{"url":…}}) and the bare-string form +// ({"image_url":"…"}) are handled. Inline data: URIs and non-http schemes are +// skipped. +// +// Scope: only the OpenAI image_url/video_url shapes are matched — these are the +// shapes the Swift provider consumes as media. Anthropic-native blocks on +// /v1/messages ({"type":"image","source":{"type":"url",…}}) are NOT collected; +// Anthropic source-URL inlining is out of scope (the provider does not decode +// that shape either — tracked as a follow-up). The Responses API `input` surface +// is likewise not walked; a media-bearing Responses request is rejected by +// visionToolsFailFast in the handler before dispatch. +func collectMediaRefs(parsed map[string]any) []mediaRef { + var refs []mediaRef + messages, ok := parsed["messages"].([]any) + if !ok { + return nil + } + for _, m := range messages { + mm, ok := m.(map[string]any) + if !ok { + continue + } + parts, ok := mm["content"].([]any) + if !ok { + continue + } + for _, part := range parts { + pm, ok := part.(map[string]any) + if !ok { + continue + } + typ, _ := pm["type"].(string) + key, kind, ok := mediaKeyForType(typ) + if !ok { + continue + } + if ref, ok := mediaRefFromPart(pm, key, kind); ok { + refs = append(refs, ref) + } + } + } + return refs +} + +// mediaKeyForType maps a content-part type to the part field that carries its +// URL and the kind the fetched bytes must match. Only the types the Swift +// provider actually consumes as media (image_url/video_url → .imageURL/.videoURL) +// are resolved. +func mediaKeyForType(typ string) (key string, kind mediaKind, ok bool) { + switch typ { + case "image_url": + return "image_url", kindImage, true + case "video_url": + return "video_url", kindVideo, true + default: + return "", "", false + } +} + +// mediaRefFromPart extracts a mutable handle to the http(s) URL inside a part's +// media field, handling both the object ({"url":…}) and bare-string forms. +func mediaRefFromPart(pm map[string]any, key string, kind mediaKind) (mediaRef, bool) { + switch v := pm[key].(type) { + case string: + if isRemoteMediaURL(v) { + return mediaRef{set: pm, key: key, url: v, kind: kind}, true + } + case map[string]any: + if u, ok := v["url"].(string); ok && isRemoteMediaURL(u) { + return mediaRef{set: v, key: "url", url: u, kind: kind}, true + } + } + return mediaRef{}, false +} diff --git a/coordinator/mediafetch/resolver_test.go b/coordinator/mediafetch/resolver_test.go new file mode 100644 index 0000000000..2f7a878a44 --- /dev/null +++ b/coordinator/mediafetch/resolver_test.go @@ -0,0 +1,1214 @@ +package mediafetch + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/saferun" +) + +// --- helpers --------------------------------------------------------------- + +// pngPrefix returns `total` bytes whose PREFIX sniffs as image/png. Only usable +// in tests that fail before content validation (size caps, timeouts, SSRF) — +// the zero-padded body does not survive the pixel gate's header parse. Success +// paths must serve validPNG(t) (sniff_test.go) instead. +func pngPrefix(total int) []byte { + sig := []byte("\x89PNG\r\n\x1a\n") + if total < len(sig) { + total = len(sig) + } + b := make([]byte, total) + copy(b, sig) + return b +} + +// devConfig returns a Config usable against httptest (loopback) servers. +func devConfig() Config { + c := DefaultConfig() + c.AllowPrivateIPs = true // httptest binds 127.0.0.1 + c.AllowNonStandardPorts = true // httptest chooses an ephemeral port + return c +} + +// chatBody builds a parsed chat-completions body with the given user content parts. +func chatBody(parts ...map[string]any) map[string]any { + anyParts := make([]any, len(parts)) + for i, p := range parts { + anyParts[i] = p + } + return map[string]any{ + "model": "test", + "messages": []any{ + map[string]any{"role": "user", "content": anyParts}, + }, + } +} + +func imagePartObj(url string) map[string]any { + return map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}} +} + +func imagePartStr(url string) map[string]any { + return map[string]any{"type": "image_url", "image_url": url} +} + +func videoPartObj(url string) map[string]any { + return map[string]any{"type": "video_url", "video_url": map[string]any{"url": url}} +} + +// firstImageURL extracts messages[0].content[idx].image_url(.url) as a string. +func firstImageURL(t *testing.T, parsed map[string]any, idx int) string { + t.Helper() + parts := parsed["messages"].([]any)[0].(map[string]any)["content"].([]any) + switch v := parts[idx].(map[string]any)["image_url"].(type) { + case string: + return v + case map[string]any: + s, _ := v["url"].(string) + return s + } + return "" +} + +func serveBytes(data []byte) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write(data) + })) +} + +// --- tests ----------------------------------------------------------------- + +func TestResolveSuccessObjectForm(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody( + map[string]any{"type": "text", "text": "what is this?"}, + imagePartObj(srv.URL+"/cat.png"), + ) + res, err := r.Resolve(context.Background(), parsed) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if !res.Changed || res.Count != 1 { + t.Fatalf("Result = %+v, want Changed=true Count=1", res) + } + if got := firstImageURL(t, parsed, 1); !strings.HasPrefix(got, "data:image/png;base64,") { + t.Errorf("image not inlined; url = %.40q", got) + } +} + +func TestResolveSuccessStringForm(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody(imagePartStr(srv.URL + "/cat.png")) + if _, err := r.Resolve(context.Background(), parsed); err != nil { + t.Fatalf("Resolve: %v", err) + } + if got := firstImageURL(t, parsed, 0); !strings.HasPrefix(got, "data:image/png;base64,") { + t.Errorf("string-form image not inlined; url = %.40q", got) + } +} + +func TestResolveVideoMP4(t *testing.T) { + srv := serveBytes(mp4Bytes(64)) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody(videoPartObj(srv.URL + "/clip.mp4")) + if _, err := r.Resolve(context.Background(), parsed); err != nil { + t.Fatalf("Resolve: %v", err) + } + parts := parsed["messages"].([]any)[0].(map[string]any)["content"].([]any) + got, _ := parts[0].(map[string]any)["video_url"].(map[string]any)["url"].(string) + if !strings.HasPrefix(got, "data:video/mp4;base64,") { + t.Errorf("video not inlined; url = %.40q", got) + } +} + +func TestResolveVideoWebMRejected(t *testing.T) { + // AVFoundation (the provider's video decoder) cannot decode WebM — inlining + // it would waste a dispatch just to 400 at the provider, so the coordinator + // rejects it up front. + srv := serveBytes([]byte("\x1aE\xdf\xa3................")) + defer srv.Close() + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(videoPartObj(srv.URL+"/clip.webm")), r, http.StatusBadRequest, "media_invalid_type") +} + +func TestResolveKindMismatch(t *testing.T) { + srv := serveBytes(mp4Bytes(64)) // an image_url part pointing at a video + defer srv.Close() + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/sneaky")), r, http.StatusBadRequest, "media_kind_mismatch") +} + +func TestResolvePixelBombRejected(t *testing.T) { + srv := serveBytes(bombPNG(t)) // tiny file, 400 MP declared dimensions + defer srv.Close() + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/bomb.png")), r, http.StatusRequestEntityTooLarge, "media_too_large") +} + +func TestResolveMixedDataAndRemoteAndText(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + + const inlineData = "data:image/png;base64,iVBORw0KGgo=" + r := NewResolver(devConfig(), nil) + parsed := chatBody( + map[string]any{"type": "text", "text": "compare"}, + imagePartObj(inlineData), // already inline → untouched + imagePartObj(srv.URL+"/x"), // remote → fetched + ) + res, err := r.Resolve(context.Background(), parsed) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if res.Count != 1 { + t.Errorf("Count = %d, want 1 (only the remote URL)", res.Count) + } + if got := firstImageURL(t, parsed, 1); got != inlineData { + t.Errorf("inline data: URI was modified: %.40q", got) + } + if got := firstImageURL(t, parsed, 2); !strings.HasPrefix(got, "data:image/png;base64,") { + t.Errorf("remote URL not inlined: %.40q", got) + } +} + +func TestResolveTextOnlyNoOp(t *testing.T) { + r := NewResolver(devConfig(), nil) + parsed := map[string]any{"model": "test", "messages": []any{ + map[string]any{"role": "user", "content": "just text"}, + }} + res, err := r.Resolve(context.Background(), parsed) + if err != nil || res.Changed { + t.Fatalf("text-only: res=%+v err=%v, want no-op", res, err) + } +} + +func TestResolvePreservesClientCancellation(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := r.Resolve(ctx, chatBody(imagePartObj("https://example.com/cancelled.png"))) + if !errors.Is(err, context.Canceled) { + t.Fatalf("Resolve error = %v, want context.Canceled", err) + } +} + +func TestResolveMultipleImages(t *testing.T) { + img := validPNG(t) + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(img) + })) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody( + imagePartObj(srv.URL+"/1.png"), + imagePartObj(srv.URL+"/2.png"), + imagePartObj(srv.URL+"/3.png"), + ) + res, err := r.Resolve(context.Background(), parsed) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if res.Count != 3 || atomic.LoadInt32(&hits) != 3 { + t.Fatalf("Count=%d hits=%d, want 3/3", res.Count, hits) + } +} + +func TestResolveDuplicateURLFetchesOnce(t *testing.T) { + img := validPNG(t) + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(img) + })) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody( + imagePartObj(srv.URL+"/same.png#first"), + imagePartStr(" "+srv.URL+"/same.png#second "), + imagePartObj(srv.URL+"/same.png"), + ) + res, err := r.Resolve(context.Background(), parsed) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if res.Count != 1 || res.Bytes != int64(len(img)) || atomic.LoadInt32(&hits) != 1 { + t.Fatalf("Count=%d Bytes=%d hits=%d, want 1/%d/1", res.Count, res.Bytes, hits, len(img)) + } + want := firstImageURL(t, parsed, 0) + for i := 0; i < 3; i++ { + if got := firstImageURL(t, parsed, i); got != want || !strings.HasPrefix(got, "data:image/png;base64,") { + t.Errorf("part %d = %.40q, want shared inlined data URI", i, got) + } + } +} + +func TestResolveDuplicateTargetsStillRespectPartCap(t *testing.T) { + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(validPNG(t)) + })) + defer srv.Close() + + cfg := devConfig() + cfg.MaxParts = 2 + r := NewResolver(cfg, nil) + parsed := chatBody( + imagePartObj(srv.URL+"/same.png#one"), + imagePartObj(srv.URL+"/same.png#two"), + imagePartObj(srv.URL+"/same.png#three"), + ) + mustErr(t, parsed, r, http.StatusBadRequest, "too_many_media_parts") + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("over-limit duplicate targets triggered %d fetch(es); want 0", n) + } +} + +func TestResolveSameURLWithConflictingKindsRejectsBeforeFetch(t *testing.T) { + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(validPNG(t)) + })) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + parsed := chatBody(imagePartObj(srv.URL+"/same#image"), videoPartObj(srv.URL+"/same#video")) + mustErr(t, parsed, r, http.StatusBadRequest, "media_kind_mismatch") + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("conflicting kinds triggered %d fetch(es); want 0", n) + } +} + +// TestGroupMediaRefsDedupKey pins what the dedup key does and — more importantly +// — what it must NOT do. The key normalizes only what can never change the +// on-the-wire target (scheme/host case, fragment). It must never rewrite the URL +// that is actually fetched: an explicitly written :80/:443 stays, because a +// presigned S3/R2/GCS signature can cover the exact host:port and stripping it +// turns a valid link into an upstream auth error. +func TestGroupMediaRefsDedupKey(t *testing.T) { + // Case and fragment differ only off the wire → one fetch, two targets, and + // the URL requested is the first ORIGINAL string, not a normalized rewrite. + original := "HTTPS://Example.COM/a.png#one" + fetches, err := groupMediaRefs([]mediaRef{ + {url: original, kind: kindImage}, + {url: "https://example.com/a.png#two", kind: kindImage}, + }) + if err != nil { + t.Fatalf("groupMediaRefs: %v", err) + } + if len(fetches) != 1 || len(fetches[0].targets) != 2 { + t.Fatalf("case/fragment variants = %+v, want one group with two targets", fetches) + } + if fetches[0].request.url != original { + t.Errorf("fetched URL = %q, want the consumer's original %q — the key must not rewrite it", + fetches[0].request.url, original) + } + + // An explicit default port is NOT folded away: two fetches, each requesting + // exactly what the consumer wrote. + fetches, err = groupMediaRefs([]mediaRef{ + {url: "https://example.com:443/a.png", kind: kindImage}, + {url: "https://example.com/a.png", kind: kindImage}, + }) + if err != nil { + t.Fatalf("groupMediaRefs: %v", err) + } + if len(fetches) != 2 { + t.Fatalf("explicit :443 grouped with the portless form (%+v); a signed host:port must be preserved", fetches) + } + if fetches[0].request.url != "https://example.com:443/a.png" { + t.Errorf("fetched URL = %q, want the explicit port preserved", fetches[0].request.url) + } + + // IPv6 hex digits are case-insensitive, so they share one fetch. + fetches, err = groupMediaRefs([]mediaRef{ + {url: "https://[2001:DB8::1]/a.png", kind: kindImage}, + {url: "https://[2001:db8::1]/a.png", kind: kindImage}, + }) + if err != nil { + t.Fatalf("groupMediaRefs: %v", err) + } + if len(fetches) != 1 || len(fetches[0].targets) != 2 { + t.Fatalf("IPv6 case variants = %+v, want one group with two targets", fetches) + } + + // Query strings are application-semantic and must remain distinct. + fetches, err = groupMediaRefs([]mediaRef{ + {url: "https://example.com/a.png?v=1", kind: kindImage}, + {url: "https://example.com/a.png?v=2", kind: kindImage}, + }) + if err != nil || len(fetches) != 2 { + t.Fatalf("query-distinct groups = %d, err=%v; want 2", len(fetches), err) + } +} + +func mustErr(t *testing.T, parsed map[string]any, r *Resolver, wantStatus int, wantCode string) { + t.Helper() + mustErrDetail(t, parsed, r, wantStatus, wantCode) +} + +// mustErrDetail is mustErr, returning the typed error so a caller can pin WHICH +// guard rejected the request: several mechanisms share one status/code pair and +// only the Internal diagnostic distinguishes them. +func mustErrDetail(t *testing.T, parsed map[string]any, r *Resolver, wantStatus int, wantCode string) *Error { + t.Helper() + _, err := r.Resolve(context.Background(), parsed) + if err == nil { + t.Fatalf("Resolve: expected error %s/%d", wantCode, wantStatus) + } + me, ok := err.(*Error) + if !ok { + t.Fatalf("error type = %T, want *Error: %v", err, err) + } + if me.Status != wantStatus || me.Code != wantCode { + t.Errorf("error = %d/%s, want %d/%s", me.Status, me.Code, wantStatus, wantCode) + } + return me +} + +func TestResolveDisabledRejectsRemote(t *testing.T) { + cfg := devConfig() + cfg.Enabled = false + r := NewResolver(cfg, nil) + // Fake URL: never fetched because the disabled gate fires first. + parsed := chatBody(imagePartObj("https://example.com/cat.png")) + mustErr(t, parsed, r, http.StatusBadRequest, "remote_media_disabled") +} + +func TestResolveNonStandardPortRejectedBeforeDial(t *testing.T) { + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(validPNG(t)) + })) + defer srv.Close() + + cfg := DefaultConfig() + cfg.AllowPrivateIPs = true // isolate the port policy + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/cat.png")), r, http.StatusForbidden, "media_blocked") + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("non-standard port rejection must happen before dial; origin hits=%d", n) + } +} + +func TestResolveTooManyParts(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + cfg := devConfig() + cfg.MaxParts = 2 + r := NewResolver(cfg, nil) + parsed := chatBody( + imagePartObj(srv.URL+"/1"), imagePartObj(srv.URL+"/2"), imagePartObj(srv.URL+"/3"), + ) + mustErr(t, parsed, r, http.StatusBadRequest, "too_many_media_parts") +} + +func TestResolvePerFileTooLargeHonestContentLength(t *testing.T) { + srv := serveBytes(pngPrefix(200)) // httptest sets Content-Length=200 + defer srv.Close() + cfg := devConfig() + cfg.MaxFileBytes = 50 + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/big.png")), r, http.StatusRequestEntityTooLarge, "media_too_large") +} + +func TestResolvePerFileTooLargeChunked(t *testing.T) { + // Flush mid-write so the response is chunked (Content-Length unknown). This + // proves the io.LimitReader cap — not just the Content-Length pre-check — + // enforces the per-file limit even when the server lies/omits the length. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fl, _ := w.(http.Flusher) + w.Write(pngPrefix(30)) + if fl != nil { + fl.Flush() + } + w.Write(make([]byte, 60)) // total 90 > cap + })) + defer srv.Close() + cfg := devConfig() + cfg.MaxFileBytes = 40 + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/big.png")), r, http.StatusRequestEntityTooLarge, "media_too_large") +} + +func TestResolvePerRequestTotalTooLarge(t *testing.T) { + img := validPNG(t) + srv := serveBytes(img) + defer srv.Close() + cfg := devConfig() + cfg.MaxFileBytes = int64(len(img)) // each file fits the per-file cap exactly + cfg.MaxTotalBytes = int64(2*len(img) - 1) // but the sum exceeds the per-request cap + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/1"), imagePartObj(srv.URL+"/2")), + r, http.StatusRequestEntityTooLarge, "media_too_large") +} + +func TestResolveNonMediaContentType(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/png") // lying header + w.Write([]byte("not an image")) + })) + defer srv.Close() + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/fake.png")), r, http.StatusBadRequest, "media_invalid_type") +} + +func TestResolveUpstreamError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "nope", http.StatusNotFound) + })) + defer srv.Close() + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/missing.png")), r, http.StatusBadGateway, "media_fetch_failed") +} + +func TestResolveTimeout(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(300 * time.Millisecond) + w.Write(validPNG(t)) + })) + defer srv.Close() + cfg := devConfig() + cfg.FetchTimeout = 80 * time.Millisecond + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/slow.png")), r, http.StatusRequestTimeout, "media_fetch_timeout") +} + +func TestResolveSSRFBlocksLoopback(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + // Strict policy: the httptest server is on 127.0.0.1, so the dial Control + // hook must refuse it. + cfg := DefaultConfig() // AllowPrivateIPs=false + cfg.AllowNonStandardPorts = true // isolate the dial-time IP policy from the port gate + r := NewResolver(cfg, nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/x.png")), r, http.StatusForbidden, "media_blocked") +} + +func TestResolveRedirectToDisallowedScheme(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "file:///etc/passwd", http.StatusFound) + })) + defer srv.Close() + r := NewResolver(devConfig(), nil) // allow loopback so the first hop dials + mustErr(t, chatBody(imagePartObj(srv.URL+"/redir")), r, http.StatusBadRequest, "media_invalid_scheme") +} + +func TestResolveRedirectToNonStandardPortBlockedBeforeSecondDial(t *testing.T) { + redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://target.test:8080/media.png", http.StatusFound) + })) + defer redirect.Close() + redirectAddr := strings.TrimPrefix(redirect.URL, "http://") + + cfg := DefaultConfig() // standard ports only + r := NewResolver(cfg, nil) + var targetDials int32 + transport := &http.Transport{ + DisableKeepAlives: true, + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + switch address { + case "origin.test:80": + return (&net.Dialer{}).DialContext(ctx, network, redirectAddr) + case "target.test:8080": + atomic.AddInt32(&targetDials, 1) + } + return nil, net.UnknownNetworkError(address) + }, + } + r.client = &http.Client{Transport: transport, CheckRedirect: redirectGuard(cfg)} + + mustErr(t, chatBody(imagePartObj("http://origin.test/start")), r, http.StatusForbidden, "media_blocked") + if n := atomic.LoadInt32(&targetDials); n != 0 { + t.Fatalf("redirect to non-standard port was dialed %d time(s); must be rejected first", n) + } +} + +func TestResolveRedirectLoopDepthCap(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/again", http.StatusFound) // self-redirect forever + })) + defer srv.Close() + r := NewResolver(devConfig(), nil) + // Exceeding maxRedirects surfaces as errBlockedHost → media_blocked. + mustErr(t, chatBody(imagePartObj(srv.URL+"/start")), r, http.StatusForbidden, "media_blocked") +} + +func TestResolveRedirectStripsRefererToPreventSignedURLLeak(t *testing.T) { + img := validPNG(t) + var gotReferer string + var sawSecond int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&sawSecond, 1) + gotReferer = r.Header.Get("Referer") + w.Write(img) + })) + defer target.Close() + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/real.png", http.StatusFound) + })) + defer origin.Close() + + r := NewResolver(devConfig(), nil) + // A presigned-style signature in the query must not reach the redirect target. + parsed := chatBody(imagePartObj(origin.URL + "/signed.png?X-Amz-Signature=leak-me")) + if _, err := r.Resolve(context.Background(), parsed); err != nil { + t.Fatalf("Resolve: %v", err) + } + if atomic.LoadInt32(&sawSecond) != 1 { + t.Fatalf("redirect target hit %d time(s), want 1", sawSecond) + } + if gotReferer != "" { + t.Errorf("redirect target saw Referer %q; signed origin URL must not leak", gotReferer) + } +} + +func TestHasRemoteMediaAndFetchablePart(t *testing.T) { + withRemote := chatBody(imagePartObj("https://example.com/a.png"), videoPartObj("https://example.com/v.mp4")) + if !HasRemoteMedia(withRemote) { + t.Error("HasRemoteMedia = false for a remote image_url") + } + parts := withRemote["messages"].([]any)[0].(map[string]any)["content"].([]any) + for i, part := range parts { + if !IsFetchableRemotePart(part.(map[string]any)) { + t.Errorf("part %d must be fetchable", i) + } + } + withData := chatBody(imagePartObj("data:image/png;base64,iVBORw0KGgo=")) + if HasRemoteMedia(withData) { + t.Error("HasRemoteMedia = true for an inline data: URI") + } + inlinePart := withData["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any) + if IsFetchableRemotePart(inlinePart) { + t.Error("inline data URI must not be classified as a fetchable remote part") + } + textOnly := map[string]any{"messages": []any{map[string]any{"role": "user", "content": "hi"}}} + if HasRemoteMedia(textOnly) { + t.Error("HasRemoteMedia = true for a text-only request") + } + // Anthropic source blocks are NOT fetchable shapes — must not be collected. + anthropic := chatBody(map[string]any{ + "type": "image", + "source": map[string]any{"type": "url", "url": "https://example.com/anthropic.png"}, + }) + if HasRemoteMedia(anthropic) { + t.Error("Anthropic source blocks must not be collected as fetchable") + } + if IsFetchableRemotePart(anthropic["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)) { + t.Error("Anthropic source block must not be classified as fetchable") + } +} + +// jsonRoundTrip guards that a resolved body re-marshals to valid JSON the +// downstream encrypt path can forward. +func TestResolvedBodyReMarshals(t *testing.T) { + srv := serveBytes(validPNG(t)) + defer srv.Close() + r := NewResolver(devConfig(), nil) + parsed := chatBody(imagePartObj(srv.URL + "/x.png")) + if _, err := r.Resolve(context.Background(), parsed); err != nil { + t.Fatalf("Resolve: %v", err) + } + b, err := json.Marshal(parsed) + if err != nil { + t.Fatalf("re-marshal: %v", err) + } + if !strings.Contains(string(b), "data:image/png;base64,") { + t.Errorf("re-marshaled body missing inlined data: URI") + } +} + +func TestConfigSanitized(t *testing.T) { + c := Config{Enabled: true, MaxFileBytes: 64 << 20, MaxTotalBytes: 1 << 20}.sanitized() + if c.MaxFileBytes != c.MaxTotalBytes { + t.Errorf("per-file cap must clamp DOWN to the total budget; got file=%d total=%d", c.MaxFileBytes, c.MaxTotalBytes) + } + c = Config{}.sanitized() + if c.MaxParts <= 0 || c.FetchTimeout <= 0 || c.TotalDeadline <= 0 || c.Concurrency <= 0 || + c.GlobalConcurrency <= 0 || c.MaxFileBytes <= 0 || c.MaxTotalBytes <= 0 || c.MaxInlinedBytes <= 0 { + t.Errorf("zero config must clamp to safe defaults: %+v", c) + } + if c.MaxImageMegapixels != 0 { + t.Errorf("MaxImageMegapixels=0 is a meaningful off switch, must not be clamped; got %d", c.MaxImageMegapixels) + } + if (Config{MaxImageMegapixels: -5}).sanitized().MaxImageMegapixels != DefaultMaxImageMegapixels { + t.Error("negative MaxImageMegapixels must clamp to the default") + } +} + +func TestConfigFromEnvNonStandardPortOverride(t *testing.T) { + t.Setenv(envAllowOtherPorts, "true") + if !ConfigFromEnv().AllowNonStandardPorts { + t.Error("explicit non-standard-port dev/test override was not read") + } +} + +// TestResolverEnabledIsConstructionTime pins that the kill switch is the value +// captured when the Resolver was built, and that ConfigFromEnv is what reads the +// env. An earlier revision called env.EnvBool on every Enabled() call and +// advertised the switch as redeploy-free — a false promise, because os.Getenv +// returns the process environment captured at exec, so editing the env file or +// reloading the unit cannot change a running coordinator. Re-adding a per-call +// env read would restore the overhead and the wrong operational expectation. +func TestResolverEnabledIsConstructionTime(t *testing.T) { + cfg := devConfig() + cfg.Enabled = true + r := NewResolver(cfg, nil) + if !r.Enabled() { + t.Fatal("Enabled() must report the Config value it was built with") + } + + // Changing the environment underneath a live Resolver must NOT change it: + // the process env of a running coordinator cannot be edited from outside + // either, so pretending otherwise is the bug this guards. + t.Setenv(envEnabled, "false") + if !r.Enabled() { + t.Error("Enabled() re-read the environment; it must reflect construction time only") + } + + // The switch takes effect through ConfigFromEnv at construction, which is + // what a process restart actually re-runs. + if NewResolver(ConfigFromEnv(), nil).Enabled() { + t.Error("a Resolver built after ENABLED=false must be disabled") + } +} + +// TestNewResolverWarnsOnSSRFOverride pins the boot warning for the two dev-only +// escape hatches. Config.Check deliberately accepts them (single-host +// deployments need them), so this WARN is the only signal an operator gets that +// a process is running without the full SSRF policy. +func TestNewResolverWarnsOnSSRFOverride(t *testing.T) { + cases := []struct { + name string + privateIPs bool + otherPorts bool + wantWarn bool + wantSubstring []string + }{ + {"production defaults stay quiet", false, false, false, nil}, + {"private IPs", true, false, true, []string{"allow_private_ips=true", "allow_nonstandard_ports=false"}}, + {"nonstandard ports", false, true, true, []string{"allow_private_ips=false", "allow_nonstandard_ports=true"}}, + {"both", true, true, true, []string{"allow_private_ips=true", "allow_nonstandard_ports=true"}}, + } + for _, c := range cases { + buf := &bytes.Buffer{} + cfg := DefaultConfig() + cfg.AllowPrivateIPs = c.privateIPs + cfg.AllowNonStandardPorts = c.otherPorts + NewResolver(cfg, slog.New(slog.NewTextHandler(buf, nil))) + + got := strings.Contains(buf.String(), "media fetch SSRF override enabled") + if got != c.wantWarn { + t.Errorf("%s: warned = %v, want %v (log: %s)", c.name, got, c.wantWarn, buf.String()) + continue + } + for _, want := range c.wantSubstring { + if !strings.Contains(buf.String(), want) { + t.Errorf("%s: warning must carry %s; got %s", c.name, want, buf.String()) + } + } + } +} + +// gzipBytes returns data compressed with gzip. +func gzipBytes(t *testing.T, data []byte) []byte { + t.Helper() + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write(data); err != nil { + t.Fatalf("gzip write: %v", err) + } + if err := zw.Close(); err != nil { + t.Fatalf("gzip close: %v", err) + } + return buf.Bytes() +} + +// TestResolveGzipEncodedBodyIsNotInflated is the behavioral half of the +// no-transparent-decompression guarantee: a hostile origin declares +// Content-Encoding: gzip over a payload that would inflate into a perfectly +// valid PNG. The coordinator must hand the RAW gzip bytes to the magic-byte +// sniffer — which rejects them — instead of inflating an attacker-controlled +// stream whose expanded size is not bounded by the read caps. It also pins the +// request-side half of the guard (Accept-Encoding: identity). +func TestResolveGzipEncodedBodyIsNotInflated(t *testing.T) { + inner := validPNG(t) + var sawAcceptEncoding atomic.Value + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sawAcceptEncoding.Store(r.Header.Get("Accept-Encoding")) + w.Header().Set("Content-Encoding", "gzip") + w.Header().Set("Content-Type", "image/png") + w.Write(gzipBytes(t, inner)) + })) + defer srv.Close() + + r := NewResolver(devConfig(), nil) + mustErr(t, chatBody(imagePartObj(srv.URL+"/bomb.png")), r, http.StatusBadRequest, "media_invalid_type") + + if ae, _ := sawAcceptEncoding.Load().(string); ae != "identity" { + t.Errorf("outbound Accept-Encoding = %q, want \"identity\" — the request must never advertise a compressed encoding", ae) + } +} + +// TestHTTPClientDisableCompression pins Transport.DisableCompression itself. +// fetchOne ALSO sends "Accept-Encoding: identity", and either guard alone stops +// Go's transparent inflation — Transport only auto-inflates a response when IT +// added the Accept-Encoding header — so an end-to-end fetch can never tell which +// of the two is load-bearing. Driving the client directly with no request-level +// Accept-Encoding isolates the transport setting: flipping DisableCompression to +// false makes Go advertise gzip, inflate the response, and hand back the PNG the +// bomb was hiding. +func TestHTTPClientDisableCompression(t *testing.T) { + inner := validPNG(t) + compressed := gzipBytes(t, inner) + var advertised atomic.Value + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + advertised.Store(r.Header.Get("Accept-Encoding")) + w.Header().Set("Content-Encoding", "gzip") + w.Header().Set("Content-Type", "image/png") + w.Write(compressed) + })) + defer srv.Close() + + resp, err := newHTTPClient(devConfig()).Get(srv.URL + "/bomb.png") + if err != nil { + t.Fatalf("GET: %v", err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + + if ae, _ := advertised.Load().(string); ae != "" { + t.Errorf("transport advertised Accept-Encoding %q; DisableCompression must stop it from requesting gzip", ae) + } + if resp.Uncompressed { + t.Error("response was transparently inflated; DisableCompression must keep the body raw") + } + if !bytes.Equal(body, compressed) { + t.Errorf("body was rewritten by the transport (%d bytes, want the %d raw gzip bytes)", len(body), len(compressed)) + } + if bytes.Equal(body, inner) { + t.Error("transport inflated the gzip bomb back into a valid PNG — a decompressed stream would bypass the read caps") + } +} + +// TestHTTPClientPerHostCapIsProcessWideNotPerRequest pins MaxConnsPerHost to +// GlobalConcurrency. The client is built ONCE per Resolver, so MaxConnsPerHost +// is a process-wide bound on concurrent sockets to a single origin — and with +// DisableKeepAlives no connection is ever reused, so a cap of Concurrency (the +// per-REQUEST worker-pool size, 4) forces all media traffic to one CDN into +// serialized waves of four. That queue wait is charged against FetchTimeout, so +// a healthy origin starts returning spurious media_fetch_timeout under load. +// +// The origin here blocks every request until `want` of them are simultaneously +// in flight. Reverting MaxConnsPerHost to cfg.Concurrency caps the observed peak +// at 4, the barrier never opens, and the test fails. +func TestHTTPClientPerHostCapIsProcessWideNotPerRequest(t *testing.T) { + cfg := devConfig() + const want = 8 // > cfg.Concurrency (4), <= cfg.GlobalConcurrency (32) + if want <= cfg.Concurrency || want > cfg.GlobalConcurrency { + t.Fatalf("test premise broken: want=%d must sit between Concurrency=%d and GlobalConcurrency=%d", + want, cfg.Concurrency, cfg.GlobalConcurrency) + } + + var inFlight, peak atomic.Int32 + allArrived := make(chan struct{}) + var once sync.Once + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := inFlight.Add(1) + defer inFlight.Add(-1) + for { + old := peak.Load() + if n <= old || peak.CompareAndSwap(old, n) { + break + } + } + if n >= want { + once.Do(func() { close(allArrived) }) + } + select { + case <-allArrived: + case <-time.After(3 * time.Second): // capped so a regression fails instead of hanging + } + w.Write([]byte("ok")) + })) + defer srv.Close() + + client := newHTTPClient(cfg) + var wg sync.WaitGroup + for range want { + wg.Add(1) + go func() { + defer wg.Done() + resp, err := client.Get(srv.URL + "/media.png") + if err != nil { + t.Errorf("GET: %v", err) + return + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + }() + } + wg.Wait() + + if got := peak.Load(); got != want { + t.Errorf("peak concurrent sockets to one origin = %d, want %d; MaxConnsPerHost must be the process-wide GlobalConcurrency, not the per-request Concurrency", got, want) + } +} + +// --- fetch-worker panic containment ---------------------------------------- + +// panicRoundTripper stands in for a panic anywhere on the fetch path. Every +// step below fetchAll's `go func` — the outbound HTTP/TLS client, the sniffer, +// jpeg/png/gif.DecodeConfig, the hand-rolled WebP/BMP header parsers — runs +// over attacker-chosen bytes on that spawned goroutine. +type panicRoundTripper struct{} + +func (panicRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { + panic("mediafetch test: synthetic panic on the fetch path") +} + +// A panic on a goroutine SPAWNED inside an http.Handler is a runtime fatal: +// net/http recovers panics only on the per-connection handler goroutine, so an +// unrecovered panic here kills the process and every in-flight request from +// every consumer. The worker must recover through saferun (stack trace + panic +// metric) and turn the aborted fetch into a typed error, never leave out[i] nil +// for Resolve to dereference. +func TestResolveRecoversPanicInFetchWorker(t *testing.T) { + var ( + mu sync.Mutex + observed []string + ) + saferun.SetPanicObserver(func(name string) { + mu.Lock() + observed = append(observed, name) + mu.Unlock() + }) + t.Cleanup(func() { saferun.SetPanicObserver(nil) }) + + r := NewResolver(devConfig(), nil) + r.client.Transport = panicRoundTripper{} + + const url0 = "http://media.test/a.png" + parsed := chatBody(imagePartObj(url0), imagePartObj("http://media.test/b.png")) + + mustErr(t, parsed, r, http.StatusBadGateway, "media_fetch_failed") + + if got := firstImageURL(t, parsed, 0); got != url0 { + t.Errorf("a panicking fetch mutated the request: part 0 = %.40q", got) + } + mu.Lock() + seen := append([]string(nil), observed...) + mu.Unlock() + if len(seen) == 0 { + t.Error("panic was not routed through saferun.Recover: no observer callback fired, " + + "so operators get neither the stack trace nor the panic metric") + } + for _, name := range seen { + if name != "mediafetch.fetchOne" { + t.Errorf("panic observer got goroutine %q, want mediafetch.fetchOne", name) + } + } + if stuck := fetchWorkersRunning(); stuck > 0 { + t.Errorf("%d fetch worker goroutine(s) still running after a recovered panic", stuck) + } + // The recovery must unwind through the semaphore releases too: a slot held + // by a dead worker would wedge every future fetch in the process. + if held := len(r.globalSem); held != 0 { + t.Errorf("global fetch semaphore still holds %d slot(s) after a recovered panic", held) + } +} + +// fetchWorkersRunning counts the mediafetch fetch workers still on the stack, +// polling briefly so a worker mid-unwind isn't reported as stuck. Unrelated +// goroutines are ignored — notably net/http's own Client.Timeout watcher, which +// the stdlib strands when a RoundTripper panics. +func fetchWorkersRunning() int { + var running int + for range 50 { + if running = countGoroutineFrames("(*Resolver).fetchAll"); running == 0 { + return 0 + } + time.Sleep(10 * time.Millisecond) + } + return running +} + +// countGoroutineFrames reports how many frames in the all-goroutine stack dump +// mention fn. +func countGoroutineFrames(fn string) int { + buf := make([]byte, 1<<16) + for { + if n := runtime.Stack(buf, true); n < len(buf) { + return strings.Count(string(buf[:n]), fn) + } + buf = make([]byte, 2*len(buf)) + } +} + +// --- post-inline projection ------------------------------------------------- + +// A URL repeated across parts is fetched ONCE but written back to every +// location, so N targets inline N copies of the same base64 blob. MaxFileBytes +// and MaxTotalBytes bound only what is fetched and cannot see that +// multiplication; MaxInlinedBytes must reject it before anything is mutated, +// instead of letting the coordinator build a body the API layer can only throw +// away afterwards. +func TestResolveDuplicateTargetsRejectedByInlinedProjection(t *testing.T) { + img := validPNG(t) + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + w.Write(img) + })) + defer srv.Close() + + cfg := devConfig() + // One fetch, far inside every byte cap; eight targets inline 8x its data URI. + cfg.MaxInlinedBytes = 4 * int64(len(toDataURI(&fetchedMedia{mime: "image/png", data: img}))) + r := NewResolver(cfg, nil) + + urls := make([]string, DefaultMaxParts) // exactly at MaxParts: the part cap cannot catch this + parts := make([]map[string]any, len(urls)) + for i := range urls { + urls[i] = fmt.Sprintf("%s/same.png#%d", srv.URL, i) + parts[i] = imagePartObj(urls[i]) + } + parsed := chatBody(parts...) + + me := mustErrDetail(t, parsed, r, http.StatusRequestEntityTooLarge, "media_too_large") + if !strings.Contains(me.Internal, "projected inlined") { + t.Errorf("rejected by %q; want the post-inline projection, not a raw byte cap", me.Internal) + } + for i := range urls { + if got := firstImageURL(t, parsed, i); got != urls[i] { + t.Errorf("part %d = %.40q; a rejected resolve must inline nothing", i, got) + } + } + if n := atomic.LoadInt32(&hits); n != 1 { + t.Errorf("origin hits = %d, want 1: the shared URL is fetched once and duplicated", n) + } +} + +// --- budget / concurrency / deadline wiring --------------------------------- + +// The shared byte budget must cut CONCURRENT reads off mid-stream. fetchAll's +// post-hoc aggregate check cannot do that job: it only runs once a fetch has +// been fully buffered, so Concurrency x MaxFileBytes can be retained before it +// notices. Here each body fits MaxFileBytes and only the overlap breaches +// MaxTotalBytes, so at most ONE fetch can ever complete — the post-hoc check can +// never fire, and only fetchOne's totalBudget.reader can reject this. +func TestResolveSharedReadBudgetInterruptsConcurrentReads(t *testing.T) { + const ( + parts = 4 + bodySize = 256 << 10 + chunkSize = 8 << 10 + ) + // MP4 (not PNG): a body that does complete must pass content validation, so + // the read-time budget stays the only possible source of the error. + body := mp4Bytes(bodySize) + var written int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + flusher, _ := w.(http.Flusher) + for sent := 0; sent < len(body); sent += chunkSize { + n, err := w.Write(body[sent:min(sent+chunkSize, len(body))]) + atomic.AddInt64(&written, int64(n)) + if err != nil { + return + } + if flusher != nil { + flusher.Flush() + } + // Pace delivery so the four reads genuinely overlap rather than each + // response landing whole in a socket buffer. + select { + case <-r.Context().Done(): + return + case <-time.After(2 * time.Millisecond): + } + } + })) + defer srv.Close() + + cfg := devConfig() + cfg.Concurrency = parts + cfg.MaxFileBytes = bodySize + (32 << 10) // each body on its own is fine ... + cfg.MaxTotalBytes = bodySize + (64 << 10) // ... but no two of them fit together + r := NewResolver(cfg, nil) + + items := make([]map[string]any, parts) + for i := range items { + items[i] = videoPartObj(fmt.Sprintf("%s/stream-%d.mp4", srv.URL, i)) + } + me := mustErrDetail(t, chatBody(items...), r, http.StatusRequestEntityTooLarge, "media_too_large") + if !strings.Contains(me.Internal, "aggregate body exceeded cap") { + t.Errorf("rejected by %q; want the read-time shared budget (fetchOne's totalBudget.reader), "+ + "not fetchAll's post-hoc backstop", me.Internal) + } + if got, full := atomic.LoadInt64(&written), int64(parts*bodySize); got >= full { + t.Errorf("origins delivered %d of %d bytes: the shared budget must stop the reads mid-stream, "+ + "never buffer the whole aggregate", got, full) + } +} + +// The process-wide semaphore bounds in-flight fetches across ALL requests: it +// is the only thing stopping a burst of media-heavy requests from opening an +// unbounded number of outbound sockets. Two ORIGINS are used deliberately — +// Transport.MaxConnsPerHost is also derived from GlobalConcurrency but is keyed +// per host, so only the semaphore can serialize fetches that target different +// hosts from different requests. +func TestResolveGlobalConcurrencyBoundsFetchesAcrossRequests(t *testing.T) { + img := validPNG(t) + var inFlight, peak atomic.Int64 + origin := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cur := inFlight.Add(1) + for { + old := peak.Load() + if cur <= old || peak.CompareAndSwap(old, cur) { + break + } + } + time.Sleep(40 * time.Millisecond) // hold the slot long enough for overlap to be observable + w.Write(img) + inFlight.Add(-1) + }) + hosts := []*httptest.Server{httptest.NewServer(origin), httptest.NewServer(origin)} + for _, srv := range hosts { + defer srv.Close() + } + + cfg := devConfig() + cfg.GlobalConcurrency = 1 + cfg.Concurrency = 4 // the per-request worker cap must not be what bounds this + r := NewResolver(cfg, nil) + + var wg sync.WaitGroup + errs := make([]error, 2) + for req := range errs { + wg.Add(1) + go func(req int) { + defer wg.Done() + _, errs[req] = r.Resolve(context.Background(), chatBody( + imagePartObj(fmt.Sprintf("%s/r%d.png", hosts[0].URL, req)), + imagePartObj(fmt.Sprintf("%s/r%d.png", hosts[1].URL, req)), + )) + }(req) + } + wg.Wait() + + for req, err := range errs { + if err != nil { + t.Fatalf("Resolve %d: %v", req, err) + } + } + if got := peak.Load(); got > 1 { + t.Errorf("peak concurrent fetches = %d with GlobalConcurrency=1; the process-wide semaphore "+ + "must bound in-flight fetches across requests and hosts", got) + } +} + +// TotalDeadline bounds the WHOLE resolution step. FetchTimeout is deliberately +// far longer here, so a fetch that outlives the step budget can only be stopped +// by the total deadline: without it this request simply succeeds, slowly. +func TestResolveTotalDeadlineBoundsWholeStep(t *testing.T) { + img := validPNG(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-time.After(400 * time.Millisecond): + w.Write(img) + case <-r.Context().Done(): // the client gave up; don't hold Close() + } + })) + defer srv.Close() + + cfg := devConfig() + cfg.TotalDeadline = 60 * time.Millisecond + cfg.FetchTimeout = 30 * time.Second + r := NewResolver(cfg, nil) + + start := time.Now() + mustErr(t, chatBody(imagePartObj(srv.URL+"/slow.png")), r, http.StatusRequestTimeout, "media_fetch_timeout") + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Errorf("resolve took %v: the whole-step TotalDeadline (%v) must bound it, not FetchTimeout (%v)", + elapsed, cfg.TotalDeadline, cfg.FetchTimeout) + } +} + +// TestResolveRejectsHTTPSToHTTPDowngrade pins that an https caller keeps +// transport confidentiality across the whole redirect chain. Validating each hop +// independently against the scheme allowlist accepts the downgrade — both +// schemes are individually legal — but it puts a redirect's signed query on the +// wire in plaintext and lets an on-path party swap the bytes before they are +// inlined into the (encrypted) provider request. +func TestResolveRejectsHTTPSToHTTPDowngrade(t *testing.T) { + var plainHits int32 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&plainHits, 1) + w.Write(validPNG(t)) + })) + defer plain.Close() + + tls := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+"/downgraded.png", http.StatusFound) + })) + defer tls.Close() + + cfg := devConfig() + r := NewResolver(cfg, nil) + // Trust the httptest CA so the first (https) hop succeeds and the downgrade + // is the only thing under test. + r.client.Transport.(*http.Transport).TLSClientConfig = tls.Client().Transport.(*http.Transport).TLSClientConfig + + mustErr(t, chatBody(imagePartObj(tls.URL+"/redir")), r, http.StatusBadRequest, "media_invalid_scheme") + if n := atomic.LoadInt32(&plainHits); n != 0 { + t.Errorf("downgraded hop was dialed %d time(s); the guard must refuse before the request", n) + } +} + +// TestMediaTransportCapsResponseHeaders pins the header budget. Headers are read +// before any body cap applies and Go's default is 10 MiB per connection, so an +// attacker-controlled origin could force GlobalConcurrency x 10 MiB of buffering +// while every body stayed within budget. +func TestMediaTransportCapsResponseHeaders(t *testing.T) { + c := newHTTPClient(DefaultConfig()) + tr, ok := c.Transport.(*http.Transport) + if !ok { + t.Fatal("media client transport is not *http.Transport") + } + if tr.MaxResponseHeaderBytes <= 0 || tr.MaxResponseHeaderBytes > 1<<20 { + t.Errorf("MaxResponseHeaderBytes = %d, want a small explicit cap (0 means Go's 10 MiB default)", + tr.MaxResponseHeaderBytes) + } +} diff --git a/coordinator/mediafetch/sniff.go b/coordinator/mediafetch/sniff.go new file mode 100644 index 0000000000..57b0996f11 --- /dev/null +++ b/coordinator/mediafetch/sniff.go @@ -0,0 +1,255 @@ +package mediafetch + +// sniff.go decides what fetched bytes actually ARE — from magic bytes, never the +// spoofable Content-Type header — and enforces the structural safety policy on +// them: an explicit allowlist of formats the provider's decoders (CoreImage for +// images, AVFoundation for video) support, a part-kind cross-check (an image_url +// part must be an image, a video_url part a video), and a header-only megapixel +// cap for every accepted image format (pixel-bomb defense, mirroring the +// provider's own pre-raster gate). HTML, SVG (scriptable), archives, standalone +// executables, and anything else outside the allowlist is rejected; trailing +// bytes in an otherwise-valid media container are never executed here. + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "fmt" + "image" + "image/gif" + "image/jpeg" + "image/png" + "math" + "net/http" + "strings" +) + +// mediaKind is the request-declared kind of a media part: an image_url part +// declares kindImage, a video_url part kindVideo. The sniffed bytes must match. +type mediaKind string + +const ( + kindImage mediaKind = "image" + kindVideo mediaKind = "video" +) + +// allowedSniffedTypes maps each sniffed MIME type the coordinator will inline to +// the media kind it satisfies. Deliberately restricted to formats the provider +// can decode: CoreImage handles the image set; AVFoundation decodes MP4/QuickTime +// but NOT WebM/AVI/Matroska — inlining those would burn a fetch + dispatch just +// to 400 at the provider, so they are rejected here with a clear error instead. +// SVG never sniffs as image/* (http.DetectContentType yields text/xml or +// text/html), so scriptable vector content fails the allowlist by construction. +var allowedSniffedTypes = map[string]mediaKind{ + "image/jpeg": kindImage, + "image/png": kindImage, + "image/gif": kindImage, + "image/webp": kindImage, + "image/bmp": kindImage, + + "video/mp4": kindVideo, + "video/quicktime": kindVideo, // custom sniff below; DetectContentType doesn't classify qt brands +} + +// fetchedMedia is the result of a successful fetch: validated bytes plus the +// sniffed MIME type used to build the data: URI. +type fetchedMedia struct { + mime string + data []byte +} + +// sniffMediaType returns the sniffed MIME type and kind for data, or ok=false +// when the bytes are not an allowlisted image/video format. The sniffed type +// (not the response header) is authoritative, so a server claiming image/png +// while serving HTML/SVG/an archive is rejected. +func sniffMediaType(data []byte) (mime string, kind mediaKind, ok bool) { + ct := http.DetectContentType(data) // e.g. "image/png", "video/mp4", "text/plain; charset=utf-8" + base := strings.TrimSpace(strings.SplitN(ct, ";", 2)[0]) + if base == "application/octet-stream" { + // DetectContentType's MP4 matcher only recognizes ftyp brands starting + // "mp4"; QuickTime files (brand "qt ") fall through to octet-stream. + // AVFoundation decodes .mov natively, so classify it ourselves. + if isQuickTime(data) { + base = "video/quicktime" + } + } + k, allowed := allowedSniffedTypes[base] + if !allowed { + return "", "", false + } + return base, k, true +} + +// isQuickTime reports whether data starts with an ISO-BMFF ftyp box whose major +// brand is QuickTime ("qt "). Layout: [4-byte box size]["ftyp"][4-byte major +// brand][...]. Only the major brand is checked — compatible-brand scanning isn't +// needed for the .mov files AVFoundation targets. +func isQuickTime(data []byte) bool { + return len(data) >= 12 && + bytes.Equal(data[4:8], []byte("ftyp")) && + bytes.Equal(data[8:12], []byte("qt ")) +} + +// validateFetchedMedia enforces the post-download structural policy for one +// media item: allowlisted format, declared-kind match, and the image pixel cap. +// Returns the sniffed MIME type to build the data: URI from. +func (r *Resolver) validateFetchedMedia(declared mediaKind, data []byte) (string, error) { + mime, kind, ok := sniffMediaType(data) + if !ok { + return "", &Error{Status: http.StatusBadRequest, Code: "media_invalid_type", + Public: "a media URL did not return a supported image or video format (supported: JPEG, PNG, GIF, WebP, BMP images; MP4/QuickTime video)", + Internal: fmt.Sprintf("sniffed type %q not in allowlist", http.DetectContentType(data))} + } + if kind != declared { + return "", &Error{Status: http.StatusBadRequest, Code: "media_kind_mismatch", + Public: fmt.Sprintf("a %s_url part resolved to %s content; use the matching content-part type", declared, kind), + Internal: fmt.Sprintf("declared %s_url, sniffed %q", declared, mime)} + } + if kind == kindImage { + if err := r.enforceImagePixelCap(mime, data); err != nil { + return "", err + } + } + return mime, nil +} + +// enforceImagePixelCap rejects decompression/pixel bombs by reading ONLY the +// image header (never a full decode). JPEG/PNG/GIF use stdlib DecodeConfig; +// WebP and BMP use their documented header layouts below. GIF is checked on its +// logical-screen size (per-frame bombs are likewise the provider's aggregate +// caps' job). A header that its own sniffed format cannot parse is rejected +// outright: the provider's decoder would fail on it anyway, so failing fast here +// saves a dispatch. +func (r *Resolver) enforceImagePixelCap(mime string, data []byte) error { + maxMP := r.cfg.MaxImageMegapixels + if maxMP <= 0 { + return nil + } + var ( + cfg image.Config + err error + ) + switch mime { + case "image/jpeg": + cfg, err = jpeg.DecodeConfig(bytes.NewReader(data)) + case "image/png": + cfg, err = png.DecodeConfig(bytes.NewReader(data)) + case "image/gif": + cfg, err = gif.DecodeConfig(bytes.NewReader(data)) + case "image/webp": + cfg.Width, cfg.Height, err = webPDimensions(data) + case "image/bmp": + cfg.Width, cfg.Height, err = bmpDimensions(data) + default: + err = fmt.Errorf("unsupported image mime %q", mime) + } + if err != nil { + return &Error{Status: http.StatusBadRequest, Code: "media_invalid_type", + Public: "a media URL returned an image with an unreadable header", + Internal: fmt.Sprintf("%s header decode: %v", mime, err)} + } + maxPixels := int64(maxMP) + if maxPixels > math.MaxInt64/1_000_000 { + maxPixels = math.MaxInt64 + } else { + maxPixels *= 1_000_000 + } + width, height := int64(cfg.Width), int64(cfg.Height) + if width <= 0 || height <= 0 { + return &Error{Status: http.StatusBadRequest, Code: "media_invalid_type", + Public: "a media URL returned an image with invalid dimensions", + Internal: fmt.Sprintf("%s dimensions %dx%d", mime, cfg.Width, cfg.Height)} + } + // Compare by division BEFORE multiplying: OS/2 BMP dimensions are uint32 + // and can otherwise overflow int64 when multiplied (e.g. 0xffffffff² wraps + // negative and would bypass a naive pixels > maxPixels check). + if width > maxPixels/height { + return &Error{Status: http.StatusRequestEntityTooLarge, Code: "media_too_large", + Public: fmt.Sprintf("an image exceeds the maximum decoded size of %d megapixels", maxMP), + Internal: fmt.Sprintf("%s %dx%d exceeds %d MP cap", mime, cfg.Width, cfg.Height, maxMP)} + } + return nil +} + +// webPDimensions reads the canvas/frame dimensions from each standardized WebP +// bitstream form without decoding pixels: VP8X (extended), VP8L (lossless), and +// VP8 (lossy key frame). See the WebP container specification §2–4. +func webPDimensions(data []byte) (int, int, error) { + if len(data) < 20 || !bytes.Equal(data[0:4], []byte("RIFF")) || !bytes.Equal(data[8:12], []byte("WEBP")) { + return 0, 0, fmt.Errorf("invalid WebP RIFF header") + } + switch string(data[12:16]) { + case "VP8X": + if len(data) < 30 || binary.LittleEndian.Uint32(data[16:20]) < 10 { + return 0, 0, fmt.Errorf("truncated VP8X header") + } + width := 1 + int(data[24]) + int(data[25])<<8 + int(data[26])<<16 + height := 1 + int(data[27]) + int(data[28])<<8 + int(data[29])<<16 + return width, height, nil + case "VP8L": + if len(data) < 25 || data[20] != 0x2f { + return 0, 0, fmt.Errorf("truncated VP8L header") + } + width := 1 + int(data[21]) + (int(data[22])&0x3f)<<8 + height := 1 + int(data[22]>>6) + int(data[23])<<2 + (int(data[24])&0x0f)<<10 + return width, height, nil + case "VP8 ": + if len(data) < 30 || !bytes.Equal(data[23:26], []byte{0x9d, 0x01, 0x2a}) { + return 0, 0, fmt.Errorf("invalid VP8 key-frame header") + } + width := int(binary.LittleEndian.Uint16(data[26:28]) & 0x3fff) + height := int(binary.LittleEndian.Uint16(data[28:30]) & 0x3fff) + if width == 0 || height == 0 { + return 0, 0, fmt.Errorf("zero-sized VP8 frame") + } + return width, height, nil + default: + return 0, 0, fmt.Errorf("unsupported WebP chunk %q", data[12:16]) + } +} + +// bmpDimensions reads dimensions from the OS/2 BITMAPCOREHEADER (12 bytes) or +// Windows BITMAPINFOHEADER-family DIB headers (>=40 bytes). Negative Windows +// heights indicate top-down row order; their absolute value is the canvas size. +func bmpDimensions(data []byte) (int, int, error) { + if len(data) < 26 || !bytes.Equal(data[0:2], []byte("BM")) { + return 0, 0, fmt.Errorf("truncated BMP header") + } + dibSize := binary.LittleEndian.Uint32(data[14:18]) + if dibSize == 12 { + width := int(binary.LittleEndian.Uint16(data[18:20])) + height := int(binary.LittleEndian.Uint16(data[20:22])) + if width == 0 || height == 0 { + return 0, 0, fmt.Errorf("zero-sized BMP canvas") + } + return width, height, nil + } + // OS/2 2.x defines a 64-byte header plus a legal 16-byte short form. Both + // store unsigned 32-bit dimensions at the same offsets as Windows headers. + if dibSize == 16 || dibSize == 64 { + width64 := uint64(binary.LittleEndian.Uint32(data[18:22])) + height64 := uint64(binary.LittleEndian.Uint32(data[22:26])) + maxInt := uint64(^uint(0) >> 1) + if width64 == 0 || height64 == 0 || width64 > maxInt || height64 > maxInt { + return 0, 0, fmt.Errorf("invalid OS/2 BMP dimensions %dx%d", width64, height64) + } + return int(width64), int(height64), nil + } + if dibSize < 40 { + return 0, 0, fmt.Errorf("unsupported BMP DIB header size %d", dibSize) + } + width64 := int64(int32(binary.LittleEndian.Uint32(data[18:22]))) + height64 := int64(int32(binary.LittleEndian.Uint32(data[22:26]))) + if height64 < 0 { + height64 = -height64 + } + if width64 <= 0 || height64 <= 0 || width64 > int64(^uint(0)>>1) || height64 > int64(^uint(0)>>1) { + return 0, 0, fmt.Errorf("invalid BMP dimensions %dx%d", width64, height64) + } + return int(width64), int(height64), nil +} + +// toDataURI encodes fetched media as a standard base64 data: URI. +func toDataURI(m *fetchedMedia) string { + return "data:" + m.mime + ";base64," + base64.StdEncoding.EncodeToString(m.data) +} diff --git a/coordinator/mediafetch/sniff_test.go b/coordinator/mediafetch/sniff_test.go new file mode 100644 index 0000000000..35702755e3 --- /dev/null +++ b/coordinator/mediafetch/sniff_test.go @@ -0,0 +1,340 @@ +package mediafetch + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "image" + "image/color" + "image/gif" + "image/jpeg" + "image/png" + "net/http" + "strings" + "testing" +) + +// --- fixtures ---------------------------------------------------------------- + +// validPNG / validJPEG / validGIF are real, decodable 2x2 images produced by the +// stdlib encoders — they pass both the sniff allowlist AND the header pixel gate. +func validPNG(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil { + t.Fatalf("encode png: %v", err) + } + return buf.Bytes() +} + +func validJPEG(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + if err := jpeg.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 2)), nil); err != nil { + t.Fatalf("encode jpeg: %v", err) + } + return buf.Bytes() +} + +func validGIF(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + pal := color.Palette{color.Black, color.White} + if err := gif.Encode(&buf, image.NewPaletted(image.Rect(0, 0, 2, 2), pal), nil); err != nil { + t.Fatalf("encode gif: %v", err) + } + return buf.Bytes() +} + +// mp4Bytes returns bytes http.DetectContentType sniffs as video/mp4: an ISO-BMFF +// ftyp box (size 20) with major brand mp42. +func mp4Bytes(total int) []byte { + head := append([]byte{0, 0, 0, 20}, []byte("ftypmp42\x00\x00\x00\x00mp42")...) + if total < len(head) { + total = len(head) + } + b := make([]byte, total) + copy(b, head) + return b +} + +// quickTimeBytes returns an ftyp box with the QuickTime major brand ("qt "), +// which DetectContentType does NOT classify — our custom sniff must. +func quickTimeBytes(total int) []byte { + head := append([]byte{0, 0, 0, 20}, []byte("ftypqt \x00\x00\x00\x00qt ")...) + if total < len(head) { + total = len(head) + } + b := make([]byte, total) + copy(b, head) + return b +} + +// webPVP8XBytes builds a VP8X header with the requested canvas dimensions. +// Pixel payload is unnecessary: the coordinator validates headers only and the +// provider remains the authoritative full decoder. +func webPVP8XBytes(width, height int) []byte { + b := make([]byte, 30) + copy(b[0:4], "RIFF") + binary.LittleEndian.PutUint32(b[4:8], uint32(len(b)-8)) + copy(b[8:12], "WEBP") + copy(b[12:16], "VP8X") + binary.LittleEndian.PutUint32(b[16:20], 10) + w := width - 1 + h := height - 1 + b[24], b[25], b[26] = byte(w), byte(w>>8), byte(w>>16) + b[27], b[28], b[29] = byte(h), byte(h>>8), byte(h>>16) + return b +} + +func webPVP8LBytes(width, height int) []byte { + b := make([]byte, 25) + copy(b[0:4], "RIFF") + binary.LittleEndian.PutUint32(b[4:8], uint32(len(b)-8)) + copy(b[8:12], "WEBP") + copy(b[12:16], "VP8L") + binary.LittleEndian.PutUint32(b[16:20], 5) + b[20] = 0x2f + packed := uint32(width-1) | uint32(height-1)<<14 + binary.LittleEndian.PutUint32(b[21:25], packed) + return b +} + +func webPVP8Bytes(width, height int) []byte { + b := make([]byte, 30) + copy(b[0:4], "RIFF") + binary.LittleEndian.PutUint32(b[4:8], uint32(len(b)-8)) + copy(b[8:12], "WEBP") + copy(b[12:16], "VP8 ") + binary.LittleEndian.PutUint32(b[16:20], 10) + copy(b[23:26], []byte{0x9d, 0x01, 0x2a}) + binary.LittleEndian.PutUint16(b[26:28], uint16(width)) + binary.LittleEndian.PutUint16(b[28:30], uint16(height)) + return b +} + +// bmpBytes builds a Windows BITMAPINFOHEADER with the requested dimensions. +func bmpBytes(width, height int32) []byte { + b := make([]byte, 54) + copy(b[0:2], "BM") + binary.LittleEndian.PutUint32(b[2:6], uint32(len(b))) + binary.LittleEndian.PutUint32(b[10:14], 54) + binary.LittleEndian.PutUint32(b[14:18], 40) + binary.LittleEndian.PutUint32(b[18:22], uint32(width)) + binary.LittleEndian.PutUint32(b[22:26], uint32(height)) + binary.LittleEndian.PutUint16(b[26:28], 1) + binary.LittleEndian.PutUint16(b[28:30], 24) + return b +} + +func bmpCoreBytes(width, height uint16) []byte { + b := make([]byte, 26) + copy(b[0:2], "BM") + binary.LittleEndian.PutUint32(b[2:6], uint32(len(b))) + binary.LittleEndian.PutUint32(b[14:18], 12) + binary.LittleEndian.PutUint16(b[18:20], width) + binary.LittleEndian.PutUint16(b[20:22], height) + return b +} + +func bmpOS2Bytes(dibSize uint32, width, height uint32) []byte { + b := make([]byte, 30) + copy(b[0:2], "BM") + binary.LittleEndian.PutUint32(b[2:6], uint32(len(b))) + binary.LittleEndian.PutUint32(b[14:18], dibSize) + binary.LittleEndian.PutUint32(b[18:22], width) + binary.LittleEndian.PutUint32(b[22:26], height) + return b +} + +// bombPNG hand-crafts a syntactically valid PNG header (correct IHDR CRC) +// declaring width×height = 20000×20000 = 400 MP — a pixel bomb whose FILE size +// is tiny. png.DecodeConfig reads exactly this header. +func bombPNG(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + buf.WriteString("\x89PNG\r\n\x1a\n") + ihdr := make([]byte, 13) + binary.BigEndian.PutUint32(ihdr[0:4], 20000) // width + binary.BigEndian.PutUint32(ihdr[4:8], 20000) // height + ihdr[8] = 8 // bit depth + ihdr[9] = 6 // color type RGBA + // compression/filter/interlace = 0 + var length [4]byte + binary.BigEndian.PutUint32(length[:], 13) + buf.Write(length[:]) + chunk := append([]byte("IHDR"), ihdr...) + buf.Write(chunk) + var crc [4]byte + binary.BigEndian.PutUint32(crc[:], crc32.ChecksumIEEE(chunk)) + buf.Write(crc[:]) + return buf.Bytes() +} + +// --- tests --------------------------------------------------------------- + +func TestSniffMediaType(t *testing.T) { + cases := []struct { + name string + data []byte + wantMime string + wantKind mediaKind + wantOK bool + }{ + {"png", []byte("\x89PNG\r\n\x1a\n................"), "image/png", kindImage, true}, + {"jpeg", []byte("\xff\xd8\xff\xe0................"), "image/jpeg", kindImage, true}, + {"gif", []byte("GIF89a................"), "image/gif", kindImage, true}, + {"webp", webPVP8XBytes(2, 2), "image/webp", kindImage, true}, + {"bmp", bmpBytes(2, 2), "image/bmp", kindImage, true}, + {"mp4", mp4Bytes(32), "video/mp4", kindVideo, true}, + {"quicktime", quickTimeBytes(32), "video/quicktime", kindVideo, true}, + + // Formats the provider cannot decode (AVFoundation has no WebM/AVI) and + // non-media content must fail the allowlist. + {"webm rejected", []byte("\x1aE\xdf\xa3................"), "", "", false}, + {"avi rejected", []byte("RIFF\x00\x00\x00\x00AVI ............"), "", "", false}, + {"html", []byte(""), "", "", false}, + {"svg-as-xml", []byte(""), "", "", false}, + {"text", []byte("just some text here, not media"), "", "", false}, + {"elf executable", []byte("\x7fELF............................"), "", "", false}, + {"empty", []byte{}, "", "", false}, + } + for _, c := range cases { + mime, kind, ok := sniffMediaType(c.data) + if mime != c.wantMime || kind != c.wantKind || ok != c.wantOK { + t.Errorf("sniffMediaType(%s) = (%q,%q,%v), want (%q,%q,%v)", + c.name, mime, kind, ok, c.wantMime, c.wantKind, c.wantOK) + } + } +} + +func TestValidateFetchedMediaKindMismatch(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) + // An image_url part resolving to a video must be rejected (and vice versa). + if _, err := r.validateFetchedMedia(kindImage, mp4Bytes(32)); err == nil { + t.Fatal("image_url→mp4 must be rejected") + } else if me := err.(*Error); me.Code != "media_kind_mismatch" || me.Status != http.StatusBadRequest { + t.Errorf("got %d/%s, want 400/media_kind_mismatch", me.Status, me.Code) + } + if _, err := r.validateFetchedMedia(kindVideo, validPNG(t)); err == nil { + t.Fatal("video_url→png must be rejected") + } else if me := err.(*Error); me.Code != "media_kind_mismatch" { + t.Errorf("got %s, want media_kind_mismatch", me.Code) + } + // Matching kinds pass and return the sniffed mime. + mime, err := r.validateFetchedMedia(kindImage, validJPEG(t)) + if err != nil || mime != "image/jpeg" { + t.Errorf("valid jpeg: mime=%q err=%v", mime, err) + } + if mime, err := r.validateFetchedMedia(kindVideo, quickTimeBytes(32)); err != nil || mime != "video/quicktime" { + t.Errorf("quicktime: mime=%q err=%v", mime, err) + } +} + +func TestPixelCapRejectsBomb(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) // 100 MP default cap + _, err := r.validateFetchedMedia(kindImage, bombPNG(t)) + if err == nil { + t.Fatal("400 MP png header must be rejected") + } + me := err.(*Error) + if me.Code != "media_too_large" || me.Status != http.StatusRequestEntityTooLarge { + t.Errorf("got %d/%s, want 413/media_too_large", me.Status, me.Code) + } +} + +func TestPixelCapAcceptsAllNormalImageFormats(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) + for name, data := range map[string][]byte{ + "png": validPNG(t), "jpeg": validJPEG(t), "gif": validGIF(t), + "webp-vp8x": webPVP8XBytes(2, 2), + "webp-vp8l": webPVP8LBytes(2, 2), + "webp-vp8": webPVP8Bytes(2, 2), + "bmp-info": bmpBytes(2, 2), + "bmp-top-down": bmpBytes(2, -2), + "bmp-core": bmpCoreBytes(2, 2), + "bmp-os2-short": bmpOS2Bytes(16, 2, 2), + "bmp-os2-full": bmpOS2Bytes(64, 2, 2), + } { + if _, err := r.validateFetchedMedia(kindImage, data); err != nil { + t.Errorf("%s: %v", name, err) + } + } +} + +func TestPixelCapRejectsWebPAndBMPBombs(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) + for name, data := range map[string][]byte{ + "webp-vp8x": webPVP8XBytes(20_000, 20_000), + "webp-vp8l": webPVP8LBytes(12_000, 12_000), + "webp-vp8": webPVP8Bytes(12_000, 12_000), + "bmp-info": bmpBytes(20_000, 20_000), + "bmp-core": bmpCoreBytes(20_000, 20_000), + "bmp-os2-product-overflow": bmpOS2Bytes(16, ^uint32(0), ^uint32(0)), + } { + _, err := r.validateFetchedMedia(kindImage, data) + if err == nil { + t.Errorf("%s 400 MP header must be rejected", name) + continue + } + if me := err.(*Error); me.Code != "media_too_large" { + t.Errorf("%s: got %s, want media_too_large", name, me.Code) + } + } +} + +func TestPixelCapRejectsCorruptHeader(t *testing.T) { + r := NewResolver(DefaultConfig(), nil) + // Sniffs as PNG (magic bytes) but the IHDR is garbage — the provider's + // decoder would fail on it, so it must fail fast here. + corrupt := []byte("\x89PNG\r\n\x1a\n................") + _, err := r.validateFetchedMedia(kindImage, corrupt) + if err == nil { + t.Fatal("corrupt png header must be rejected") + } + if me := err.(*Error); me.Code != "media_invalid_type" { + t.Errorf("got %s, want media_invalid_type", me.Code) + } +} + +func TestPixelCapDisabled(t *testing.T) { + cfg := DefaultConfig() + cfg.MaxImageMegapixels = 0 // explicit off → header parse skipped entirely + r := NewResolver(cfg, nil) + if _, err := r.validateFetchedMedia(kindImage, bombPNG(t)); err != nil { + t.Errorf("cap disabled: bomb header should pass to the provider layer, got %v", err) + } +} + +func TestToDataURI(t *testing.T) { + got := toDataURI(&fetchedMedia{mime: "image/png", data: []byte("AB")}) + want := "data:image/png;base64,QUI=" + if got != want { + t.Errorf("toDataURI = %q, want %q", got, want) + } +} + +func TestQuickTimeSniffTooShort(t *testing.T) { + if isQuickTime([]byte("\x00\x00\x00\x14ftypqt")) { + t.Error("11-byte prefix must not classify as QuickTime") + } + if _, _, ok := sniffMediaType([]byte("\x00\x00\x00\x14ftyp")); ok { + t.Error("bare ftyp must not pass the allowlist") + } + nearMatch := quickTimeBytes(32) + copy(nearMatch[8:12], "qtxx") + if isQuickTime(nearMatch) { + t.Error("only the exact QuickTime major brand \"qt \" may match") + } +} + +// Guard: no allowlisted type may be outside image/* or video/* (the Accept +// header and kind cross-check assume the two families). +func TestAllowlistFamilies(t *testing.T) { + for mime, kind := range allowedSniffedTypes { + wantPrefix := string(kind) + "/" + if !strings.HasPrefix(mime, wantPrefix) { + t.Errorf("allowlist entry %q maps to kind %q but lacks prefix %q", mime, kind, wantPrefix) + } + } +} diff --git a/coordinator/mediafetch/ssrf.go b/coordinator/mediafetch/ssrf.go new file mode 100644 index 0000000000..035f93d948 --- /dev/null +++ b/coordinator/mediafetch/ssrf.go @@ -0,0 +1,199 @@ +package mediafetch + +import ( + "errors" + "fmt" + "net" + "net/netip" + "strings" + "syscall" + + "golang.org/x/net/idna" +) + +// errBlockedIP is returned (wrapped) by the dialer Control hook when a socket is +// about to connect to a denied address. Callers detect it with errors.Is to map +// the failure to a 403 instead of a generic network error. +var errBlockedIP = errors.New("mediafetch: destination IP is not allowed") + +// errBlockedScheme / errBlockedHost surface non-IP rejections (scheme, userinfo, +// blocklisted domain) with the same errors.Is treatment. +var ( + errBlockedScheme = errors.New("mediafetch: URL scheme is not allowed") + errBlockedHost = errors.New("mediafetch: host is not allowed") +) + +// blockedMetadataV4 is the cloud metadata service address (AWS/GCP/Azure all use +// 169.254.169.254). It is already covered by the link-local 169.254.0.0/16 deny +// below, but we keep it explicit for clarity and defense against future changes. +var blockedMetadataV4 = netip.MustParseAddr("169.254.169.254") + +// blockedPrefixes are ranges that net/netip's IsPrivate/IsLoopback/IsLinkLocal/ +// IsGlobalUnicast helpers do NOT classify as non-global — so without this +// explicit list they would be (wrongly) allowed. The critical ones are IPv6 +// transition mechanisms that embed or tunnel IPv4 destinations — NAT64, 6to4, +// Teredo, and the deprecated 6to4 relay anycast — because an embedded loopback, +// metadata, or RFC1918 address can bypass an IPv4-only deny policy if the host +// has the corresponding tunnel configured. CGNAT/RFC6598 is also denied because +// it commonly reaches internal cloud/VPC overlays. The rest are benchmarking, +// documentation, IETF-assignment, deprecated site-local, and reserved ranges +// that are never a legitimate public media origin. Transition space is denied +// outright; coordinator hosts are dual-stack and never need it — fail closed. +var blockedPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), // "this network" (RFC 1122); IsUnspecified only matches 0.0.0.0 exactly + netip.MustParsePrefix("100.64.0.0/10"), // CGNAT / RFC 6598 shared address space + netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments (RFC 6890) + netip.MustParsePrefix("192.88.99.0/24"), // deprecated 6to4 relay anycast (RFC 7526) + netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1 (documentation) + netip.MustParsePrefix("198.18.0.0/15"), // benchmarking (RFC 2544) + netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2 (documentation) + netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3 (documentation) + netip.MustParsePrefix("240.0.0.0/4"), // reserved / future use (incl. 255.255.255.255) + netip.MustParsePrefix("64:ff9b::/96"), // NAT64 well-known prefix (RFC 6052) + netip.MustParsePrefix("64:ff9b:1::/48"), // NAT64 local-use prefix (RFC 8215) + netip.MustParsePrefix("::/96"), // deprecated IPv4-compatible IPv6 (e.g. ::127.0.0.1) + netip.MustParsePrefix("2001::/32"), // Teredo (RFC 4380; embeds IPv4 endpoints) + netip.MustParsePrefix("2002::/16"), // 6to4 (RFC 3056; embeds an IPv4 destination) + netip.MustParsePrefix("2001:db8::/32"), // IPv6 documentation (RFC 3849) + netip.MustParsePrefix("100::/64"), // IPv6 discard-only (RFC 6666) + netip.MustParsePrefix("fec0::/10"), // deprecated IPv6 site-local space (RFC 3879) +} + +// ipAllowed reports whether dialing ip is permitted under the SSRF policy. +// allowPrivate=true (dev/test) bypasses the deny set so httptest's 127.0.0.1 +// servers are reachable. +// +// Denied (when allowPrivate is false): loopback (127.0.0.0/8, ::1), RFC1918 +// private (10/8, 172.16/12, 192.168/16), IPv6 ULA (fc00::/7), link-local +// (169.254/16, fe80::/10) including cloud metadata, unspecified (0.0.0.0, ::), +// multicast, and anything not classified as a normal global-unicast address. +// IPv4-mapped IPv6 (::ffff:a.b.c.d) is unmapped first so the inner IPv4 is judged +// by the IPv4 rules — closing a classic blocklist bypass — and any IPv6 zone +// ("%eth0") is stripped so a zoned address cannot skip the prefix deny set. +func ipAllowed(ip netip.Addr, allowPrivate bool) bool { + if !ip.IsValid() { + return false + } + // Normalize IPv4-mapped IPv6 (::ffff:127.0.0.1) to its IPv4 form so the + // loopback/private checks below see the real address. + if ip.Is4In6() { + ip = ip.Unmap() + } + // Strip any IPv6 zone ("fe80::1%eth0"). netip.Prefix.Contains returns false + // for EVERY zoned address, so without this the whole blockedPrefixes loop is + // silently skipped — a zone suffix survives url.Parse → u.Hostname() → + // http.Transport's canonicalAddr → this Control hook, and an unknown zone + // name resolves to ZoneId 0 so the kernel still dials the bare address. + // Zones are meaningless for an outbound media fetch; drop before any policy + // evaluation so BOTH the dial-time hook and direct callers are covered. + ip = ip.WithZone("") + if allowPrivate { + // Dev/test: only reject the obviously-bogus unspecified address. + return !ip.IsUnspecified() + } + // Explicit deny of ranges the stdlib helpers misclassify as global-unicast + // (NAT64, CGNAT, benchmarking, documentation, reserved). Checked before the + // helper-based switch below. + for _, p := range blockedPrefixes { + if p.Contains(ip) { + return false + } + } + switch { + case ip.IsLoopback(): // 127.0.0.0/8, ::1 + return false + case ip.IsPrivate(): // 10/8, 172.16/12, 192.168/16, fc00::/7 + return false + case ip.IsLinkLocalUnicast(): // 169.254/16, fe80::/10 (covers cloud metadata) + return false + case ip.IsLinkLocalMulticast() || ip.IsMulticast(): + return false + case ip.IsUnspecified(): // 0.0.0.0, :: + return false + case ip.IsInterfaceLocalMulticast(): + return false + case ip == blockedMetadataV4: + return false + case !ip.IsGlobalUnicast(): + // Reject anything not a routable global-unicast address (reserved, + // benchmarking, documentation ranges, etc.) — fail closed. + return false + default: + return true + } +} + +// dialControl returns a net.Dialer.Control hook that validates the actual +// resolved IP the socket is about to connect to — after DNS resolution, before +// the connect syscall. This is the rebinding/TOCTOU-proof core of the SSRF +// defense: a hostname that resolves "public" at validation time but "private" at +// connect time is still caught, because every dial (including each redirect hop's +// dial) runs through here against the literal connect address Go hands us. +func dialControl(allowPrivate bool) func(network, address string, c syscall.RawConn) error { + return func(network, address string, _ syscall.RawConn) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + // Control is called with a resolved host:port; a parse failure is + // unexpected — fail closed. + return fmt.Errorf("%w: unparseable dial address %q", errBlockedIP, address) + } + ip, err := netip.ParseAddr(host) + if err != nil { + // Go resolves the hostname to an IP literal before calling Control, + // so a non-IP host here is anomalous — fail closed. + return fmt.Errorf("%w: non-IP dial host %q", errBlockedIP, host) + } + if !ipAllowed(ip, allowPrivate) { + return fmt.Errorf("%w: %s", errBlockedIP, ip) + } + return nil + } +} + +// canonicalHost normalizes a hostname so both sides of a blocklist comparison +// see the same string the transport will actually dial. +// +// net/http runs a non-ASCII host through idna.Lookup.ToASCII (UTS-46) in +// canonicalAddr before dialing, and UTS-46 maps U+3002 IDEOGRAPHIC FULL STOP, +// U+FF0E FULLWIDTH FULL STOP and U+FF61 HALFWIDTH IDEOGRAPHIC FULL STOP to an +// ASCII dot. Comparing the raw host would therefore read "evil\u3002com" as one +// label (no blocklist hit) while the socket connects to evil.com. Applying the +// same profile the transport uses closes that gap. A host the profile rejects +// is left as-is: canonicalAddr keeps the raw form on error too, so the raw +// comparison remains the accurate one. +func canonicalHost(h string) string { + h = strings.ToLower(strings.Trim(h, "[]")) + if ascii, err := idna.Lookup.ToASCII(h); err == nil { + h = strings.ToLower(ascii) + } + // A trailing dot (evil.com.) is the DNS-absolute spelling of evil.com; a + // leading dot (.evil.com) is the conventional wildcard spelling of a + // blocklist entry. Trim both ends so the two sides of the suffix match in + // hostAllowed line up regardless of which spelling either used. + return strings.Trim(h, ".") +} + +// hostAllowed validates a URL host string (the "host" or "host:port" from a +// parsed URL) against the optional domain blocklist. A domain entry blocks both +// itself and every subdomain at a label boundary (evil.com blocks +// img.evil.com, never notevil.com). The IP-level deny policy is enforced at dial +// time by the Control hook; this catches name-based blocklist entries (and +// IP-literal hosts that match a blocklist entry) up front. +func hostAllowed(host string, blocklist map[string]bool) error { + h := host + if hp, _, err := net.SplitHostPort(host); err == nil { + h = hp + } + // parseBlocklist canonicalizes entries through the same helper, so an + // operator entry and a request host always meet in the same namespace. + h = canonicalHost(h) + if h == "" { + return fmt.Errorf("%w: empty host", errBlockedHost) + } + for blocked := range blocklist { + if h == blocked || strings.HasSuffix(h, "."+blocked) { + return fmt.Errorf("%w: destination matches blocklist", errBlockedHost) + } + } + return nil +} diff --git a/coordinator/mediafetch/ssrf_test.go b/coordinator/mediafetch/ssrf_test.go new file mode 100644 index 0000000000..0af9bc0531 --- /dev/null +++ b/coordinator/mediafetch/ssrf_test.go @@ -0,0 +1,212 @@ +package mediafetch + +import ( + "errors" + "net/netip" + "net/url" + "testing" +) + +func TestIPAllowed(t *testing.T) { + cases := []struct { + ip string + allowPrivate bool + want bool + }{ + // Public addresses are allowed under the strict policy. + {"8.8.8.8", false, true}, + {"1.1.1.1", false, true}, + {"93.184.216.34", false, true}, // example.com + {"2606:4700:4700::1111", false, true}, + {"::ffff:8.8.8.8", false, true}, // IPv4-mapped public + + // Loopback / private / link-local / metadata / unspecified are blocked. + {"127.0.0.1", false, false}, + {"127.10.20.30", false, false}, + {"10.0.0.1", false, false}, + {"172.16.5.4", false, false}, + {"192.168.1.1", false, false}, + {"169.254.169.254", false, false}, // cloud metadata + {"169.254.1.1", false, false}, // link-local + {"0.0.0.0", false, false}, + {"::1", false, false}, + {"fc00::1", false, false}, // IPv6 ULA + {"fe80::1", false, false}, // IPv6 link-local + {"::ffff:127.0.0.1", false, false}, // IPv4-mapped loopback (bypass attempt) + {"::ffff:192.168.1.1", false, false}, // IPv4-mapped private + {"::ffff:169.254.169.254", false, false}, // IPv4-mapped metadata + {"224.0.0.1", false, false}, // multicast + {"::", false, false}, // unspecified IPv6 + + // Ranges the stdlib helpers report as global-unicast but must still be + // blocked (these slip past IsPrivate/IsGlobalUnicast). + {"64:ff9b::7f00:1", false, false}, // NAT64 of 127.0.0.1 (loopback bypass) + {"64:ff9b::a00:1", false, false}, // NAT64 of 10.0.0.1 + {"64:ff9b:1::1", false, false}, // NAT64 local-use prefix + {"::7f00:1", false, false}, // IPv4-compatible 127.0.0.1 + {"::a00:1", false, false}, // IPv4-compatible 10.0.0.1 + {"2002:7f00:1::1", false, false}, // 6to4 embedding 127.0.0.1 + {"2002:a9fe:a9fe::1", false, false}, // 6to4 embedding metadata 169.254.169.254 + {"2001:0000:4136:e378:8000:63bf:3fff:fdd2", false, false}, // Teredo + {"100.64.0.1", false, false}, // CGNAT / RFC 6598 + {"100.127.255.1", false, false}, // CGNAT upper bound + {"198.18.0.1", false, false}, // benchmarking + {"192.0.2.5", false, false}, // TEST-NET-1 + {"240.0.0.1", false, false}, // reserved + {"255.255.255.255", false, false}, // broadcast (in 240/4) + {"2001:db8::1", false, false}, // IPv6 documentation + {"192.88.99.1", false, false}, // deprecated 6to4 relay anycast + {"fec0::1", false, false}, // deprecated IPv6 site-local + {"0.0.0.1", false, false}, // 0.0.0.0/8 "this network" (IsUnspecified only matches 0.0.0.0) + {"0.255.255.255", false, false}, // 0.0.0.0/8 upper bound + + // IPv4-mapped forms whose ONLY deny path is blockedPrefixes: netip's + // IsLoopback/IsPrivate/IsLinkLocalUnicast are themselves 4-in-6 aware, so + // the ::ffff:127.0.0.1-style cases above stay blocked even without the + // Unmap. These ranges have no such helper — Prefix.Contains compares the + // 16-byte form and never matches an IPv4 prefix — so each of these fails + // if `if ip.Is4In6() { ip = ip.Unmap() }` is removed from ipAllowed. + {"::ffff:100.64.0.1", false, false}, // IPv4-mapped CGNAT + {"::ffff:198.18.0.1", false, false}, // IPv4-mapped benchmarking + {"::ffff:240.0.0.1", false, false}, // IPv4-mapped reserved + {"::ffff:192.0.2.5", false, false}, // IPv4-mapped TEST-NET-1 + + // Zoned IPv6: netip.Prefix.Contains returns false for ANY address that + // carries a zone, so a "%zone" suffix skips the whole blockedPrefixes + // loop unless ipAllowed strips it first. The zone survives url.Parse → + // u.Hostname() → canonicalAddr → the dialer Control hook, and an unknown + // zone name resolves to ZoneId 0 so the kernel dials the bare address. + // Each of these fails if `ip = ip.WithZone("")` is removed. + {"64:ff9b::a9fe:a9fe%eth0", false, false}, // NAT64 of metadata 169.254.169.254 + {"64:ff9b::7f00:1%eth0", false, false}, // NAT64 of loopback + {"2002:7f00:1::1%z", false, false}, // 6to4 embedding 127.0.0.1 + {"::7f00:1%z", false, false}, // IPv4-compatible 127.0.0.1 + {"2001::1%z", false, false}, // Teredo + {"fec0::1%z", false, false}, // deprecated IPv6 site-local + + // allowPrivate (dev/test) permits private/loopback but still blocks the + // unspecified address. + {"127.0.0.1", true, true}, + {"192.168.1.1", true, true}, + {"0.0.0.0", true, false}, + } + for _, c := range cases { + ip := netip.MustParseAddr(c.ip) + if got := ipAllowed(ip, c.allowPrivate); got != c.want { + t.Errorf("ipAllowed(%s, allowPrivate=%v) = %v, want %v", c.ip, c.allowPrivate, got, c.want) + } + } +} + +func TestValidateURL(t *testing.T) { + cfg := DefaultConfig() + cfg.BlocklistDomains = map[string]bool{"evil.com": true} + cases := []struct { + raw string + wantErr error // nil = allowed + }{ + {"https://example.com/cat.jpg", nil}, + {"http://example.com", nil}, + {"HTTPS://Example.com/x", nil}, + {"http://example.com:80/x", nil}, + {"https://example.com:443/x", nil}, + {"http://example.com:8080/x", errBlockedHost}, + {"https://example.com:8443/x", errBlockedHost}, + {"ftp://example.com/x", errBlockedScheme}, + {"file:///etc/passwd", errBlockedScheme}, + {"gopher://example.com", errBlockedScheme}, + {"https://user:pass@example.com/x", errBlockedHost}, // embedded credentials + {"https://evil.com/x", errBlockedHost}, // blocklisted domain + {"https://EVIL.com/x", errBlockedHost}, // blocklist is case-insensitive + {"https://evil.com:8443/x", errBlockedHost}, // blocklist ignores port + {"https://images.evil.com/x", errBlockedHost}, // subdomain inherits parent block + {"https://not-evil.com/x", nil}, // suffix without label boundary is unrelated + + // UTS-46 maps these separators to an ASCII dot, and net/http's + // canonicalAddr runs the host through idna.Lookup.ToASCII before it + // dials. Matching the raw host would read each of these as ONE label + // (no blocklist hit) while the socket lands on evil.com. Each fails if + // the idna.Lookup.ToASCII normalization is removed from canonicalHost. + {"https://evil\u3002com/x", errBlockedHost}, // U+3002 IDEOGRAPHIC FULL STOP + {"https://img\uff0eevil\uff0ecom/x", errBlockedHost}, // U+FF0E FULLWIDTH FULL STOP + {"https://evil\uff61com/x", errBlockedHost}, // U+FF61 HALFWIDTH IDEOGRAPHIC FULL STOP + {"https://notevil\u3002com/x", nil}, // canonicalizes to notevil.com — must NOT over-block + } + for _, c := range cases { + u, err := url.Parse(c.raw) + if err != nil { + t.Fatalf("url.Parse(%q): %v", c.raw, err) + } + got := validateURL(u, cfg) + switch { + case c.wantErr == nil && got != nil: + t.Errorf("validateURL(%q) = %v, want nil", c.raw, got) + case c.wantErr != nil && !errors.Is(got, c.wantErr): + t.Errorf("validateURL(%q) = %v, want errors.Is %v", c.raw, got, c.wantErr) + } + } + + cfg.AllowNonStandardPorts = true + u, err := url.Parse("http://example.com:8080/x") + if err != nil { + t.Fatal(err) + } + if err := validateURL(u, cfg); err != nil { + t.Errorf("AllowNonStandardPorts=true must allow controlled dev/test origins: %v", err) + } +} + +// TestHostAllowedIDNACanonicalization pins the blocklist comparison to the +// namespace the transport actually dials in. Removing the idna.Lookup.ToASCII +// call from canonicalHost flips every "blocked: true" Unicode row to allowed. +func TestHostAllowedIDNACanonicalization(t *testing.T) { + blocklist := parseBlocklist("evil.com") + cases := []struct { + host string + blocked bool + }{ + {"evil.com", true}, // plain-ASCII control + {"EVIL.COM", true}, // ASCII case folding + {"img.evil.com", true}, // ASCII subdomain + {"evil.com.", true}, // FQDN trailing dot + {"example.com", false}, // plain-ASCII control, unrelated host + {"notevil.com", false}, // ASCII near-miss stays allowed + {"evil\u3002com", true}, // U+3002 IDEOGRAPHIC FULL STOP + {"EVIL\u3002com", true}, // mixed case + U+3002 + {"evil\uff0ecom", true}, // U+FF0E FULLWIDTH FULL STOP + {"evil\uff61com", true}, // U+FF61 HALFWIDTH IDEOGRAPHIC FULL STOP + {"img\u3002evil\u3002com", true}, // subdomain via mapped separators + {"evil\u3002com:443", true}, // host:port form + {"notevil\u3002com", false}, // maps to notevil.com — must NOT over-block + } + for _, c := range cases { + err := hostAllowed(c.host, blocklist) + if got := err != nil; got != c.blocked { + t.Errorf("hostAllowed(%q) blocked = %v, want %v (err=%v)", c.host, got, c.blocked, err) + } + if err != nil && !errors.Is(err, errBlockedHost) { + t.Errorf("hostAllowed(%q) = %v, want errors.Is errBlockedHost", c.host, err) + } + } +} + +func TestIsRemoteMediaURL(t *testing.T) { + cases := map[string]bool{ + "http://example.com/a.png": true, + "https://example.com/a.png": true, + " https://example.com/a.png ": true, + "HTTPS://example.com": true, + "data:image/png;base64,iVBORw0KGgo=": false, + "file:///etc/passwd": false, + "ftp://example.com/x": false, + "": false, + "https:/": false, + } + for in, want := range cases { + if got := isRemoteMediaURL(in); got != want { + t.Errorf("isRemoteMediaURL(%q) = %v, want %v", in, got, want) + } + } +} + +// Sniffing/allowlist/pixel-cap tests live in sniff_test.go. diff --git a/coordinator/registry/registry.go b/coordinator/registry/registry.go index 6417d70de7..03de480d48 100644 --- a/coordinator/registry/registry.go +++ b/coordinator/registry/registry.go @@ -453,14 +453,20 @@ func (pr *PendingRequest) MarkRouteOutcomeFinalized() bool { } type RequestTiming struct { - ReceivedAt time.Time // handler entry - ParsedAt time.Time // after parse + validate - ReservedAt time.Time // after balance reservation - RoutedAt time.Time // after provider selection (including queue wait) - EncryptedAt time.Time // after E2E encryption - QueuedAt time.Time // set when request enters the queue - DispatchedAt time.Time // set when request is sent to provider via WebSocket - FirstChunkAt time.Time // set when first inference chunk (incl. held boilerplate) arrives from provider + ReceivedAt time.Time // handler entry + ParsedAt time.Time // after parse + validate + ReservedAt time.Time // after balance reservation + // MediaFetchedAt is set when remote media URLs were fetched and inlined + // post-reservation (api.resolveRemoteMedia); zero when the request needed + // no fetches. It sits between ReservedAt and RoutedAt in the lifecycle and + // anchors the route segment so a multi-second media download is reported as + // media_fetch time, not routing time. + MediaFetchedAt time.Time + RoutedAt time.Time // after provider selection (including queue wait) + EncryptedAt time.Time // after E2E encryption + QueuedAt time.Time // set when request enters the queue + DispatchedAt time.Time // set when request is sent to provider via WebSocket + FirstChunkAt time.Time // set when first inference chunk (incl. held boilerplate) arrives from provider // FirstContentAt is set when the first CONTENT-bearing chunk is committed to // the client — i.e. excluding role-only / lifecycle boilerplate the dispatch // loop holds back. The reputation latency sample uses this so a provider that diff --git a/deploy/datadog/dev-network-dashboard.json b/deploy/datadog/dev-network-dashboard.json index 45fc9bcdde..dbfcff934c 100644 --- a/deploy/datadog/dev-network-dashboard.json +++ b/deploy/datadog/dev-network-dashboard.json @@ -695,6 +695,66 @@ } ] } + }, + { + "definition": { + "type": "timeseries", + "title": "Remote Media Refusals & Fetches", + "show_legend": true, + "legend_layout": "auto", + "requests": [ + { + "response_format": "timeseries", + "queries": [ + { + "name": "rejected", + "data_source": "metrics", + "query": "sum:d_inference.inference.media_fetch.rejected{$env} by {code}.as_count()" + }, + { + "name": "pre_fetch_rejected", + "data_source": "metrics", + "query": "sum:d_inference.inference.media_remote_url_rejected{$env}.as_count()" + }, + { + "name": "ok", + "data_source": "metrics", + "query": "sum:d_inference.inference.media_fetch.ok{$env}.as_count()" + } + ], + "formulas": [ + { "formula": "rejected", "alias": "rejected by code" }, + { "formula": "pre_fetch_rejected", "alias": "refused before fetch (sealed / unfetchable shape / disabled)" }, + { "formula": "ok", "alias": "fetched ok" } + ], + "display_type": "bars", + "style": { "palette": "warm" } + } + ] + } + }, + { + "definition": { + "type": "timeseries", + "title": "Remote Media Fetch Duration (p95) [ms]", + "show_legend": true, + "legend_layout": "auto", + "requests": [ + { + "response_format": "timeseries", + "queries": [ + { + "name": "p95", + "data_source": "metrics", + "query": "avg:d_inference.inference.media_fetch.duration_ms.95percentile{$env,model:$model} by {model}" + } + ], + "formulas": [ + { "formula": "p95" } + ] + } + ] + } } ] } diff --git a/deploy/environments/prod.env b/deploy/environments/prod.env index b9bf2b0d6b..94e1497907 100644 --- a/deploy/environments/prod.env +++ b/deploy/environments/prod.env @@ -74,3 +74,11 @@ EIGENINFERENCE_PROMPT_SIDECAR_RESTART_WINDOW_MS=60000 EIGENINFERENCE_PROMPT_SIDECAR_RESTART_MAX_IN_WINDOW=3 EIGENINFERENCE_PROMPT_SIDECAR_RESTART_COOLDOWN_MS=30000 EIGENINFERENCE_PROMPT_SIDECAR_STDERR_MAX_BYTES=16384 + +# Coordinator-side remote media (image_url / video_url) resolution. Enabled is +# the incident rollback lever: setting it false restores the previous 400 for +# remote URLs. Like every variable in this file it is read at process start, so +# the container must be recreated for a change to take effect. Every other +# EIGENINFERENCE_MEDIA_FETCH_* knob keeps its code default; the two SSRF +# overrides (ALLOW_PRIVATE_IPS, ALLOW_NONSTANDARD_PORTS) must stay unset here. +EIGENINFERENCE_MEDIA_FETCH_ENABLED=true diff --git a/deploy/gcp/prod/release-env-defaults b/deploy/gcp/prod/release-env-defaults index 647fb663bc..125066c45f 100644 --- a/deploy/gcp/prod/release-env-defaults +++ b/deploy/gcp/prod/release-env-defaults @@ -35,3 +35,4 @@ EIGENINFERENCE_PROMPT_SIDECAR_MAX_CONNECTIONS=64 EIGENINFERENCE_PROMPT_SIDECAR_MAX_LOADED_CONTRACTS=8 EIGENINFERENCE_PROMPT_SIDECAR_MAX_TOKENS=1048576 EIGENINFERENCE_PROMPT_SIDECAR_MEMORY_LIMIT_MIB=1024 +EIGENINFERENCE_MEDIA_FETCH_ENABLED=true diff --git a/docs/architecture/routing-telemetry-and-calibration.md b/docs/architecture/routing-telemetry-and-calibration.md index 6c56532340..ff1646b0cd 100644 --- a/docs/architecture/routing-telemetry-and-calibration.md +++ b/docs/architecture/routing-telemetry-and-calibration.md @@ -207,7 +207,7 @@ All already in `inference_routes`. These are the **inputs** the cost used. ### 4.6 Gaps to ADD to `inference_routes` (Phase 1) | **New field** | Why it matters | |-----------|----------------| -| **`parse_ms`, `reserve_ms`, `route_ms`, `encrypt_ms`, `queue_wait_ms`, `dispatch_ms`** | The `X-Timing` decomposition is computed per request and returned in a header but **thrown away**. This is our coordinator-side overhead budget — needed to separate "our latency" from "provider latency". Cheap: already on `pr.Timing`. | +| **`parse_ms`, `reserve_ms`, `media_fetch_ms`, `route_ms`, `encrypt_ms`, `queue_wait_ms`, `dispatch_ms`** | The `X-Timing` decomposition is computed per request and returned in a header but **thrown away**. `media_fetch_us` is emitted only when the request actually carried remote media that was fetched and inlined; `route_us` is anchored at the end of that fetch (not at reservation), so a multi-second origin download is never mis-attributed to routing latency. This is our coordinator-side overhead budget — needed to separate "our latency" from "provider latency". Cheap: already on `pr.Timing`. | | **`actual_queue_wait_ms`** | We store the queue *penalty estimate* (`queue_ms`) but not the *measured* wait (`EnqueuedAt → dispatch`). Without it we cannot validate the queue penalty. | | **`actual_decode_tps`** | Measured decode TPS for the completed request (`completion_tokens / decode_time`). The single most important calibration signal vs `effective_tps`. | | **`used_backup`, `backup_won`** | Speculative/backup-race dispatch happens (`raceBackupErrWaitPrimary`) but its win/loss is invisible. Tells us if speculation helps. | diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index f51dc83df6..bc4cfc7520 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -637,6 +637,24 @@ semantics is the code (`coordinator/registry/`, `coordinator/api/`); the highlig | `EIGENINFERENCE_CACHE_ROUTING_PERCENT`, `_MAX_PLAN_QPS` | Independent staged-rollout caps inside `on`. Preserve the current approved production stage; defaults apply only when bootstrapping a fresh environment. | | `EIGENINFERENCE_CACHE_MASTER_KEY` | Independent random 256-bit key required whenever routing is `on`. Preserve it byte-for-byte across releases; never derive from or reuse `MNEMONIC`, API, release, or database keys. | | `EIGENINFERENCE_IPAPI_KEY` | ip-api.com PRO key; unset falls back to the free 45 req/min tier | +| `EIGENINFERENCE_MEDIA_FETCH_ENABLED` | Default `true`. Master switch for coordinator-side resolution of remote `http(s)` `image_url`/`video_url` parts into inline `data:` URIs. **Incident rollback lever:** set `false` to restore the previous `400` for remote URLs (inline `data:` URIs keep working). Read once at process start, like every other variable here — editing the env file is **not** enough, the container must be recreated (see the container-swap procedure above). No image rebuild is needed. | +| `EIGENINFERENCE_MEDIA_FETCH_MAX_FILE_BYTES` | Default `8388608` (8 MiB). Cap on a single fetched media item, raw bytes before base64. | +| `EIGENINFERENCE_MEDIA_FETCH_MAX_TOTAL_BYTES` | Default `10485760` (10 MiB). Cap on the sum of all media fetched for one request (~13.3 MiB once inlined). Authoritative over `MAX_FILE_BYTES`: a per-file cap above this value fails boot. | +| `EIGENINFERENCE_MEDIA_FETCH_TIMEOUT_MS` | Default `15000`. Per-fetch deadline (connect + read) for one origin. | +| `EIGENINFERENCE_MEDIA_FETCH_TOTAL_DEADLINE_MS` | Default `25000`. Deadline for the whole resolution step across every part of a request. | +| `EIGENINFERENCE_MEDIA_FETCH_GLOBAL_CONCURRENCY` | Default `32`. Process-wide in-flight fetch cap — the bound on outbound sockets a media-heavy burst can open from the TEE. | +| `EIGENINFERENCE_MEDIA_FETCH_MAX_IMAGE_MEGAPIXELS` | Default `100`. Header-only pixel-bomb gate for every accepted image format; mirrors the provider's `DARKBLOOM_MAX_IMAGE_MEGAPIXELS`. `0` disables the coordinator-side check (the provider's own pre-raster cap still applies). | +| `EIGENINFERENCE_MEDIA_FETCH_BLOCKLIST_DOMAINS` | Default empty. Comma-separated hostnames refused for the initial request and every redirect hop. The IP-level SSRF policy applies regardless of this list. | +| `EIGENINFERENCE_MEDIA_FETCH_ALLOW_PRIVATE_IPS` | Default `false`. **Dev/test only — disables an SSRF protection.** `true` removes the connect-time deny policy for loopback/private/link-local/metadata/CGNAT addresses, letting the coordinator be aimed at the TEE's own network. Never set in prod; boot logs a WARN when it is on. | +| `EIGENINFERENCE_MEDIA_FETCH_ALLOW_NONSTANDARD_PORTS` | Default `false`. **Dev/test only — disables an SSRF protection.** `true` permits ports other than 80/443, turning the coordinator into a usable public-network port scanner. Never set in prod; boot logs a WARN when it is on. | + +Those ten `EIGENINFERENCE_MEDIA_FETCH_*` keys are the whole operator surface. Three further bounds — the post-inline body projection cap (16 MiB), the per-request part cap (8), and the per-request fetch worker count (4) — are compile-time constants in `coordinator/mediafetch/config.go` with no env var, on purpose: the first is protocol-derived (it mirrors the coordinator's own forwarded-body limit, so tuning it separately only moves where an oversized request fails), the second is matched to the provider's videos-per-request cap (changing one side desyncs the two), and the third is not a useful capacity lever — `GLOBAL_CONCURRENCY` is the one that bounds outbound sockets. + +Every numeric knob above is validated at boot: `AppConfig.Check()` → `mediafetch.Config.Check()` rejects any non-positive value and any `MAX_FILE_BYTES` above `MAX_TOTAL_BYTES`, so a typo (`MAX_TOTAL_BYTES=0`, `TIMEOUT_MS=-1`) aborts startup with a `media_fetch: ...` error naming the offending variable rather than silently reverting to a default the operator did not ask for. `MAX_IMAGE_MEGAPIXELS` is the one field where `0` is legal — it is the documented "coordinator-side pixel check off" value — so it is validated as `>= 0` and a negative (`MAX_IMAGE_MEGAPIXELS=-5`) fails boot rather than being quietly replaced by the 100 MP default. `NewResolver` still clamps out-of-range values as defense-in-depth for a programmatically supplied `ServerConfig.MediaFetch`, warning about whatever it had to clamp. + +The two `ALLOW_*` overrides are deliberately *not* boot errors — dev deployments need them — so they are surfaced as a `media fetch SSRF override enabled` WARN at construction instead. If that line appears in a prod coordinator's startup log, treat it as a misconfiguration incident. + +`EIGENINFERENCE_MEDIA_FETCH_ENABLED` ships as a `release-env-defaults` entry and is intentionally **not** listed in `required-env-keys.txt`: `refresh-env.sh` enforces the required-key manifest against the live `/etc/d-inference/env` *before* merging release defaults, so listing a key that no host has yet would fail both `--check` and `--apply`. This matches how every `EIGENINFERENCE_CACHE_ROUTING_*` and `EIGENINFERENCE_PROMPT_SIDECAR_*` key was introduced; it can be promoted into the manifest in a later release, once the key exists on every host. ## Troubleshooting diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index c0c152f987..82d77a0206 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -2392,3 +2392,208 @@ threats: detection_hint: > Every new chip/model or macOS release needs GPU-load correlation and full engage/release/restore hardware validation before support is claimed. + + # ── TB-001: Coordinator-side remote media fetching (mediafetch) ── + + - id: T-049 + trust_boundary: TB-001 + stride: Spoofing + title: SSRF / resource abuse via consumer-supplied remote media URLs + description: > + The coordinator fetches remote http(s) image_url/video_url links from chat + completion requests and inlines them as base64 data: URIs before sealing the + body to a provider (coordinator/mediafetch, api/media_resolve.go; default ON, + EIGENINFERENCE_MEDIA_FETCH_ENABLED kill switch). This makes the coordinator — + the TEE control plane — issue attacker-chosen outbound HTTP requests: the + classic SSRF surface (internal services, cloud metadata, DNS rebinding, + redirect laundering), plus resource abuse (decompression/pixel bombs, slow + origins, fetch storms) and a privacy side channel (the URL's origin observes + coordinator egress correlated with a request). The provider-side data:-only + guard is unchanged, so providers never fetch anything (their SSRF posture is + not affected). + adversaries: [ADV-002, ADV-003] + affected_assets: [A-001] + affected_files: + - coordinator/mediafetch/ssrf.go + - coordinator/mediafetch/fetch.go + - coordinator/mediafetch/budget.go + - coordinator/mediafetch/sniff.go + - coordinator/mediafetch/resolver.go + - coordinator/mediafetch/config.go + - coordinator/api/media_resolve.go + - coordinator/api/consumer.go + - coordinator/api/inference_admission.go + mitigations: + - description: > + Connect-time IP deny policy in net.Dialer.Control — runs on the + post-DNS-resolution address of EVERY dial including each redirect hop + (DNS-rebinding/TOCTOU-proof). The IPv6 scope zone is stripped before the + policy scan because netip.Prefix.Contains returns false for ANY zoned + address, which would otherwise let a "%zone" suffix skip the whole + prefix deny list. Denies loopback, RFC1918, link-local (incl. + 169.254.169.254 cloud metadata), CGNAT, "this network" 0.0.0.0/8, + IPv4-mapped IPv6, and IPv6 transition/compatibility spaces that can + embed/tunnel denied IPv4 destinations (IPv4-compatible ::/96, NAT64, + 6to4, Teredo, deprecated 6to4 relay anycast), plus deprecated + site-local, multicast, unspecified, benchmarking/documentation/reserved + ranges, and anything not global-unicast (mediafetch/ssrf.go ipAllowed, + fail-closed). + status: implemented + - description: > + URL policy: http/https schemes only, standard web ports only (HTTP 80, + HTTPS 443; non-standard ports require the explicit dev/test override + EIGENINFERENCE_MEDIA_FETCH_ALLOW_NONSTANDARD_PORTS), no embedded + credentials, redirect depth capped at 3 with per-hop re-validation and + the auto-populated Referer stripped on every hop (a presigned origin URL + in the query string never leaks to a redirect target), optional operator + domain blocklist that applies at DNS-label boundaries to each listed + domain and all of its subdomains + (EIGENINFERENCE_MEDIA_FETCH_BLOCKLIST_DOMAINS). Request hosts and + blocklist entries are canonicalized identically (canonicalHost: + lowercase, UTS-46 IDNA to ASCII, leading/trailing dots trimmed) so the + set the policy matches is the set net/http actually dials — a Unicode + separator homoglyph (U+3002/U+FF0E/U+FF61) cannot present one host to + the blocklist and another to the transport, and the conventional + wildcard spelling ".evil.com" cannot store a key that never matches. + status: implemented + - description: > + Content policy: data: URI built from magic-byte sniffing (never the + Content-Type header); explicit allowlist of provider-decodable formats + (JPEG/PNG/GIF/WebP/BMP; MP4/QuickTime) — HTML/SVG/executables/WebM fail + closed; declared part kind must match sniffed kind (image_url must be an + image); header-only megapixel parsing covers every accepted image format + (stdlib DecodeConfig for JPEG/PNG/GIF, explicit VP8/VP8L/VP8X and BMP DIB + parsing for WebP/BMP) and mirrors the provider's pre-raster pixel gate. + Provider decode-time caps (pixels, bytes, duration, frames) remain the + authoritative second layer. + status: implemented + - description: > + Resource bounds: per-file (8 MiB) cap via io.LimitReader plus one SHARED + per-request byte budget enforced during every concurrent read (10 MiB + + one overflow-sentinel byte, rather than checking only after each response + returns). Duplicate canonical URLs are fetched and byte-accounted once + and rewritten at every request location, so the raw byte caps do NOT see + the per-location base64 multiplication: the projected inlined total + (sum over targets of the data: URI length, saturating arithmetic) is + therefore checked against MaxInlinedBytes (16 MiB, mirroring + api.maxInferenceBodyBytes) BEFORE the request map is mutated, so eight + parts sharing one 8 MiB URL are rejected instead of materializing an + ~85 MiB marshal buffer. Content-Length is only a pre-check. No + transparent decompression (gzip bombs), per-request worker cap (4), + process-wide fetch semaphore (32), per-fetch (15s) and whole-step (25s) + deadlines, and the post-inline body re-check against the 16 MiB + sealed-frame budget. Each fetch worker runs under saferun.Recover: the + goroutine parses fully attacker-controlled bytes off the HTTP handler + goroutine, where an unrecovered panic would be a process-wide fatal. + status: implemented + - description: > + Cost gating: fetching runs AFTER token-rate admission, the balance + reservation, and the catalog check (consumer.go phase-2 call site). The + pre-fetch reservation uses the greater of the raw-byte billing bound and + the media-aware 300/1500-soft-token estimate, so a caller funded only for + the short URL cannot drive egress. That floor is NOT an upper bound on + real vision tokens, so once the media is inlined the reservation is + re-taken against the post-inline byte bound + (topUpReservationForInlinedMedia) — without it, settlement's + 2x-reservation overage clamp would silently absorb the shortfall and + recompute the provider payout from the clamped total. Exclusive + self-route skips the balance reservation, so resolveRemoteMedia first + runs the self-route serve-ability check (selfRouteUnavailable) before any + fetch — a caller with no linked/online/capable machine gets the + self-route error without driving egress. The monetary reservation is + refunded on fetch failure and on a failed top-up; token-rate admission is + deliberately retained, matching other post-admission validation failures, + so failed URL probes consume quota. + status: implemented + - description: > + Sealed requests are never fetched: a sender-sealed payload carrying a + remote media URL is rejected pre-billing with a clear error + (gateRemoteMediaPreDispatch) — fetching would generate origin-observable + egress correlated with a payload the sender chose to seal. + status: implemented + - description: > + Consumer-facing fetch errors carry only generic messages (media_blocked, + media_too_large, …). Coordinator logs record stable code/status fields + only; request URLs, hosts, query strings, fragments, credentials, and + wrapped network errors are never logged because presigned media URLs + commonly contain secrets. The API cannot be used as a fine-grained + internal-network oracle beyond the allowed/blocked bit. + status: implemented + - description: > + Configuration integrity: every numeric bound is validated at boot + (AppConfig.Check -> mediafetch.Config.Check), so an operator typo + (MAX_PARTS=0, TIMEOUT_MS=-1) aborts startup instead of silently reverting + to a default; NewResolver additionally clamps and WARNs for a + programmatically supplied ServerConfig.MediaFetch, and WARNs whenever + ALLOW_PRIVATE_IPS or ALLOW_NONSTANDARD_PORTS is on so a production + process running without the full SSRF policy is visible in the logs. + status: implemented + - description: > + Redirect chains cannot silently downgrade transport: a hop to http is + refused when any earlier hop used https (redirectGuard), so a caller who + supplied an https URL keeps confidentiality and integrity for the whole + chain — a redirect's signed query never crosses the network in plaintext + and an on-path party cannot substitute the bytes before they are inlined + into the encrypted provider request. Response headers are capped at + 64 KiB (MaxResponseHeaderBytes): headers are read before any body budget + applies and Go's 10 MiB default would let an attacker-owned origin force + GlobalConcurrency x 10 MiB of buffering while every body stayed in budget. + status: implemented + - description: > + Residual (accepted): the blocked/allowed distinction plus timing still + leaks coarse reachability of public HTTP/HTTPS origins on ports 80/443 + from the coordinator's egress IP; origins learn the coordinator fetches + on behalf of requests. + Operators can disable the feature per deployment via + EIGENINFERENCE_MEDIA_FETCH_ENABLED=false, which authoritatively restores + the pre-dispatch 400. The switch is read at process start like every + other coordinator env var, so an incident rollback requires recreating + the container — editing the env file alone does not affect a running + process. An earlier revision of this entry claimed a live per-request + re-read; that was wrong (os.Getenv returns the environment captured at + exec) and the code no longer pretends otherwise. + status: implemented + - description: > + Residual (accepted): on the public route a funded caller whose model IS + served by vision-capable providers, but whose providers are momentarily + at capacity, drives the fetch and then receives a 429/503 from + runInferenceAdmission with the monetary reservation refunded. Fleet + ELIGIBILITY is already gated before any fetch (visionToolsFailFast -> + HasVisionProviderForModel / HasToolCapableProviderForModel, which run + ahead of the media gate), so only transient capacity is affected, and + token-rate admission is charged before the fetch and never refunded, so + repeat probing consumes the caller's ITPM quota. Duplicating the + capacity preflight ahead of resolution was rejected deliberately: the + admission gate needs the POST-inline traits (MinPrefixCacheProtocol is + derived from body size), so a pre-fetch copy would either answer from + the wrong body or have to be kept in sync with the real gate, and it + would still race. + status: accepted + - description: > + Residual (accepted): on the exclusive self-route path the pre-fetch + serve-ability check uses the traits derived from the PRE-inline body, so + a size-derived trait that only inlining raises (MinPrefixCacheProtocol, + computed from body size) cannot be known before the fetch. An owner + whose only machine is a protocol-0 build can therefore drive one capped + fetch and then be rejected by runInferenceAdmission. Assuming the + higher protocol floor pre-emptively was rejected: most inlined media + stays far below the threshold, so it would falsely reject self-route + requests that would have succeeded. The exposure is one fetch, bounded + by the per-request byte caps, on a caller's own hardware. + status: accepted + open_findings: [] + severity: high + detection_hint: > + Any change that adds a coordinator-side fetch of a consumer-supplied URL + outside coordinator/mediafetch, weakens ipAllowed (new allowlisted range, + Is4In6 unmapping, IPv6 zone stripping, or transition-space denies removed), + diverges host canonicalization from net/http's idna.Lookup profile, permits + non-standard ports by default, allows an https to http redirect downgrade, + unsets MaxResponseHeaderBytes, lifts DisableCompression, removes the shared + read-time byte budget or the projected-inlined-size check, drops + saferun.Recover from the fetch workers, lets the deduplication key rewrite + the URL that is actually fetched, trusts the response Content-Type header, + skips image-header dimension parsing, moves resolveRemoteMedia before the + balance reservation, skips the post-inline reservation top-up, forwards a + body to a provider that was captured before inlining, or fetches for sealed + requests must be treated as high severity. diff --git a/go.mod b/go.mod index 66ff4d742c..53a270bd05 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/stretchr/testify v1.11.1 go.etcd.io/bbolt v1.4.3 golang.org/x/crypto v0.51.0 + golang.org/x/net v0.55.0 golang.org/x/time v0.15.0 gopkg.in/DataDog/dd-trace-go.v1 v1.74.8 nhooyr.io/websocket v1.8.17 @@ -93,7 +94,6 @@ require ( go.uber.org/zap v1.27.0 // indirect golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect golang.org/x/mod v0.35.0 // indirect - golang.org/x/net v0.55.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.45.0 // indirect golang.org/x/text v0.37.0 // indirect