Repository navigation
feat(coordinator): safely fetch and inline remote media URLs - #530
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 2 finding(s) (2 blocking)
- 🟡 [MEDIUM]
coordinator/mediafetch/fetch.go:114-121— HTTP request construction with user-controlled URL could enable header injection- Suggestion: Validate that parsed URL components don't contain newlines or other control characters that could inject headers
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:88-107— Remote media resolution lacks comprehensive URL validation before network operations- Suggestion: Add stricter validation of URL components (path, query, fragment) to prevent potential bypass of SSRF protections
Performance — 3 finding(s) (3 blocking)
- 🔴 [CRITICAL]
coordinator/mediafetch/resolver.go:148-197— Unbounded goroutine creation in fetchAll without proper context cancellation- Suggestion: The fetchAll method creates one goroutine per media reference without limiting concurrency upfront. While there's a per-request semaphore (line 153), goroutines are spawned before acquiring it, potentially creating hundreds of goroutines that block on semaphore acquisition. Consider using an errgroup with SetLimit() or pre-allocating a worker pool to bound goroutine creation.
- 🟡 [MEDIUM]
coordinator/mediafetch/fetch.go:147-149— Synchronous io.ReadAll on hot path without streaming- Suggestion: The fetchOne method uses io.ReadAll to buffer entire media files (up to 8MB per file) synchronously. For large images/videos, this blocks the goroutine and can cause memory pressure under concurrent load. Consider implementing streaming validation or chunked processing to reduce memory footprint and improve responsiveness.
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:158-170— JSON re-marshaling after every media resolution- Suggestion: When media URLs are inlined, the entire request body is re-marshaled via marshalForwardBody (line 158). For requests with multiple media items, this could be optimized by tracking which parts changed and doing incremental updates, or by deferring marshaling until all media is resolved.
Type_diligence — 3 finding(s) (3 blocking)
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:69— Missing type assertion check for mediaRef.set map access- Suggestion: Add type assertion check: if set, ok := pm[key].(map[string]any); !ok { return mediaRef{}, false }
- 🔴 [CRITICAL]
coordinator/api/media_resolve.go:82— Missing type assertion check in mediaPartURLString call- Suggestion: Add type assertion validation before calling mediaPartURLString to ensure pm is a valid map[string]any
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:295— Missing type assertion check for URL extraction from map- Suggestion: Add type assertion check: if u, ok := v["url"].(string); !ok { return mediaRef{}, false }
Additive_complexity — 1 finding(s)
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:304— mediaKeyForType function has only two cases and could be simplified- Suggestion: Consider inlining this logic into the caller or using a simple map lookup instead of a function with hardcoded cases
9 finding(s) total, 8 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
|
|
||
| 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: err.Error()} | ||
| } | ||
| req.Header.Set("Accept", "image/*,video/*") | ||
| req.Header.Set("Accept-Encoding", "identity") // belt-and-suspenders with DisableCompression |
There was a problem hiding this comment.
🟡 [MEDIUM] 🔒 HTTP request construction with user-controlled URL could enable header injection
💡 Suggestion: Validate that parsed URL components don't contain newlines or other control characters that could inject headers
📊 Score: 3×4 = 12 · Category: command-injection
| // 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.cfg.Enabled { | ||
| 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"} | ||
| } | ||
| if len(refs) > r.cfg.MaxParts { | ||
| return Result{}, &Error{Status: http.StatusBadRequest, Code: "too_many_media_parts", | ||
| Public: fmt.Sprintf("too many remote media items (%d); the maximum is %d", len(refs), r.cfg.MaxParts), | ||
| Internal: fmt.Sprintf("%d refs > MaxParts %d", len(refs), r.cfg.MaxParts)} | ||
| } | ||
|
|
||
| // Bound the whole resolution step (independent of the request TTFT deadline). | ||
| resolveCtx, cancel := context.WithTimeout(ctx, r.cfg.TotalDeadline) | ||
| defer cancel() |
There was a problem hiding this comment.
🟡 [MEDIUM] 🔒 Remote media resolution lacks comprehensive URL validation before network operations
💡 Suggestion: Add stricter validation of URL components (path, query, fragment) to prevent potential bypass of SSRF protections
📊 Score: 4×3 = 12 · Category: missing-input-validation
| ctxCancelled := func() { | ||
| 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, ref := range refs { | ||
| wg.Add(1) | ||
| go func(i int, ref mediaRef) { | ||
| defer wg.Done() | ||
| // 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, ref, r.cfg.MaxFileBytes, totalBudget) | ||
| if e != nil { | ||
| r.logger.Warn("media fetch rejected", "error", e) | ||
| 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, ref) | ||
| } |
There was a problem hiding this comment.
🔴 [CRITICAL] ⚡ Unbounded goroutine creation in fetchAll without proper context cancellation
💡 Suggestion: The fetchAll method creates one goroutine per media reference without limiting concurrency upfront. While there's a per-request semaphore (line 153), goroutines are spawned before acquiring it, potentially creating hundreds of goroutines that block on semaphore acquisition. Consider using an errgroup with SetLimit() or pre-allocating a worker pool to bound goroutine creation.
📊 Score: 4×4 = 16 · Category: unbounded_goroutines
| // 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. |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Synchronous io.ReadAll on hot path without streaming
💡 Suggestion: The fetchOne method uses io.ReadAll to buffer entire media files (up to 8MB per file) synchronously. For large images/videos, this blocks the goroutine and can cause memory pressure under concurrent load. Consider implementing streaming validation or chunked processing to reduce memory footprint and improve responsiveness.
📊 Score: 3×3 = 9 · Category: blocking_io_hot_path
| return rawBody, 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")) |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ JSON re-marshaling after every media resolution
💡 Suggestion: When media URLs are inlined, the entire request body is re-marshaled via marshalForwardBody (line 158). For requests with multiple media items, this could be optimized by tracking which parts changed and doing incremental updates, or by deferring marshaling until all media is resolved.
📊 Score: 3×4 = 12 · Category: repeated_work
| // Enabled reports whether remote-media fetching is turned on. | ||
| func (r *Resolver) Enabled() bool { return r.cfg.Enabled } | ||
|
|
||
| // mediaRef points at one resolvable URL inside the parsed request: the map that |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Missing type assertion check for mediaRef.set map access
💡 Suggestion: Add type assertion check: if set, ok := pm[key].(map[string]any); !ok { return mediaRef{}, false }
📊 Score: 4×3 = 12 · Category: missing_type_assertion
| return "", true | ||
| } | ||
| for _, p := range parts { | ||
| pm, isMap := p.(map[string]any) |
There was a problem hiding this comment.
🔴 [CRITICAL] 🏷️ Missing type assertion check in mediaPartURLString call
💡 Suggestion: Add type assertion validation before calling mediaPartURLString to ensure pm is a valid map[string]any
📊 Score: 4×4 = 16 · Category: missing_type_assertion
| func mediaRefFromPart(pm map[string]any, key string, kind mediaKind) (mediaRef, bool) { | ||
| switch v := pm[key].(type) { | ||
| case string: | ||
| if isRemoteMediaURL(v) { |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Missing type assertion check for URL extraction from map
💡 Suggestion: Add type assertion check: if u, ok := v["url"].(string); !ok { return mediaRef{}, false }
📊 Score: 4×3 = 12 · Category: missing_type_assertion
| } | ||
| } | ||
| return mediaRef{}, false | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 mediaKeyForType function has only two cases and could be simplified
💡 Suggestion: Consider inlining this logic into the caller or using a simple map lookup instead of a function with hardcoded cases
📊 Score: 2×3 = 6 · Category: over-abstraction
|
This PR introduces the coordinator-side remote media fetch subsystem ( Trust Boundaries Touched
Threat AnalysisT-049 — SSRF / resource abuse via consumer-supplied remote media URLs✅ Substantially strengthens the mitigation — this PR is the implementation of T-049's mitigations. Specific checks:
One residual concern on
T-002 — Unbounded request body causes coordinator OOMℹ️ Neutral — T-005 — Consumer denies inference requests / billing chargesℹ️ Neutral — T-031 — Provider earnings enumerable without authℹ️ Neutral — T-040 — Host header injection influences generated URLsℹ️ Neutral — T-004, T-021, T-024 — Admin/MDM/auth surface in
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2f3a65490a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
| // Internal carries the URL/host/cause for operators; the consumer gets | ||
| // only the generic Public message (no internal host/DNS leakage). | ||
| s.logger.Warn("remote media rejected", "code", me.Code, "status", me.Status, "detail", me.Internal) |
There was a problem hiding this comment.
Redact remote media URLs before logging
When a media fetch is rejected, me.Internal is logged verbatim; the mediafetch errors populate that field with the original URL for cases like upstream 4xx, oversize bodies, empty bodies, and parse errors. For users passing presigned S3/R2/GCS URLs or tokens in query strings, a failed fetch now persists request content/secrets in coordinator logs even though the consumer-facing error is redacted. Log only a redacted URL/host or structured cause here.
Useful? React with 👍 / 👎.
| continue | ||
| } | ||
| if ref, ok := mediaRefFromPart(pm, key, kind); ok { | ||
| refs = append(refs, ref) |
There was a problem hiding this comment.
Deduplicate identical media URLs before fetching
When the same http(s) media URL appears in multiple image_url/video_url parts, every occurrence is appended and later fetched independently. This violates the intended fetch-once-per-URL behavior, creates duplicate origin-visible hits, and charges MaxParts/MaxTotalBytes per duplicate; for example, reusing the same 6 MiB image twice will be rejected by the 10 MiB aggregate cap even though only one unique file needs downloading. Cache the fetched result by URL and rewrite all matching refs from that single fetch.
Useful? React with 👍 / 👎.
| if !isMedia || ref == "" { | ||
| continue | ||
| } | ||
| if !isInlineDataURI(ref) && !fetchable[ref] { |
There was a problem hiding this comment.
Reject unsupported media parts even when URLs repeat
This check treats a media reference as fetchable solely because its URL string appears in any OpenAI image_url/video_url part. If a request includes a supported image_url and an unsupported media shape such as an Anthropic source:{type:"url"} block with the same URL, the unsupported block is allowed through, but Resolve only rewrites the OpenAI part, leaving the remote URL in the provider-bound body and risking the image-blind/provider-400 behavior this gate was meant to prevent. Track fetchable refs by their location/shape, or always reject unsupported media shapes regardless of URL equality.
Useful? React with 👍 / 👎.
…t floor Codex/review round on PR #530: - URL dedupe: canonicalize (drop fragment, lowercase scheme/host, strip default ports) so an equivalent URL fetches once and rewrites every location; reject cross-kind reuse of one URL before any network I/O. Keep a pre-dedup total-target cap so duplicate targets can't expand into an oversized base64 body (MaxParts on refs, byte accounting on unique fetches). - Secret redaction: mediafetch.Error.Internal never carries the URL/host/ query/cause, and the API layer logs only code+status — presigned S3/R2 URLs can't leak into coordinator logs. - Shape-based gate: firstUnfetchableRemoteRef judges each part by its own shape/location via mediafetch.IsFetchableRemotePart, so an unsupported Anthropic source block sharing a URL with an OpenAI part still 400s. - Blocklist: parent-domain entries match at DNS-label boundaries (evil.com blocks img.evil.com, not notevil.com). - Cost floor: reserve against max(byte-bound, media-aware estimate) before fetch so a URL-only-funded caller can't drive coordinator egress. - Rollback: EIGENINFERENCE_MEDIA_FETCH_ENABLED=false is authoritative and ignores the legacy DARKBLOOM_VISION_REJECT_REMOTE_URLS flag. - Cancellation: client cancel propagates as context.Canceled (no fake media_fetch_timeout telemetry / no response write). Tests + threat model T-043 updated; coordinator suite green with -race.
2f3a654 to
f23f780
Compare
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 2 finding(s) (1 blocking)
- 🟡 [MEDIUM]
coordinator/api/inference_admission.go:61-66— Potential integer overflow in reservation cost calculation- Suggestion: Add bounds checking before max() operation to prevent overflow when estimatedPromptTokens is extremely large
- 🔵 [INFO]
coordinator/mediafetch/fetch.go:114-121— User-Agent header contains static string without validation- Suggestion: Consider validating or sanitizing the User-Agent string to prevent header injection, though current static value appears safe
Performance — 4 finding(s) (4 blocking)
- 🟡 [MEDIUM]
coordinator/api/inference_admission.go:61-66— max() function call on every request creates unnecessary allocation overhead- Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:207-275— fetchAll spawns unbounded goroutines without proper error handling coordination- Suggestion: Use errgroup.WithContext to properly coordinate goroutine cancellation and error handling, ensuring all goroutines are cleaned up on first error
- 🟡 [MEDIUM]
coordinator/mediafetch/budget.go:45-62— reserve() blocks indefinitely waiting for budget availability- Suggestion: Add context-aware timeout to budget reservation to prevent indefinite blocking when other readers hold all capacity
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:155-180— marshalForwardBody re-marshals entire request body after media inlining- Suggestion: Consider incremental updates or caching marshaled portions to avoid full re-serialization of large request bodies
Type_diligence — 13 finding(s)
- 🔵 [INFO]
coordinator/api/media_resolve.go:32— map[string]any access without type assertion check- Suggestion: Add type assertion check: if parsed, ok := parsed.(map[string]any); !ok { return nil, false }
- 🔵 [INFO]
coordinator/api/media_resolve.go:101— []any type assertion without ok check- Suggestion: Change to: if msgs, ok := parsed["messages"].([]any); !ok { return "", true }
- 🔵 [INFO]
coordinator/api/media_resolve.go:103— map[string]any type assertion without ok check- Suggestion: Change to: if mm, ok := m.(map[string]any); !ok { continue }
- 🔵 [INFO]
coordinator/api/media_resolve.go:105— []any type assertion without ok check- Suggestion: Change to: if parts, ok := content.([]any); !ok { return "", true }
- 🔵 [INFO]
coordinator/api/media_resolve.go:111— []any type assertion without ok check- Suggestion: Change to: if input, ok := parsed["input"].([]any); !ok { return "", true }
- 🔵 [INFO]
coordinator/api/media_resolve.go:113— map[string]any type assertion without ok check- Suggestion: Change to: if im, ok := it.(map[string]any); !ok { continue }
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:325— []any type assertion without ok check- Suggestion: Change to: messages, ok := parsed["messages"].([]any); if !ok { return nil }
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:328— map[string]any type assertion without ok check- Suggestion: Change to: mm, ok := m.(map[string]any); if !ok { continue }
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:332— []any type assertion without ok check- Suggestion: Change to: parts, ok := mm["content"].([]any); if !ok { continue }
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:335— map[string]any type assertion without ok check- Suggestion: Change to: pm, ok := part.(map[string]any); if !ok { continue }
- 🔵 [INFO]
coordinator/mediafetch/resolver.go:380— string type assertion without ok check- Suggestion: Change to: if u, ok := v["url"].(string); ok && isRemoteMediaURL(u) {
- 🔵 [INFO]
coordinator/api/media_resolve_test.go:89— []any type assertion without ok check- Suggestion: Add ok check: parts, ok := parsed["messages"].([]any)[0].(map[string]any)["content"].([]any); if !ok { t.Fatal("invalid structure") }
- 🔵 [INFO]
coordinator/api/media_resolve_test.go:90-96— nested type assertions without ok checks- Suggestion: Add proper type assertion checks for the nested map/slice access pattern
Additive_complexity — 4 finding(s) (1 blocking)
- 🔵 [INFO]
coordinator/api/media_resolve.go:1-229— New 229-line file introduces complex media resolution system with single consumer- Suggestion: Consider whether this complexity is justified for the single use case, or if a simpler inline approach would suffice
- 🔵 [INFO]
coordinator/mediafetch/config.go:42-224— Extensive configuration system with 12+ environment variables for media fetching- Suggestion: Evaluate if all configuration knobs are necessary or if some could use sensible defaults without env var exposure
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:1-395— Large resolver implementation adds significant cognitive load with complex URL canonicalization and grouping logic- Suggestion: Consider breaking down the resolver into smaller, more focused components or simplifying the URL handling logic
- 🔵 [INFO]
coordinator/mediafetch/sniff.go:1-255— Custom media type detection and validation reimplements functionality available in standard libraries- Suggestion: Evaluate if existing libraries like net/http.DetectContentType plus image format libraries could handle most of this logic
23 finding(s) total, 6 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| // 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) |
There was a problem hiding this comment.
🟡 [MEDIUM] 🔒 Potential integer overflow in reservation cost calculation
💡 Suggestion: Add bounds checking before max() operation to prevent overflow when estimatedPromptTokens is extremely large
📊 Score: 3×4 = 12 · Category: missing-input-validation
|
|
||
| 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 |
There was a problem hiding this comment.
🔵 [INFO] 🔒 User-Agent header contains static string without validation
💡 Suggestion: Consider validating or sanitizing the User-Agent string to prevent header injection, though current static value appears safe
📊 Score: 2×2 = 4 · Category: missing-input-validation
| // 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) |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ max() function call on every request creates unnecessary allocation overhead
💡 Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| // (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() | ||
| // 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 | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ fetchAll spawns unbounded goroutines without proper error handling coordination
💡 Suggestion: Use errgroup.WithContext to properly coordinate goroutine cancellation and error handling, ensuring all goroutines are cleaned up on first error
📊 Score: 4×3 = 12 · Category: unbounded_goroutines
| // 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() | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ reserve() blocks indefinitely waiting for budget availability
💡 Suggestion: Add context-aware timeout to budget reservation to prevent indefinite blocking when other readers hold all capacity
📊 Score: 3×4 = 12 · Category: blocking_io
| } | ||
|
|
||
| func sealedReq() *http.Request { | ||
| req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) | ||
| return req.WithContext(context.WithValue(req.Context(), sealedCtxKey, struct{}{})) | ||
| } | ||
|
|
There was a problem hiding this comment.
🔵 [INFO] 🏷️ nested type assertions without ok checks
💡 Suggestion: Add proper type assertion checks for the nested map/slice access pattern
📊 Score: 3×2 = 6 · Category: missing_type_assertion
| 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 | ||
| } | ||
| if s.mediaResolver == nil || !s.mediaResolver.Enabled() { | ||
| // Resolver off means authoritative rollback to the data:-only contract; | ||
| // the older DARKBLOOM_VISION_REJECT_REMOTE_URLS switch must not override it. | ||
| return s.rejectRemoteMediaURLsAlways(w, r, parsed, model, publicModel, requiresVision, hasTools) | ||
| } | ||
| // Sender-sealed requests are never fetched: the sender opted into sealing | ||
| // the payload to the coordinator, and a fetch would leak request-correlated | ||
| // egress to the URL's origin. Reject with a clear next step. | ||
| if mediafetch.HasRemoteMedia(parsed) && isSealedRequest(r) { | ||
| s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, | ||
| "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") | ||
| return true | ||
| } | ||
| // 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). | ||
| if badRef, ok := firstUnfetchableRemoteRef(parsed); !ok { | ||
| s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, | ||
| "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(badRef)) | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // firstUnfetchableRemoteRef returns ok=false with the first remote/non-inline | ||
| // media reference that the mediafetch resolver will NOT fetch based on that | ||
| // part's own shape and location (not URL equality with another part). OpenAI | ||
| // image_url/video_url http(s) parts are fetchable only under messages[]; | ||
| // Anthropic/input_* shapes, non-http(s) schemes, and every Responses input[] | ||
| // media ref remain unsupported. Mirrors validateMediaParts' fail-open stance on | ||
| // unreadable shapes. | ||
| func firstUnfetchableRemoteRef(parsed map[string]any) (badRef string, ok bool) { | ||
| check := func(content any, allowFetchableShape bool) (string, bool) { | ||
| parts, isArr := content.([]any) | ||
| if !isArr { | ||
| return "", true | ||
| } | ||
| for _, p := range parts { | ||
| pm, isMap := p.(map[string]any) | ||
| if !isMap { | ||
| continue | ||
| } | ||
| ref, isMedia := mediaPartURLString(pm) | ||
| if !isMedia || ref == "" { | ||
| continue | ||
| } | ||
| if !isInlineDataURI(ref) { | ||
| if allowFetchableShape && mediafetch.IsFetchableRemotePart(pm) { | ||
| continue | ||
| } | ||
| return ref, false | ||
| } | ||
| } | ||
| return "", true | ||
| } | ||
| if msgs, isArr := parsed["messages"].([]any); isArr { | ||
| for _, m := range msgs { | ||
| if mm, isMap := m.(map[string]any); isMap { | ||
| if ref, good := check(mm["content"], true); !good { | ||
| return ref, false | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if input, isArr := parsed["input"].([]any); isArr { | ||
| for _, it := range input { | ||
| if im, isMap := it.(map[string]any); isMap { | ||
| if ref, good := check(im["content"], false); !good { | ||
| return ref, false | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return "", true | ||
| } | ||
|
|
||
| // mediaResolveMeta carries the request descriptors resolveRemoteMedia needs to | ||
| // record rejection telemetry with the same fidelity as the surrounding gates. | ||
| type mediaResolveMeta struct { | ||
| model string | ||
| publicModel string | ||
| stream bool | ||
| estimatedPromptTokens int | ||
| requestedMaxTokens int | ||
| hasTools bool | ||
| } | ||
|
|
||
| // 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 — 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. | ||
| func (s *Server) resolveRemoteMedia(w http.ResponseWriter, r *http.Request, rawBody []byte, parsed map[string]any, timing *registry.RequestTiming, meta mediaResolveMeta) ([]byte, bool) { | ||
| if s.mediaResolver == nil || !s.mediaResolver.Enabled() { | ||
| return rawBody, true | ||
| } | ||
|
|
||
| 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 | ||
| } | ||
| 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 | ||
| } | ||
| if !res.Changed { | ||
| return rawBody, 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 | ||
| } | ||
| // 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 | ||
| } | ||
|
|
||
| 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 | ||
| } | ||
|
|
||
| // 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 := "bad_param" | ||
| if status == http.StatusRequestEntityTooLarge { | ||
| reason = "payload_too_large" | ||
| } | ||
| 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"))) | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 New 229-line file introduces complex media resolution system with single consumer
💡 Suggestion: Consider whether this complexity is justified for the single use case, or if a simpler inline approach would suffice
📊 Score: 3×2 = 6 · Category: over-abstraction
| package mediafetch | ||
|
|
||
| import ( | ||
| "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" | ||
| envMaxParts = env.EnvPrefix + "_MEDIA_FETCH_MAX_PARTS" | ||
| envTimeoutMS = env.EnvPrefix + "_MEDIA_FETCH_TIMEOUT_MS" | ||
| envTotalDeadline = env.EnvPrefix + "_MEDIA_FETCH_TOTAL_DEADLINE_MS" | ||
| envConcurrency = env.EnvPrefix + "_MEDIA_FETCH_CONCURRENCY" | ||
| 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 — the body the coordinator | ||
| // re-marshals and seals), which is the binding constraint, not just the | ||
| // provider's 32 MiB WebSocket frame. Raw media of M bytes inflates to ~1.37*M as | ||
| // a base64 data: URI, so the aggregate raw cap must leave headroom under 16 MiB | ||
| // for the inlined media PLUS the rest of the request (prompt text, JSON | ||
| // structure, the coordinator-injected max_tokens). A 10 MiB aggregate raw cap | ||
| // inlines to ~13.3 MiB, leaving ~2.7 MiB for everything else — so a valid | ||
| // request is never fetched only to be rejected by the final 16 MiB body check. | ||
| // | ||
| // DefaultMaxImageMegapixels mirrors the provider's DARKBLOOM_MAX_IMAGE_MEGAPIXELS | ||
| // default (100 MP, header-read before rasterization) so the coordinator rejects | ||
| // pixel bombs before dispatch instead of shipping them 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) | ||
| 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 | ||
| // MaxParts caps the number of remote media URLs fetched per request. | ||
| 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. | ||
| 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 | ||
| } | ||
|
|
||
| // DefaultConfig returns the production defaults (feature enabled). | ||
| func DefaultConfig() Config { | ||
| return Config{ | ||
| Enabled: true, | ||
| MaxFileBytes: DefaultMaxFileBytes, | ||
| MaxTotalBytes: DefaultMaxTotalBytes, | ||
| 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 or unparseable. | ||
| func ConfigFromEnv() Config { | ||
| c := DefaultConfig() | ||
| c.Enabled = env.EnvBool(envEnabled, c.Enabled) | ||
| c.MaxFileBytes = int64(env.EnvInt(envMaxFileBytes, int(c.MaxFileBytes))) | ||
| c.MaxTotalBytes = int64(env.EnvInt(envMaxTotalBytes, int(c.MaxTotalBytes))) | ||
| c.MaxParts = env.EnvInt(envMaxParts, c.MaxParts) | ||
| c.FetchTimeout = time.Duration(env.EnvInt(envTimeoutMS, int(c.FetchTimeout/time.Millisecond))) * time.Millisecond | ||
| c.TotalDeadline = time.Duration(env.EnvInt(envTotalDeadline, int(c.TotalDeadline/time.Millisecond))) * time.Millisecond | ||
| c.Concurrency = env.EnvInt(envConcurrency, c.Concurrency) | ||
| c.GlobalConcurrency = env.EnvInt(envGlobalConc, c.GlobalConcurrency) | ||
| c.MaxImageMegapixels = env.EnvInt(envMaxMegapixels, c.MaxImageMegapixels) | ||
| c.BlocklistDomains = parseBlocklist(env.EnvOr(envBlocklist, "")) | ||
| c.AllowPrivateIPs = env.EnvBool(envAllowPrivateIP, c.AllowPrivateIPs) | ||
| c.AllowNonStandardPorts = env.EnvBool(envAllowOtherPorts, c.AllowNonStandardPorts) | ||
| return c.sanitized() | ||
| } | ||
|
|
||
| // 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.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 lowercased set. | ||
| func parseBlocklist(csv string) map[string]bool { | ||
| out := map[string]bool{} | ||
| for _, raw := range strings.Split(csv, ",") { | ||
| // Strip a trailing FQDN dot so "evil.com." and "evil.com" canonicalize the | ||
| // same way hostAllowed canonicalizes request hosts (no trailing-dot bypass). | ||
| h := strings.TrimRight(strings.ToLower(strings.TrimSpace(raw)), ".") | ||
| if h != "" { | ||
| out[h] = true | ||
| } | ||
| } | ||
| return out | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Extensive configuration system with 12+ environment variables for media fetching
💡 Suggestion: Evaluate if all configuration knobs are necessary or if some could use sensible defaults without env var exposure
📊 Score: 2×3 = 6 · Category: over-configuration
| 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" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "sync" | ||
| ) | ||
|
|
||
| // 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). | ||
| func NewResolver(cfg Config, logger *slog.Logger) *Resolver { | ||
| cfg = cfg.sanitized() | ||
| if logger == nil { | ||
| logger = slog.New(slog.DiscardHandler) | ||
| } | ||
| return &Resolver{ | ||
| cfg: cfg, | ||
| client: newHTTPClient(cfg), | ||
| logger: logger, | ||
| globalSem: make(chan struct{}, cfg.GlobalConcurrency), | ||
| } | ||
| } | ||
|
|
||
| // Enabled reports whether remote-media fetching is turned on. | ||
| 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.cfg.Enabled { | ||
| 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 | ||
| } | ||
|
|
||
| // All fetches succeeded — apply mutations atomically. | ||
| for i, fetch := range fetches { | ||
| dataURI := toDataURI(fetched[i]) | ||
| for _, target := range fetch.targets { | ||
| target.set[target.key] = dataURI | ||
| } | ||
| } | ||
| return Result{Changed: true, Count: len(fetches), Bytes: totalBytes}, nil | ||
| } | ||
|
|
||
| func groupMediaRefs(refs []mediaRef) ([]mediaFetch, error) { | ||
| fetches := make([]mediaFetch, 0, len(refs)) | ||
| byURL := make(map[string]int, len(refs)) | ||
| for _, ref := range refs { | ||
| canonical, err := canonicalMediaURL(ref.url) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| ref.url = canonical | ||
| if i, exists := byURL[ref.url]; 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 | ||
| } | ||
| byURL[ref.url] = len(fetches) | ||
| fetches = append(fetches, mediaFetch{request: ref, targets: []mediaRef{ref}}) | ||
| } | ||
| return fetches, nil | ||
| } | ||
|
|
||
| // canonicalMediaURL normalizes components that do not change the on-the-wire | ||
| // request target, so each target is fetched and kind-checked once: fragments are | ||
| // never sent by HTTP, scheme/host are case-insensitive, and explicit default | ||
| // ports are equivalent to omission. Path escaping and query order are preserved | ||
| // because origins can assign them application-specific semantics. | ||
| func canonicalMediaURL(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) | ||
| hostname := u.Hostname() | ||
| if !strings.Contains(hostname, ":") { | ||
| hostname = strings.ToLower(hostname) | ||
| } | ||
| port := u.Port() | ||
| if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") { | ||
| port = "" | ||
| } | ||
| switch { | ||
| case hostname == "": | ||
| u.Host = "" | ||
| case port != "": | ||
| u.Host = net.JoinHostPort(hostname, port) | ||
| case strings.Contains(hostname, ":"): | ||
| u.Host = "[" + hostname + "]" | ||
| default: | ||
| u.Host = hostname | ||
| } | ||
| 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() | ||
| // 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 | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Large resolver implementation adds significant cognitive load with complex URL canonicalization and grouping logic
💡 Suggestion: Consider breaking down the resolver into smaller, more focused components or simplifying the URL handling logic
📊 Score: 3×3 = 9 · Category: additive complexity
| 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) | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Custom media type detection and validation reimplements functionality available in standard libraries
💡 Suggestion: Evaluate if existing libraries like net/http.DetectContentType plus image format libraries could handle most of this logic
📊 Score: 2×2 = 4 · Category: reinventing stdlib
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f23f780fd7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return func(req *http.Request, via []*http.Request) error { | ||
| if len(via) >= maxRedirects { | ||
| return fmt.Errorf("%w: too many redirects (>%d)", errBlockedHost, maxRedirects) | ||
| } | ||
| return validateURL(req.URL, cfg) |
There was a problem hiding this comment.
Clear redirect Referer for fetched media
When a media URL returns a redirect, Go's net/http client automatically sets the next request's Referer to the previous URL, including its query string. For presigned S3/R2/GCS media links, this leaks the signed URL to the redirect target even though the fetcher intentionally avoids forwarding caller credentials or logging URLs; clear Referer in the redirect guard before allowing the redirected request to proceed.
Useful? React with 👍 / 👎.
| // they don't need the inlined bytes; the billing reservation is refunded on | ||
| // any failure. parsed is mutated in place, so the alias-fallback re-marshals | ||
| // below keep the inlined media. | ||
| rawBody, ok = s.resolveRemoteMedia(w, r, rawBody, parsed, timing, mediaResolveMeta{ |
There was a problem hiding this comment.
Check self-route availability before media fetch
With X-Darkbloom-Route: self, reserveInferenceBalance intentionally skips the balance reservation, but this fetch still runs before runInferenceAdmission calls selfRouteUnavailable. An authenticated user with no linked/offline/incapable machine can therefore trigger up to the media-fetch caps of coordinator egress and then receive the self-route error, bypassing the cost gate this block relies on; run the self-route availability check before resolving remote media or otherwise require a paid reservation when the request cannot actually be served locally.
Useful? React with 👍 / 👎.
…t floor Codex/review round on PR #530: - URL dedupe: canonicalize (drop fragment, lowercase scheme/host, strip default ports) so an equivalent URL fetches once and rewrites every location; reject cross-kind reuse of one URL before any network I/O. Keep a pre-dedup total-target cap so duplicate targets can't expand into an oversized base64 body (MaxParts on refs, byte accounting on unique fetches). - Secret redaction: mediafetch.Error.Internal never carries the URL/host/ query/cause, and the API layer logs only code+status — presigned S3/R2 URLs can't leak into coordinator logs. - Shape-based gate: firstUnfetchableRemoteRef judges each part by its own shape/location via mediafetch.IsFetchableRemotePart, so an unsupported Anthropic source block sharing a URL with an OpenAI part still 400s. - Blocklist: parent-domain entries match at DNS-label boundaries (evil.com blocks img.evil.com, not notevil.com). - Cost floor: reserve against max(byte-bound, media-aware estimate) before fetch so a URL-only-funded caller can't drive coordinator egress. - Rollback: EIGENINFERENCE_MEDIA_FETCH_ENABLED=false is authoritative and ignores the legacy DARKBLOOM_VISION_REJECT_REMOTE_URLS flag. - Cancellation: client cancel propagates as context.Canceled (no fake media_fetch_timeout telemetry / no response write). Tests + threat model T-043 updated; coordinator suite green with -race.
Second review round on PR #530 (new findings on the rebased head): - Redirect Referer leak: Go's http client auto-sets Referer to the previous hop on redirect. A presigned S3/R2/GCS media URL carries its signature in the query string, so a cross-host redirect would leak the signed URL to the redirect target. redirectGuard now strips Referer on every hop. - Self-route egress gate: exclusive self-route (X-Darkbloom-Route: self) skips the balance reservation, so no cost gate preceded the fetch. An authenticated caller with no linked/online/capable machine could drive up to the media-fetch caps of coordinator egress and only then get the self-route error. resolveRemoteMedia now runs selfRouteUnavailable before any fetch when the request is self-route and carries remote media. Tests for both; threat-model T-043 updated; coordinator suite green -race.
f23f780 to
3f92101
Compare
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s)
- 🔵 [INFO]
coordinator/mediafetch/fetch.go:126-127— User-Agent header hardcoded with project name- Suggestion: Consider using a generic user agent or making it configurable to avoid fingerprinting
Performance — 4 finding(s) (4 blocking)
- 🟡 [MEDIUM]
coordinator/api/inference_admission.go:61-66— max() function call on every request creates unnecessary allocation overhead- Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path
- 🟡 [MEDIUM]
coordinator/mediafetch/budget.go:76-88— budgetReader.Read() can block indefinitely waiting for budget reservation- Suggestion: Add context cancellation support to budget.reserve() to prevent indefinite blocking when clients disconnect
- 🔴 [CRITICAL]
coordinator/mediafetch/resolver.go:207-275— fetchAll spawns goroutines without proper context cancellation coordination- Suggestion: Use errgroup.WithContext instead of manual sync.WaitGroup to ensure proper cancellation propagation and resource cleanup
- 🟡 [MEDIUM]
coordinator/mediafetch/fetch.go:108-177— fetchOne performs redundant URL parsing and validation on every call- Suggestion: Move URL parsing and validation to the caller level to avoid re-parsing the same URLs multiple times during retries or duplicate fetches
Type_diligence — 9 finding(s) (9 blocking)
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:34— Missing type assertion check for parsed map[string]any access- Suggestion: Add type assertion check: if parsed, ok := parsed.(map[string]any); !ok { return false }
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:101— Missing type assertion check for messages slice access- Suggestion: Add type assertion check: if msgs, ok := parsed["messages"].([]any); !ok { return nil, true }
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:104— Missing type assertion check for message map access- Suggestion: Add type assertion check: if mm, ok := m.(map[string]any); !ok { continue }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:324— Missing type assertion check for messages slice access- Suggestion: Add type assertion check: if messages, ok := parsed["messages"].([]any); !ok { return nil }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:327— Missing type assertion check for message map access- Suggestion: Add type assertion check: if mm, ok := m.(map[string]any); !ok { continue }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:331— Missing type assertion check for content parts slice access- Suggestion: Add type assertion check: if parts, ok := mm["content"].([]any); !ok { continue }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:334— Missing type assertion check for part map access- Suggestion: Add type assertion check: if pm, ok := part.(map[string]any); !ok { continue }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:369— Missing type assertion check for media field map access- Suggestion: Add type assertion check: if v, ok := pm[key].(map[string]any); !ok { return mediaRef{}, false }
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:371— Missing type assertion check for url string access- Suggestion: Add type assertion check: if u, ok := v["url"].(string); !ok { return mediaRef{}, false }
Additive_complexity — 3 finding(s) (2 blocking)
- 🟡 [MEDIUM]
coordinator/api/media_resolve.go:1-253— New 253-line file introduces complex media resolution system with single consumer- Suggestion: Consider whether this complexity is justified for the single use case, or if a simpler inline approach would suffice
- 🟡 [MEDIUM]
coordinator/mediafetch/resolver.go:1-395— Large resolver package with extensive abstraction for media fetching- Suggestion: Evaluate if the full resolver abstraction is needed or if a more direct approach would be clearer
- 🔵 [INFO]
coordinator/mediafetch/config.go:1-224— Extensive configuration system with 12+ environment variables for media fetching- Suggestion: Consider reducing configuration surface area to essential knobs only
17 finding(s) total, 15 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| req.Header.Set("Accept", "image/*,video/*") | ||
| req.Header.Set("Accept-Encoding", "identity") // belt-and-suspenders with DisableCompression |
There was a problem hiding this comment.
🔵 [INFO] 🔒 User-Agent header hardcoded with project name
💡 Suggestion: Consider using a generic user agent or making it configurable to avoid fingerprinting
📊 Score: 3×2 = 6 · Category: missing-input-validation
| // 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) |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ max() function call on every request creates unnecessary allocation overhead
💡 Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| } | ||
|
|
||
| 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 |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ budgetReader.Read() can block indefinitely waiting for budget reservation
💡 Suggestion: Add context cancellation support to budget.reserve() to prevent indefinite blocking when clients disconnect
📊 Score: 4×3 = 12 · Category: blocking_io
| // (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() | ||
| // 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 | ||
| } |
There was a problem hiding this comment.
🔴 [CRITICAL] ⚡ fetchAll spawns goroutines without proper context cancellation coordination
💡 Suggestion: Use errgroup.WithContext instead of manual sync.WaitGroup to ensure proper cancellation propagation and resource cleanup
📊 Score: 4×4 = 16 · Category: unbounded_goroutines
| 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 |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ fetchOne performs redundant URL parsing and validation on every call
💡 Suggestion: Move URL parsing and validation to the caller level to avoid re-parsing the same URLs multiple times during retries or duplicate fetches
📊 Score: 3×3 = 9 · Category: repeated_work
| // 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. |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Missing type assertion check for media field map access
💡 Suggestion: Add type assertion check: if v, ok := pm[key].(map[string]any); !ok { return mediaRef{}, false }
📊 Score: 4×3 = 12 · Category: missing_type_assertion
| // 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 { |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Missing type assertion check for url string access
💡 Suggestion: Add type assertion check: if u, ok := v["url"].(string); !ok { return mediaRef{}, false }
📊 Score: 4×3 = 12 · Category: missing_type_assertion
| 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 | ||
| } | ||
| if s.mediaResolver == nil || !s.mediaResolver.Enabled() { | ||
| // Resolver off means authoritative rollback to the data:-only contract; | ||
| // the older DARKBLOOM_VISION_REJECT_REMOTE_URLS switch must not override it. | ||
| return s.rejectRemoteMediaURLsAlways(w, r, parsed, model, publicModel, requiresVision, hasTools) | ||
| } | ||
| // Sender-sealed requests are never fetched: the sender opted into sealing | ||
| // the payload to the coordinator, and a fetch would leak request-correlated | ||
| // egress to the URL's origin. Reject with a clear next step. | ||
| if mediafetch.HasRemoteMedia(parsed) && isSealedRequest(r) { | ||
| s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, | ||
| "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") | ||
| return true | ||
| } | ||
| // 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). | ||
| if badRef, ok := firstUnfetchableRemoteRef(parsed); !ok { | ||
| s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, | ||
| "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(badRef)) | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // firstUnfetchableRemoteRef returns ok=false with the first remote/non-inline | ||
| // media reference that the mediafetch resolver will NOT fetch based on that | ||
| // part's own shape and location (not URL equality with another part). OpenAI | ||
| // image_url/video_url http(s) parts are fetchable only under messages[]; | ||
| // Anthropic/input_* shapes, non-http(s) schemes, and every Responses input[] | ||
| // media ref remain unsupported. Mirrors validateMediaParts' fail-open stance on | ||
| // unreadable shapes. | ||
| func firstUnfetchableRemoteRef(parsed map[string]any) (badRef string, ok bool) { | ||
| check := func(content any, allowFetchableShape bool) (string, bool) { | ||
| parts, isArr := content.([]any) | ||
| if !isArr { | ||
| return "", true | ||
| } | ||
| for _, p := range parts { | ||
| pm, isMap := p.(map[string]any) | ||
| if !isMap { | ||
| continue | ||
| } | ||
| ref, isMedia := mediaPartURLString(pm) | ||
| if !isMedia || ref == "" { | ||
| continue | ||
| } | ||
| if !isInlineDataURI(ref) { | ||
| if allowFetchableShape && mediafetch.IsFetchableRemotePart(pm) { | ||
| continue | ||
| } | ||
| return ref, false | ||
| } | ||
| } | ||
| return "", true | ||
| } | ||
| if msgs, isArr := parsed["messages"].([]any); isArr { | ||
| for _, m := range msgs { | ||
| if mm, isMap := m.(map[string]any); isMap { | ||
| if ref, good := check(mm["content"], true); !good { | ||
| return ref, false | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if input, isArr := parsed["input"].([]any); isArr { | ||
| for _, it := range input { | ||
| if im, isMap := it.(map[string]any); isMap { | ||
| if ref, good := check(im["content"], false); !good { | ||
| return ref, false | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return "", true | ||
| } | ||
|
|
||
| // 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. | ||
| selfRoute bool | ||
| ownerAccountID string | ||
| } | ||
|
|
||
| // 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 — 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. | ||
| func (s *Server) resolveRemoteMedia(w http.ResponseWriter, r *http.Request, rawBody []byte, parsed map[string]any, timing *registry.RequestTiming, meta mediaResolveMeta) ([]byte, bool) { | ||
| if s.mediaResolver == nil || !s.mediaResolver.Enabled() { | ||
| return rawBody, 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, | ||
| registry.RequestTraits{HasTools: meta.hasTools}, meta.requiresVision) { | ||
| return nil, 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 | ||
| } | ||
| 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 | ||
| } | ||
| if !res.Changed { | ||
| return rawBody, 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 | ||
| } | ||
| // 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 | ||
| } | ||
|
|
||
| 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 | ||
| } | ||
|
|
||
| // 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 := "bad_param" | ||
| if status == http.StatusRequestEntityTooLarge { | ||
| reason = "payload_too_large" | ||
| } | ||
| 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"))) | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 New 253-line file introduces complex media resolution system with single consumer
💡 Suggestion: Consider whether this complexity is justified for the single use case, or if a simpler inline approach would suffice
📊 Score: 3×4 = 12 · Category: over-abstraction
| 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" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "sync" | ||
| ) | ||
|
|
||
| // 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). | ||
| func NewResolver(cfg Config, logger *slog.Logger) *Resolver { | ||
| cfg = cfg.sanitized() | ||
| if logger == nil { | ||
| logger = slog.New(slog.DiscardHandler) | ||
| } | ||
| return &Resolver{ | ||
| cfg: cfg, | ||
| client: newHTTPClient(cfg), | ||
| logger: logger, | ||
| globalSem: make(chan struct{}, cfg.GlobalConcurrency), | ||
| } | ||
| } | ||
|
|
||
| // Enabled reports whether remote-media fetching is turned on. | ||
| 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.cfg.Enabled { | ||
| 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 | ||
| } | ||
|
|
||
| // All fetches succeeded — apply mutations atomically. | ||
| for i, fetch := range fetches { | ||
| dataURI := toDataURI(fetched[i]) | ||
| for _, target := range fetch.targets { | ||
| target.set[target.key] = dataURI | ||
| } | ||
| } | ||
| return Result{Changed: true, Count: len(fetches), Bytes: totalBytes}, nil | ||
| } | ||
|
|
||
| func groupMediaRefs(refs []mediaRef) ([]mediaFetch, error) { | ||
| fetches := make([]mediaFetch, 0, len(refs)) | ||
| byURL := make(map[string]int, len(refs)) | ||
| for _, ref := range refs { | ||
| canonical, err := canonicalMediaURL(ref.url) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| ref.url = canonical | ||
| if i, exists := byURL[ref.url]; 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 | ||
| } | ||
| byURL[ref.url] = len(fetches) | ||
| fetches = append(fetches, mediaFetch{request: ref, targets: []mediaRef{ref}}) | ||
| } | ||
| return fetches, nil | ||
| } | ||
|
|
||
| // canonicalMediaURL normalizes components that do not change the on-the-wire | ||
| // request target, so each target is fetched and kind-checked once: fragments are | ||
| // never sent by HTTP, scheme/host are case-insensitive, and explicit default | ||
| // ports are equivalent to omission. Path escaping and query order are preserved | ||
| // because origins can assign them application-specific semantics. | ||
| func canonicalMediaURL(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) | ||
| hostname := u.Hostname() | ||
| if !strings.Contains(hostname, ":") { | ||
| hostname = strings.ToLower(hostname) | ||
| } | ||
| port := u.Port() | ||
| if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") { | ||
| port = "" | ||
| } | ||
| switch { | ||
| case hostname == "": | ||
| u.Host = "" | ||
| case port != "": | ||
| u.Host = net.JoinHostPort(hostname, port) | ||
| case strings.Contains(hostname, ":"): | ||
| u.Host = "[" + hostname + "]" | ||
| default: | ||
| u.Host = hostname | ||
| } | ||
| 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() | ||
| // 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 | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Large resolver package with extensive abstraction for media fetching
💡 Suggestion: Evaluate if the full resolver abstraction is needed or if a more direct approach would be clearer
📊 Score: 3×3 = 9 · Category: over-abstraction
| // 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 ( | ||
| "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" | ||
| envMaxParts = env.EnvPrefix + "_MEDIA_FETCH_MAX_PARTS" | ||
| envTimeoutMS = env.EnvPrefix + "_MEDIA_FETCH_TIMEOUT_MS" | ||
| envTotalDeadline = env.EnvPrefix + "_MEDIA_FETCH_TOTAL_DEADLINE_MS" | ||
| envConcurrency = env.EnvPrefix + "_MEDIA_FETCH_CONCURRENCY" | ||
| 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 — the body the coordinator | ||
| // re-marshals and seals), which is the binding constraint, not just the | ||
| // provider's 32 MiB WebSocket frame. Raw media of M bytes inflates to ~1.37*M as | ||
| // a base64 data: URI, so the aggregate raw cap must leave headroom under 16 MiB | ||
| // for the inlined media PLUS the rest of the request (prompt text, JSON | ||
| // structure, the coordinator-injected max_tokens). A 10 MiB aggregate raw cap | ||
| // inlines to ~13.3 MiB, leaving ~2.7 MiB for everything else — so a valid | ||
| // request is never fetched only to be rejected by the final 16 MiB body check. | ||
| // | ||
| // DefaultMaxImageMegapixels mirrors the provider's DARKBLOOM_MAX_IMAGE_MEGAPIXELS | ||
| // default (100 MP, header-read before rasterization) so the coordinator rejects | ||
| // pixel bombs before dispatch instead of shipping them 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) | ||
| 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 | ||
| // MaxParts caps the number of remote media URLs fetched per request. | ||
| 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. | ||
| 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 | ||
| } | ||
|
|
||
| // DefaultConfig returns the production defaults (feature enabled). | ||
| func DefaultConfig() Config { | ||
| return Config{ | ||
| Enabled: true, | ||
| MaxFileBytes: DefaultMaxFileBytes, | ||
| MaxTotalBytes: DefaultMaxTotalBytes, | ||
| 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 or unparseable. | ||
| func ConfigFromEnv() Config { | ||
| c := DefaultConfig() | ||
| c.Enabled = env.EnvBool(envEnabled, c.Enabled) | ||
| c.MaxFileBytes = int64(env.EnvInt(envMaxFileBytes, int(c.MaxFileBytes))) | ||
| c.MaxTotalBytes = int64(env.EnvInt(envMaxTotalBytes, int(c.MaxTotalBytes))) | ||
| c.MaxParts = env.EnvInt(envMaxParts, c.MaxParts) | ||
| c.FetchTimeout = time.Duration(env.EnvInt(envTimeoutMS, int(c.FetchTimeout/time.Millisecond))) * time.Millisecond | ||
| c.TotalDeadline = time.Duration(env.EnvInt(envTotalDeadline, int(c.TotalDeadline/time.Millisecond))) * time.Millisecond | ||
| c.Concurrency = env.EnvInt(envConcurrency, c.Concurrency) | ||
| c.GlobalConcurrency = env.EnvInt(envGlobalConc, c.GlobalConcurrency) | ||
| c.MaxImageMegapixels = env.EnvInt(envMaxMegapixels, c.MaxImageMegapixels) | ||
| c.BlocklistDomains = parseBlocklist(env.EnvOr(envBlocklist, "")) | ||
| c.AllowPrivateIPs = env.EnvBool(envAllowPrivateIP, c.AllowPrivateIPs) | ||
| c.AllowNonStandardPorts = env.EnvBool(envAllowOtherPorts, c.AllowNonStandardPorts) | ||
| return c.sanitized() | ||
| } | ||
|
|
||
| // 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.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 lowercased set. | ||
| func parseBlocklist(csv string) map[string]bool { | ||
| out := map[string]bool{} | ||
| for _, raw := range strings.Split(csv, ",") { | ||
| // Strip a trailing FQDN dot so "evil.com." and "evil.com" canonicalize the | ||
| // same way hostAllowed canonicalizes request hosts (no trailing-dot bypass). | ||
| h := strings.TrimRight(strings.ToLower(strings.TrimSpace(raw)), ".") | ||
| if h != "" { | ||
| out[h] = true | ||
| } | ||
| } | ||
| return out | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Extensive configuration system with 12+ environment variables for media fetching
💡 Suggestion: Consider reducing configuration surface area to essential knobs only
📊 Score: 2×3 = 6 · Category: over-configuration
Support OpenAI-style http(s) image_url/video_url links on
/v1/chat/completions. The coordinator (the trusted SSRF chokepoint)
fetches each URL once per request — after token admission, the balance
reservation, and the catalog check, refunding on failure — validates it
structurally, and rewrites it in place as a base64 data: URI before the
body is sealed to a provider. The provider keeps seeing only data: URIs;
its hardened non-data: guard is unchanged (defense in depth). Default ON
(EIGENINFERENCE_MEDIA_FETCH_ENABLED=false restores the pre-dispatch 400).
New coordinator/mediafetch package:
- SSRF: scheme/userinfo/blocklist guards + connect-time IP deny policy in
net.Dialer.Control (loopback, RFC1918, link-local/metadata, CGNAT,
NAT64, IPv4-mapped, reserved) on every dial incl. redirect hops —
DNS-rebinding-proof; redirects capped at 3 and re-validated per hop.
- Content: data: URI built from magic-byte sniffing, never the header;
explicit allowlist of provider-decodable formats (JPEG/PNG/GIF/WebP/BMP,
MP4/QuickTime — custom qt-brand sniff); declared part kind must match
sniffed kind; header-only megapixel cap (100 MP) for stdlib-decodable
images mirrors the provider's pre-raster pixel gate.
- Bombs/resource use: per-file (8 MiB) + per-request (10 MiB) raw caps via
io.LimitReader, no transparent decompression, part cap (8), per-request
worker cap (4), process-wide fetch semaphore (32), per-fetch (15s) +
whole-step (25s) deadlines; env-tunable (EIGENINFERENCE_MEDIA_FETCH_*).
API wiring (media_resolve.go):
- Phase 1 pre-billing gate: sealed requests carrying remote media are
rejected (never unseal-to-fetch — fetching would leak request-correlated
egress to the origin); remote refs in shapes the resolver does not fetch
(Anthropic source blocks, file://) keep today's clean 400; resolver
disabled falls back to the legacy rejection and its kill switch.
- Phase 2 post-reservation resolve on the chat surface; generic
(completions + Anthropic) keeps the unconditional rejection.
- Observability: X-Timing media_fetch_us segment (RequestTiming.
MediaFetchedAt anchors route_us/RouteMs past the download),
inference.media_fetch.{ok,rejected,items,bytes,duration_ms} DD metrics.
Threat model: new T-043 (TB-001) documents the surface + mitigations.
Tests: SSRF matrix (metadata/NAT64/mapped-IPv6/rebinding), redirect
laundering, size-cap honesty (lying Content-Length, chunked), pixel bomb,
kind mismatch, WebM/SVG/HTML rejection, sealed no-fetch, cost-gate
ordering (prelude never fetches), full HTTP-path SSRF block / success /
disabled fallback. Full coordinator suite green with -race.
…t floor Codex/review round on PR #530: - URL dedupe: canonicalize (drop fragment, lowercase scheme/host, strip default ports) so an equivalent URL fetches once and rewrites every location; reject cross-kind reuse of one URL before any network I/O. Keep a pre-dedup total-target cap so duplicate targets can't expand into an oversized base64 body (MaxParts on refs, byte accounting on unique fetches). - Secret redaction: mediafetch.Error.Internal never carries the URL/host/ query/cause, and the API layer logs only code+status — presigned S3/R2 URLs can't leak into coordinator logs. - Shape-based gate: firstUnfetchableRemoteRef judges each part by its own shape/location via mediafetch.IsFetchableRemotePart, so an unsupported Anthropic source block sharing a URL with an OpenAI part still 400s. - Blocklist: parent-domain entries match at DNS-label boundaries (evil.com blocks img.evil.com, not notevil.com). - Cost floor: reserve against max(byte-bound, media-aware estimate) before fetch so a URL-only-funded caller can't drive coordinator egress. - Rollback: EIGENINFERENCE_MEDIA_FETCH_ENABLED=false is authoritative and ignores the legacy DARKBLOOM_VISION_REJECT_REMOTE_URLS flag. - Cancellation: client cancel propagates as context.Canceled (no fake media_fetch_timeout telemetry / no response write). Tests + threat model T-043 updated; coordinator suite green with -race.
Second review round on PR #530 (new findings on the rebased head): - Redirect Referer leak: Go's http client auto-sets Referer to the previous hop on redirect. A presigned S3/R2/GCS media URL carries its signature in the query string, so a cross-host redirect would leak the signed URL to the redirect target. redirectGuard now strips Referer on every hop. - Self-route egress gate: exclusive self-route (X-Darkbloom-Route: self) skips the balance reservation, so no cost gate preceded the fetch. An authenticated caller with no linked/online/capable machine could drive up to the media-fetch caps of coordinator egress and only then get the self-route error. resolveRemoteMedia now runs selfRouteUnavailable before any fetch when the request is self-route and carries remote media. Tests for both; threat-model T-043 updated; coordinator suite green -race.
Review of the remote-media feature surfaced one blocker and a set of security/ops gaps. Fixes, in severity order: P0 — the feature never worked end to end. `providerBody` was captured ~130 lines before `resolveRemoteMedia` reassigned `rawBody`, and was only refreshed inside `onModelFallback`. On the default success path the coordinator fetched the image, inlined the data: URI into `parsed`, discarded the result, then sealed and dispatched the ORIGINAL body still carrying the http(s) URL — which the provider's data:-only guard rejects. Extracted `refreshForwardBody` (shared with the alias-fallback path) and call it after a successful inline, so the forwarded body, the Responses re-lowering and the routing traits all describe the body that is actually sealed. `resolveRemoteMedia` now reports `inlined` so the refresh cannot be silently skipped again. P1 — a panic in the fetch worker killed the process. `fetchAll` spawned a bare goroutine that runs the outbound HTTP client and the image-header parsers over attacker-chosen bytes; net/http only recovers panics on the handler goroutine. Wrapped in `saferun.Recover` plus a result-not-stored guard that converts an aborted worker into a typed 502 instead of leaving a nil slot for `Resolve` to dereference. P1 — IPv6 zone IDs bypassed the whole SSRF deny list. `netip.Prefix.Contains` returns false for any zoned address, and a zone survives url.Parse -> Hostname -> canonicalAddr -> the Control hook, so `[64:ff9b::a9fe:a9fe%25x]` reached cloud metadata over NAT64. Strip the zone in `ipAllowed` before any policy evaluation. P1 — duplicate targets amplified past every byte cap. Eight parts naming one 8 MiB URL cost one fetch inside the aggregate budget but marshaled to ~85 MiB. `Resolve` now checks the projected inlined total against `MaxInlinedBytes` (16 MiB) before mutating the request. P2 — the reservation stopped being an upper bound. For a remote URL the byte bound is ~100 tokens, so the flat 300/1500 routing floor became the reservation while real vision prompts run far higher; settlement's 2x-reservation clamp then absorbed the shortfall and underpaid the provider. `topUpReservationForInlinedMedia` re-reserves against the post-inline byte bound, refunding and 402-ing when the caller cannot cover it. P2 — blocklist could be evaded and misconfigured. Hosts and entries now share one `canonicalHost` (lowercase, UTS-46 IDNA, dots trimmed), so a `U+3002` homoglyph cannot show one host to the policy and another to the socket, and the conventional `.evil.com` wildcard spelling no longer stores a dead key. Added 0.0.0.0/8. P2 — `MaxConnsPerHost` used the per-request worker knob as a process-wide per-host cap, serializing all traffic to one CDN into waves of 4 and turning the queue wait into spurious 408s. Now `GlobalConcurrency`. P2 — config had no boot validation and no operator surface. `Config.Check` is wired through `AppConfig.Check`, `ConfigFromEnv` returns raw operator intent so a typo fails startup, `NewResolver` clamps + WARNs for programmatic configs and WARNs when either SSRF override is on, and all 13 env vars are documented in the deploy runbook with `ENABLED` in the prod defaults. P3 — kill switch needed a redeploy (now read live), non-chat surfaces still honored the legacy `DARKBLOOM_VISION_REJECT_REMOTE_URLS` flag (now unconditional, flag deleted), upstream failures were filed as consumer `bad_param` (now mapped by status), `truncateMediaRef` could emit invalid UTF-8, and the X-Timing doc was missing `media_fetch`. Tests: the two contracts that were entirely unpinned now have regression coverage — the body a provider actually receives, and the reservation held across the fetch. Six mitigations that a reviewer proved deletable with a green suite (shared read-time byte budget, Is4In6 unmap, DisableCompression, the env kill switch, blocklist canonicalization, the global fetch semaphore) plus the total deadline are now mutation-verified. Datadog dashboard gains media-fetch refusal and latency panels. T-049 updated; its "the part cap prevents duplicate base64 expansion abuse" claim was false and is replaced by the projection check.
3f92101 to
c503404
Compare
| if mediafetch.HasRemoteMedia(parsed) && isSealedRequest(r) { | ||
| s.writeRemoteMediaRejection(w, r, parsed, model, publicModel, hasTools, | ||
| "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") | ||
| return true | ||
| } |
There was a problem hiding this comment.
Right, and the root cause was structural — fixed in 5aa0cea. The gate was asking two different questions ("any remote reference?" for sealed, "any unfetchable reference?" for everyone else) through three separate walks: HasRemoteMedia, firstUnfetchableRemoteRef and validateMediaParts. Those three are now one pass, scanRemoteMediaRefs, returning both facts, and the sealed branch keys off firstRemote — ANY non-inline shape. TestGateSealedRejectsEveryRemoteShape covers OpenAI, Anthropic source.url and Responses input_image; narrowing the branch back to the fetchable subset fails it.
| hostname := u.Hostname() | ||
| if !strings.Contains(hostname, ":") { | ||
| hostname = strings.ToLower(hostname) | ||
| } |
There was a problem hiding this comment.
Correct — fixed in 5aa0cea, and it fell out of the neighbouring fix. Canonicalization is now a dedup KEY only (mediaFetchKey), never a rewrite, so the key lowercases u.Host wholesale: host, port digits and bracketed IPv6 hex. TestGroupMediaRefsDedupKey asserts [2001:DB8::1] and [2001:db8::1] share one fetch; restoring the IPv6 carve-out fails it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3bfd39bc89
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") { | ||
| port = "" | ||
| } |
There was a problem hiding this comment.
Preserve explicit default ports when fetching media
When a media URL explicitly includes :80 or :443, this normalization removes the port from the URL that is actually fetched, rather than using normalization only as the deduplication key. This breaks origins or presigned URLs whose signature includes the exact Host header (for example, a URL signed for cdn.example.com:443 is requested as cdn.example.com and receives an upstream authentication error). Keep the first original URL as mediaFetch.request.url while using the normalized form only for grouping.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and the sharpest of the four — fixed in 5aa0cea. groupMediaRefs was assigning the canonical form back onto the ref, so the normalized URL became the one actually requested. Canonicalization is now strictly a deduplication key (mediaFetchKey); mediaFetch.request keeps the consumer's original string byte for byte. The key still folds the fragment and scheme/host case (never on the wire) and nothing else — an explicit :80/:443 survives, exactly because a presigned signature can cover the host:port. Cost is that https://h/a and https://h:443/a in one request are fetched twice; both still count against the per-file, aggregate and projected-inline caps, so no cap is bypassed. TestGroupMediaRefsDedupKey asserts the fetched URL is the original and that the explicit-port form is not folded away. Dropping the rewrite also deleted a four-branch host reassembly and the net import.
| if c.GlobalConcurrency <= 0 { | ||
| return fmt.Errorf("mediafetch: GlobalConcurrency must be > 0 (%s), got %d", envGlobalConc, c.GlobalConcurrency) | ||
| } | ||
| return nil |
There was a problem hiding this comment.
Reject negative image megapixel limits at startup
When EIGENINFERENCE_MEDIA_FETCH_MAX_IMAGE_MEGAPIXELS is set to a negative integer, ConfigFromEnv parses it successfully and Check returns nil here, so AppConfig.Check allows startup; sanitized then silently replaces the operator's value with the default. This bypasses the stated fail-startup behavior for invalid numeric safety limits and provides no warning that the configured value was ignored. Add a MaxImageMegapixels < 0 validation while continuing to allow the documented value 0.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct — fixed in 5aa0cea. MaxImageMegapixels >= 0 is now a Check() rule, so -5 aborts the boot instead of being silently swapped for the 100 MP default. 0 stays legal: it is the documented "coordinator-side pixel check off, provider cap still authoritative" value, so the rule is < 0, not <= 0. TestConfigCheck gained rows for -1 (must error and name the env var) and 0 (must pass). While in here the nine near-identical bounds branches collapsed into one table, and three knobs with no operational story became compile-time constants — MAX_INLINED_BYTES, MAX_PARTS, CONCURRENCY — taking the operator surface from 13 vars to 10.
… + config Four more bot findings, plus the simplification pass the reviewers have asked for twice. Codex — canonicalization rewrote the URL that gets fetched. `groupMediaRefs` assigned the canonical form back onto the ref, so an explicitly written `:443` was stripped before the request went out. A presigned S3/R2/GCS signature can cover the exact `host:port`, so that turned a valid link into an upstream auth error. Canonicalization is now a dedup KEY only (`mediaFetchKey`): the URL requested is the string the consumer sent, byte for byte. Two locations differing only by an explicit default port are fetched twice; both still count against every byte cap, so nothing is bypassed. Dropping the host rewrite also deleted a four-branch reassembly and the `net` import. Copilot — IPv6 hosts were not lowercased, so `[2001:DB8::1]` and `[2001:db8::1]` missed each other in dedup. Falls out of the above: the key now lowercases `u.Host` wholesale, which covers host, port digits and bracketed IPv6 hex. Copilot — a sealed request carrying an unfetchable shape got the wrong advice. The sealed branch keyed off `HasRemoteMedia`, which only sees fetchable OpenAI parts under `messages[]`, so a sealed Anthropic `source.url` fell through to the unfetchable-shape message telling the caller to "send an OpenAI http(s) link" — something a sealed request will never fetch either. The gate now keys off ANY non-inline reference. Codex — `MAX_IMAGE_MEGAPIXELS=-5` parsed fine, passed `Check`, and was silently replaced by the default. Now `>= 0` is validated (`0` stays legal: it means the coordinator-side pixel check is off and the provider's cap still applies). Simplification, all behavior-preserving: - Three walks over the same request JSON collapse into one (`scanRemoteMediaRefs`). The gate asked two questions — any remote ref, and any unfetchable ref — via `HasRemoteMedia`, `firstUnfetchableRemoteRef` and `validateMediaParts`. Deriving them from separate walks IS the sealed-shape bug above, so this fix and this simplification are the same change. - `Check()` collapses nine near-identical bounds branches into one table. - Three env knobs with no operational story become compile-time constants: `MAX_INLINED_BYTES` (derived from `api.maxInferenceBodyBytes`), `MAX_PARTS` (matched to the provider's videos-per-request cap) and `CONCURRENCY` (the real capacity lever is the process-wide `GLOBAL_CONCURRENCY`). The struct fields, defaults, clamps and validation stay, so tests and `ServerConfig.MediaFetch` are unaffected. Operator surface: 13 vars -> 10. All four fixes are mutation-verified: reverting the key-only canonicalization, the IPv6 lowercase, the sealed-branch predicate or the megapixel rule each fails its named test.
| | `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). The switch is read live on every request, so editing the env file and reloading the unit is enough — no redeploy, no image rebuild. | |
There was a problem hiding this comment.
You are right and this was my error — fixed in f2ebfd5. I introduced the per-request env.EnvBool two commits ago and then documented the redeploy-free rollback in the runbook, prod.env and T-049. os.Getenv returns the environment captured at exec, the prod container is created with docker run --env-file, and this very runbook already says elsewhere that new values apply only at container start — so the read bought nothing and attached a false promise to an incident lever. Enabled() is back to the construction-time value, the runbook row now says the container must be recreated, and T-049 records that the earlier claim was wrong. TestResolverEnabledIsConstructionTime fails if a per-call env read comes back.
Out of scope but worth flagging: registry/scheduler.go:1989 and api/dispatch.go:240,260 carry the same "read live (no restart)" claim about their own flags, and it is wrong there for the same reason. Noted in the commit message for a follow-up.
| // Enabled reports whether remote-media fetching is turned on. The env var is | ||
| // read LIVE on every call so an operator can kill the feature fleet-wide without | ||
| // a redeploy; the Config value is the fallback, which keeps programmatically | ||
| // built Resolvers (tests, embedders) working when the var is unset. | ||
| func (r *Resolver) Enabled() bool { return env.EnvBool(envEnabled, r.cfg.Enabled) } |
There was a problem hiding this comment.
You are right and this was my error — fixed in f2ebfd5. I introduced the per-request env.EnvBool two commits ago and then documented the redeploy-free rollback in the runbook, prod.env and T-049. os.Getenv returns the environment captured at exec, the prod container is created with docker run --env-file, and this very runbook already says elsewhere that new values apply only at container start — so the read bought nothing and attached a false promise to an incident lever. Enabled() is back to the construction-time value, the runbook row now says the container must be recreated, and T-049 records that the earlier claim was wrong. TestResolverEnabledIsConstructionTime fails if a per-call env read comes back.
Out of scope but worth flagging: registry/scheduler.go:1989 and api/dispatch.go:240,260 carry the same "read live (no restart)" claim about their own flags, and it is wrong there for the same reason. Noted in the commit message for a follow-up.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5aa0cea494
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if s.selfRouteUnavailable(w, r, meta.ownerAccountID, meta.model, | ||
| meta.traits, meta.requiresVision) { |
There was a problem hiding this comment.
Recompute self-route traits before allowing fetch
When a self-routed URL expands the provider body close enough to the 16 MiB limit that routingTraitsForProviderBody raises MinPrefixCacheProtocol to 1, this gate still checks the traits derived from the short pre-inline URL. An owned protocol-0 vision provider therefore passes this check, the coordinator fetches the media, and the later post-inline runInferenceAdmission rejects the request because only that provider was available. Fresh evidence beyond the earlier full-traits report is that media inlining itself changes this size-derived trait; conservatively account for that possible protocol floor before allowing free self-route egress.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and recorded as an accepted residual in T-049 rather than coded around. You are right that inlining is what raises the size-derived trait, so the pre-fetch gate structurally cannot know it: MinPrefixCacheProtocol comes from the body size, and the body does not exist until after the fetch.
Assuming the higher floor pre-emptively is the cure being worse than the disease — most inlined media lands far below the 16 MiB threshold, so a conservative floor would falsely reject self-route requests that would have succeeded, on the caller's own hardware. The actual exposure is one fetch, bounded by the per-request byte caps, on a machine the caller owns, and runInferenceAdmission still rejects correctly afterwards. Documented so the tradeoff is explicit rather than an oversight.
| fetchCtx, cancel := context.WithTimeout(ctx, r.cfg.FetchTimeout) | ||
| defer cancel() | ||
|
|
||
| req, err := http.NewRequestWithContext(fetchCtx, http.MethodGet, u.String(), nil) |
There was a problem hiding this comment.
Normalize URL schemes before creating HTTP requests
For a valid URL with a mixed-case scheme such as HTTPS://cdn.example.com/image.png, isRemoteMediaURL and validateURL accept the scheme case-insensitively, but this constructs the request from the unchanged value. Go's HTTP transport dispatches only the exact lowercase schemes http and https, so the request fails as an unsupported protocol and is returned as a 502. Lowercase u.Scheme before constructing the request without otherwise rewriting the caller's URL.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible — net/url.Parse already lowercases the scheme, so this cannot occur. Verified: url.Parse("HTTPS://cdn.example.com/a.png") yields Scheme == "https" and String() == "https://cdn.example.com/a.png", and fetchOne builds the request from u.String(), not from the raw ref. http.NewRequestWithContext re-parses anyway, so even a raw mixed-case string would normalize.
I had already written the strings.ToLower(u.Scheme) line plus a test before checking this; both are removed in f2ebfd5 rather than left as dead code and a test that cannot fail. Good instinct on the class of bug — it just doesn't apply to Go's URL handling.
| | `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). The switch is read live on every request, so editing the env file and reloading the unit is enough — no redeploy, no image rebuild. | |
There was a problem hiding this comment.
Require container recreation in kill-switch instructions
In the production flow documented in this runbook, the coordinator is created with docker run --env-file /etc/d-inference/env (lines 415–421), and the same document correctly states elsewhere that new environment values take effect only on container start (lines 394–395). Editing that file or merely reloading systemd cannot alter os.Getenv in the already-running coordinator, so following this incident procedure can leave remote fetching enabled; document the required container recreation/restart or add a real live configuration mechanism.
AGENTS.md reference: docs/AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right and this was my error — fixed in f2ebfd5. I introduced the per-request env.EnvBool two commits ago and then documented the redeploy-free rollback in the runbook, prod.env and T-049. os.Getenv returns the environment captured at exec, the prod container is created with docker run --env-file, and this very runbook already says elsewhere that new values apply only at container start — so the read bought nothing and attached a false promise to an incident lever. Enabled() is back to the construction-time value, the runbook row now says the container must be recreated, and T-049 records that the earlier claim was wrong. TestResolverEnabledIsConstructionTime fails if a per-call env read comes back.
Out of scope but worth flagging: registry/scheduler.go:1989 and api/dispatch.go:240,260 carry the same "read live (no restart)" claim about their own flags, and it is wrong there for the same reason. Noted in the commit message for a follow-up.
| // exactly what globalSem already admits. | ||
| MaxConnsPerHost: cfg.GlobalConcurrency, | ||
| TLSHandshakeTimeout: cfg.FetchTimeout, | ||
| ResponseHeaderTimeout: cfg.FetchTimeout, |
There was a problem hiding this comment.
Cap response headers in the media transport
When an attacker points media URLs at an origin they control, that origin can return oversized HTTP headers before any of the body byte budgets run. Because MaxResponseHeaderBytes is unset, Go 1.25 permits up to 10 MiB of response headers per connection; with the configured 32 global fetch slots, concurrent requests can force roughly 320 MiB of header buffering even though each body is tightly capped, and fetch failures refund the monetary reservation. Set a small explicit header limit on this dedicated transport.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct — fixed in f2ebfd5. MaxResponseHeaderBytes is now 64 KiB on this dedicated transport. Your arithmetic is the point: headers are read before any body budget applies, so the tight body caps were irrelevant to that path. TestMediaTransportCapsResponseHeaders fails if the field goes back to unset.
| if len(via) >= maxRedirects { | ||
| return fmt.Errorf("%w: too many redirects (>%d)", errBlockedHost, maxRedirects) | ||
| } | ||
| return validateURL(req.URL, cfg) |
There was a problem hiding this comment.
Reject HTTPS-to-HTTP media redirects
When a caller supplies an HTTPS media URL whose origin redirects to HTTP, this guard accepts the hop because it validates each scheme independently against the global HTTP/HTTPS allowlist. The fetch then silently loses transport confidentiality and integrity: redirect query credentials can cross the network in plaintext, and an on-path party can replace the image or video before it is inlined into the encrypted provider request. Continue allowing explicitly supplied HTTP URLs if desired, but reject a downgrade when the previous hop in via used HTTPS.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct — fixed in f2ebfd5. Validating each hop independently against the scheme allowlist accepted the downgrade because both schemes are individually legal. redirectGuard now refuses a hop to http when any earlier hop in via used https, so an https caller keeps confidentiality and integrity across the whole chain; a deliberately supplied plain-http URL still works, exactly as you suggested. TestResolveRejectsHTTPSToHTTPDowngrade uses a TLS origin redirecting to a plaintext one and asserts the downgraded hop is never dialed.
…t downgrades Third bot review round. One of these is my own error from two commits ago. **The kill switch was not "read live".** I changed `Resolver.Enabled()` to call `env.EnvBool` on every request and documented — in the runbook, in `prod.env` and in T-049 — that flipping `EIGENINFERENCE_MEDIA_FETCH_ENABLED` takes effect without a redeploy. That is false. `os.Getenv` returns the environment captured at exec, so editing `/etc/d-inference/env` or reloading the unit cannot change a running coordinator; the prod container is created with `docker run --env-file` and the runbook already says elsewhere that new values apply only at container start. The per-request read bought nothing and attached a false promise to an incident lever. `Enabled()` is back to the construction-time value, and every doc now says the container must be recreated. Caught by Copilot and Codex independently — thank you. **https -> http redirect downgrade was accepted.** `redirectGuard` validated each hop against the scheme allowlist in isolation, and both schemes are individually legal, so an https origin could bounce the fetch to plaintext http. That puts a redirect's signed query on the wire and lets an on-path party substitute the image before it is inlined into the (encrypted) provider request. A downgrade is now refused when any earlier hop used https; a deliberately supplied http URL still works. **Response headers were uncapped.** Headers are read before any body budget applies and Go's default is 10 MiB per connection, so an attacker-owned origin could force `GlobalConcurrency` x 10 MiB of buffering while every body stayed tightly capped. Set to 64 KiB. **`MAX_IMAGE_MEGAPIXELS=-5`** parsed, passed `Check`, and was silently replaced by the default — now validated as `>= 0` (`0` stays legal: it means the coordinator-side pixel check is off and the provider's cap is authoritative). Rejected one finding with evidence: Codex reported that a mixed-case scheme (`HTTPS://…`) would fail as an unsupported protocol and surface as a 502. `net/url.Parse` already lowercases the scheme, so the request is built from an already-normalized `u.String()` and the bug cannot occur. I had written the "fix" plus a test before checking; both are removed rather than left as dead code and an unfailable test. Also documented as an accepted residual: the pre-fetch self-route serve-ability check uses pre-inline traits, so a size-derived floor that only inlining raises (`MinPrefixCacheProtocol`) cannot be known before the fetch. Assuming the higher floor pre-emptively would falsely reject self-route requests that would have succeeded; the exposure is one byte-capped fetch on the caller's own hardware. Three of the four fixes are mutation-verified: removing the header cap, the downgrade guard, or the construction-time semantics each fails its named test. Note for a follow-up, out of scope here: `registry/scheduler.go:1989` and `api/dispatch.go:240,260` carry the same "read live (no restart)" claim about their own env flags, and it is wrong there for the same reason.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 32 out of 32 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (1)
docs/operations/coordinator-deploy.md:640
- PR description says
EIGENINFERENCE_MEDIA_FETCH_ENABLEDis “read live — no redeploy”, but the docs (and mediafetch implementation) state it’s read once at process start and requires recreating the container. The PR description should be updated to match the actual operational behavior.
| `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. |
| } 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"}) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f2ebfd587f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| v := strings.TrimSpace(os.Getenv(key)) | ||
| if v == "" { | ||
| return fallback |
There was a problem hiding this comment.
Reject explicitly empty kill-switch values
When an env file or deployment template explicitly sets EIGENINFERENCE_MEDIA_FETCH_ENABLED= (or whitespace), os.Getenv plus this empty-string branch treats it as unset, returns the compiled true fallback, and records no malformed value for Check, so an attempted rollback can leave remote fetching enabled without a startup error. Fresh evidence beyond the earlier malformed-value report is that the strict parser still cannot distinguish an absent variable from a present-but-empty one; use os.LookupEnv and accept the fallback only when the key is genuinely absent.
Useful? React with 👍 / 👎.
Pin mlx-swift-lm 20fa3d540d (candidate/0.10.18-c6-sdk, landing PR Layr-Labs/mlx-swift-lm#534): main 4bb2b43ee8 with a merge of #530 (f335812335, the concurrent checkpoint row decode) and a merge of #533 (175069698c, a prompt-length limit for MTP drafting). Against f335812335 it adds only #533's change; #533's provider side and docs are their own PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
http(s)image_urlandvideo_urlparts onPOST /v1/chat/completions.data:URI before coordinator-to-provider encryption.EIGENINFERENCE_MEDIA_FETCH_ENABLED=falserestores the prior pre-dispatch 400 and is read live — no redeploy.Before
flowchart LR subgraph BehaviorBefore[Behavior] A1[Chat request with remote image or video URL] --> B1[Coordinator validation] B1 --> C1[HTTP 400: inline data URI required] D1[Chat request with inline data URI] --> E1[Route to vision provider] end subgraph CodeBefore[Code flow] F1[handleChatCompletions] --> G1[detectMediaRequirement] G1 --> H1[rejectRemoteMediaURLs] H1 --> I1[writeRemoteMediaRejection] F1 --> J1[dispatch] J1 --> K1[Provider MediaIngest: data URI only] endAfter
flowchart TD subgraph BehaviorAfter[Behavior] A2[Chat request with remote image or video URL] --> B2{Pre-fetch gate} B2 -->|sealed, unsupported shape, or feature disabled| C2[HTTP 400; no outbound fetch] B2 -->|fetchable http or https URL| D2[Token admission, balance reserve, catalog check] D2 --> E2[Fetch once at coordinator] E2 -->|blocked, timeout, invalid, oversized| F2[Refund monetary reservation and return typed 4xx or 5xx] E2 -->|valid| G2[Projected inline size check, then rewrite as data URI] G2 --> H2[Re-reserve against the inlined body] H2 -->|caller cannot cover it| I2[Refund and 402] H2 -->|covered| J2[Refresh forwarded body, traits, cache plan] J2 --> K2[Route, encrypt, and dispatch] K2 --> L2[Provider receives data URI only] end subgraph CodeAfter[Code flow] M2[handleChatCompletions] --> N2[gateRemoteMediaPreDispatch] N2 --> O2[resolveRemoteMedia] O2 --> P2[mediafetch.Resolver.Resolve] P2 --> Q2[validateURL and dialControl] Q2 --> R2[HTTP fetch with per-file and shared byte budgets] R2 --> S2[magic-byte sniff, kind match, dimension checks] S2 --> T2[projectedInlinedBytes vs MaxInlinedBytes] T2 --> U2[rewrite parsed request] U2 --> V2[refreshForwardBody: providerBody, Responses lowering, routingTraits] V2 --> W2[topUpReservationForInlinedMedia] W2 --> X2[runInferenceAdmission, planCacheRoute, dispatch] endDelta from the first review round
The two structural bugs the review round fixed, isolated:
flowchart LR subgraph WasBroken[Was broken] A3["providerBody := rawBody<br/>(captured pre-fetch)"] --> B3[resolveRemoteMedia mutates parsed] B3 --> C3["rawBody' discarded"] A3 --> D3["dispatch seals providerBody<br/>= the original http URL"] D3 --> E3[Provider data:-only guard rejects] end subgraph NowFixed[Now fixed] A4[resolveRemoteMedia returns inlined=true] --> B4[refreshForwardBody] B4 --> C4[providerBody, Responses re-lowering, routingTraits, cachePlan] C4 --> D4[topUpReservationForInlinedMedia] D4 --> E4[dispatch seals the inlined body] endSecurity Boundaries
net.Dialer.Control, against the post-DNS-resolution address on every dial and redirect hop. The IPv6 scope zone is stripped first —netip.Prefix.Containsreturns false for any zoned address, so a%zonesuffix would otherwise skip the entire prefix deny list.0.0.0.0/8, IPv4-mapped and IPv4-compatible IPv6, NAT64, 6to4, Teredo, deprecated relay/site-local, multicast, unspecified, documentation, benchmarking, and reserved ranges.EIGENINFERENCE_MEDIA_FETCH_ALLOW_NONSTANDARD_PORTS=true.canonicalHost(lowercase, UTS-46 IDNA to ASCII, leading/trailing dots trimmed), matching the profilenet/httpdials with — aU+3002/U+FF0E/U+FF61homoglyph cannot show one host to the policy and another to the socket, and the conventional.evil.comwildcard spelling no longer stores a key that never matches.Referer, and caps chains at three hops.Content-Type. Accepted formats are JPEG, PNG, GIF, WebP, BMP, MP4, and QuickTime; HTML, SVG, executables, WebM, AVI, and mismatched part kinds fail closed.saferun.Recover: it parses attacker-controlled bytes on a goroutine spawned from the HTTP handler, wherenet/httpdoes not recover panics.len(bytes) >= tokensinvariant that settlement's 2x-reservation overage clamp depends on.AppConfig.Check->mediafetch.Config.Check, so an operator typo fails startup instead of silently reverting to a default;NewResolveradditionally clamps and WARNs, and WARNs whenever either SSRF override is enabled.T-049documents the surface, mitigations, residual public-origin timing signal, and regression triggers.Scope
POST /v1/chat/completions, andPOST /v1/responseswith a chat-shaped body) for OpenAIimage_urlandvideo_urlcontent parts./v1/responseswith aninput-shaped body is rejected before the media gate because the Responses-to-chat lowering does not preserve media yet./v1/completionsand Anthropic/v1/messagesreject remote media unconditionally — the legacyDARKBLOOM_VISION_REJECT_REMOTE_URLSflag is deleted, so no configuration can make those surfaces forward a URL to a provider.Observability
media_fetch_ustoX-Timingand anchorsroute_usafter media resolution.inference.media_fetch.ok,.rejected,.items,.bytes, and.duration_msDatadog metrics, plusbilling.media_reservation_topup.media_blocked, 408 ->upstream_timeout, 502/504 ->upstream_error, 413 ->payload_too_large.deploy/datadog/dev-network-dashboard.jsongains refusal-by-code and p95 fetch-latency panels, so SSRF probing is operator-visible.EIGENINFERENCE_MEDIA_FETCH_*variables are documented indocs/operations/coordinator-deploy.md;ENABLED=trueis in the prod release defaults.Verification
go build ./...,go vet ./...,gofmt -l coordinator(clean)go test ./... -race -count=1incoordinator/— greenIs4In6unmap,DisableCompression, the env kill switch, blocklist canonicalization, the global fetch semaphore, the total deadline, the panic recover, and the projected-size check.TestChatCompletionsDispatchesInlinedMediaBodyasserts the body a provider actually decrypts carries thedata:URI and not the origin URL — the contract that was previously unpinned.docs/threat-model.yamlparsed with PyYAML;deploy/datadog/dev-network-dashboard.jsonvalidated withjq.Rollback
Set
EIGENINFERENCE_MEDIA_FETCH_ENABLED=false. It is read live per request, so an incident does not require a redeploy.Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.